semlith 0.46.0

A fast local vector store for AI agents — index files once, keep it current as you save, and answer questions across all of it in milliseconds without leaving the machine.
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
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
//! SQLite side of the store: file bookkeeping and chunk payloads.
//!
//! The vector index only ever holds `(chunk id, quantized vector)`. Everything
//! a caller actually wants back — the text, the path, the line span — lives
//! here and is looked up by chunk id after the search returns.

use anyhow::Result;
use rusqlite::types::Value;
use rusqlite::{Connection, OptionalExtension, params};
use std::path::Path;

pub(crate) const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (
    k TEXT PRIMARY KEY,
    v TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS files (
    id         INTEGER PRIMARY KEY,
    path       TEXT NOT NULL UNIQUE,
    hash       TEXT NOT NULL,
    bytes      INTEGER NOT NULL,
    indexed_at INTEGER NOT NULL
);

-- AUTOINCREMENT, not a bare rowid: a sharded index routes a chunk id to a
-- shard by the range its file name claims, so SQLite handing a deleted row's
-- id to a new chunk would put one id inside two shards at once.
CREATE TABLE IF NOT EXISTS chunks (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    file_id    INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
    ord        INTEGER NOT NULL,
    start_line INTEGER NOT NULL,
    end_line   INTEGER NOT NULL,
    text       TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS chunks_file_id ON chunks(file_id);
-- How many lines each file spans, for the Stores page, read from the index
-- alone: without it that is every chunk's text off disk, fourteen seconds on
-- a 600 MB store, and the portal draws nothing until it has the answer.
CREATE INDEX IF NOT EXISTS chunks_file_end ON chunks(file_id, end_line);
-- A search asks whether anything is still being embedded, and which of its
-- keyword candidates are; without this that is a scan of every file row.
CREATE INDEX IF NOT EXISTS files_hash ON files(hash);

-- Keyword half of the search. `content='chunks'` means FTS5 keeps only its
-- index, not a second copy of every chunk, so the store barely grows.
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
    text,
    content='chunks',
    content_rowid='id',
    tokenize='unicode61'
);

-- External-content FTS5 does not track its source table by itself. A delete
-- has to hand back the original text so FTS5 can find the terms it needs to
-- remove; this trigger does, and foreign-key cascades fire it too, which is
-- what keeps `delete_file` correct. An insert is indexed by `insert_chunk`
-- itself: the trigger that did it cost twice the row's own insert (#198), and
-- one an older binary recreated is dropped again before every write (see
-- `drop_insert_trigger`).
DROP TRIGGER IF EXISTS chunks_fts_insert;

CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
    INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES('delete', old.id, old.text);
END;

-- Structure half of the store, from 0.12.0. Additive: an older store grows
-- these tables on its next open and they stay empty until something indexes
-- into it, which is why the format version does not move for them. See
-- `docs/compatibility.md`.
--
-- `chunk_id` is nullable on purpose. A symbol's defining line always falls
-- inside some chunk, but a file whose chunks were rewritten between extraction
-- and insertion would otherwise have to fail rather than record the symbol.
CREATE TABLE IF NOT EXISTS symbols (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    file_id    INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
    chunk_id   INTEGER,
    kind       TEXT NOT NULL,
    name       TEXT NOT NULL,
    qualified  TEXT NOT NULL,
    start_line INTEGER NOT NULL,
    end_line   INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS symbols_file_id ON symbols(file_id);
CREATE INDEX IF NOT EXISTS symbols_name ON symbols(name);
-- Search seeds its graph walk from the symbols inside its top chunks. Without
-- this, each seed chunk was a scan of every symbol: on the 879k-chunk benchmark
-- corpus, 1.25M rows read at random, once per seed, on every search.
CREATE INDEX IF NOT EXISTS symbols_chunk_id ON symbols(chunk_id);

-- What a symbol used to be, from 0.23.0. A re-index no longer simply deletes
-- the definitions of a file it is about to rewrite: it copies them here first,
-- stamped with the content hash the file had while they were true, so
-- `semlith symbol` can answer "what did this look like before".
--
-- A separate table rather than a validity column on `symbols`, because
-- `symbols.file_id` cascades from `files` and a re-index deletes the file row.
-- Making the live rows outlive their file would mean loosening that foreign
-- key, which is the one thing keeping the graph from rotting; copying them out
-- keeps the live table exactly as strict as it was.
--
-- Additive and `IF NOT EXISTS`, so `format_version` does not move, for the same
-- reason the 0.12.0 graph tables did not move it: an older binary opens the
-- store, never looks in here, and answers exactly as before. A store written
-- before 0.23.0 has an empty table and starts filling it at its next index
-- pass. See `docs/compatibility.md`.
--
-- Nothing prunes this. History is kept whole in 0.23.0 -- a row per changed
-- symbol per pass -- and a retention knob is a later release's problem, when
-- growth is something measured rather than imagined.
CREATE TABLE IF NOT EXISTS symbols_past (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    path         TEXT NOT NULL,
    kind         TEXT NOT NULL,
    name         TEXT NOT NULL,
    qualified    TEXT NOT NULL,
    start_line   INTEGER NOT NULL,
    end_line     INTEGER NOT NULL,
    -- The content hash of the file version this definition belonged to. What
    -- "invalid at" means: everything after this hash is a different file.
    content_hash TEXT NOT NULL,
    retired_at   INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS symbols_past_name ON symbols_past(name);
-- The change brief asks for one path's oldest retirement since a moment, per
-- changed file. With only the name index that was two scans of the whole
-- table per file, and on a store with 953,601 history rows `semlith report
-- change` ran past 12 minutes without finishing (0.42.0). Additive, so an
-- older binary opens the store and never uses it.
CREATE INDEX IF NOT EXISTS symbols_past_path ON symbols_past(path, retired_at);

-- An edge is owned by the file its *source* is in: `src` is a symbol id, and
-- the cascade above deletes an edge when its source file is re-indexed or
-- forgotten.
--
-- `dst` is a symbol NAME, not an id, and that asymmetry is the point. Ids are
-- reissued every time a file is re-extracted, so an id here would mean that
-- re-indexing `b.rs` silently deleted every edge pointing into it from `a.rs`
-- — the graph would rot from the one operation this release exists to make
-- safe. A name is resolved against `symbols_name` at query time instead, so an
-- edge is always as current as both of its ends, and an edge to something not
-- indexed (a standard-library call) is still recorded and simply resolves to
-- nothing.
--
-- `confidence` is `extracted` when an import in the source file named where the
-- target came from, and `inferred` when the target was matched by bare name.
-- Nothing that displays an edge may present the second as the first.
-- `hint` is what the source text said about where `dst` lives, when it said
-- anything: the module of a scoped call, the receiver of a method call, the
-- object of a qualified one. Nullable, and NULL on every row an older binary
-- wrote, which is why the format version does not move for it. It is a lead,
-- not an address, and `edges_out` treats it as one ranking signal among
-- several — see `resolve`.
-- `line` is where the reference was written in the source file, from 0.16.0.
-- Not where either symbol is defined: "where is X invoked" is a question about
-- this column, and until it existed the closest answer was the enclosing
-- symbol's own start line. Nullable and NULL on every row an older binary
-- wrote, so the format version does not move for it either.
CREATE TABLE IF NOT EXISTS edges (
    src        INTEGER NOT NULL REFERENCES symbols(id) ON DELETE CASCADE,
    dst        TEXT NOT NULL,
    kind       TEXT NOT NULL,
    confidence TEXT NOT NULL,
    hint       TEXT,
    line       INTEGER
);

CREATE INDEX IF NOT EXISTS edges_src ON edges(src);
CREATE INDEX IF NOT EXISTS edges_dst ON edges(dst);

-- What was not indexed, and why, from 0.30.0. One row per file for a secret,
-- a credential file, a policy limit or a file no reader can take, and one row
-- per folder for a pruned generated folder or an ignore rule. Written by every
-- pass that decides not to index something -- `semlith index`, the watcher and
-- the daemon's catch-up alike -- so it outlives the run that found it.
--
-- `matches` is JSON of what the scan found, masked: provider, line, the first
-- and last few characters, confidence and its signals. Never a value.
-- Additive and `IF NOT EXISTS`, so `format_version` does not move.
CREATE TABLE IF NOT EXISTS refusals (
    path       TEXT PRIMARY KEY,
    class      TEXT NOT NULL,
    rule       TEXT NOT NULL,
    matches    TEXT,
    confidence INTEGER,
    files      INTEGER NOT NULL DEFAULT 1,
    first_seen INTEGER NOT NULL,
    last_seen  INTEGER NOT NULL
);

-- A person's decision about one refused file, from 0.30.0. `fingerprints` is
-- JSON of salted blake3 fingerprints of the matches accepted -- never the
-- values -- so a later pass can tell "the same secret the person saw" from "a
-- new one", and refuse the file again for the second. `mode` is `redacted`,
-- `as-is`, or `refused` for a dummy-only file a person chose to keep out.
CREATE TABLE IF NOT EXISTS acceptances (
    path         TEXT PRIMARY KEY,
    class        TEXT NOT NULL,
    mode         TEXT NOT NULL,
    fingerprints TEXT NOT NULL,
    confidence   INTEGER,
    at           INTEGER NOT NULL,
    source       TEXT NOT NULL
);

-- Images, from 0.13.0. One row per indexed image file, with the pixel size the
-- Search and Files pages show in place of a line range. The vector itself is in
-- the store's second index, under `images/`, at CLIP's 512 dimensions.
--
-- Additive and `IF NOT EXISTS`, so `format_version` does not move: an older
-- binary opens the store, never looks in here, and searches its text exactly as
-- before. Same reasoning `docs/compatibility.md` records for the graph tables.
--
-- `id` is AUTOINCREMENT for the same reason chunks are: the id addresses a
-- vector in a sharded index, and SQLite reissuing a deleted row's id would put
-- one id inside two shards at once.
CREATE TABLE IF NOT EXISTS images (
    id      INTEGER PRIMARY KEY AUTOINCREMENT,
    file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
    width   INTEGER NOT NULL,
    height  INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS images_file_id ON images(file_id);

-- The retrieval ledger, from 0.12.0. Additive and empty unless recording is
-- switched on, which it is not by default.
--
-- `prev` is the hash of the row before it and `hash` covers this row's own
-- fields plus `prev`, so the table is a chain: editing or deleting a row
-- breaks every hash after it and `semlith ledger` can say so. That is what
-- makes this an audit record rather than a log file, and it costs one blake3
-- of a short string per query.
--
-- `excerpt_tokens` is what the agent actually read. `whole_file_tokens` is
-- what reading those files whole would have cost — the honest denominator for
-- a savings number, measured rather than claimed.
CREATE TABLE IF NOT EXISTS retrievals (
    id                INTEGER PRIMARY KEY AUTOINCREMENT,
    at                INTEGER NOT NULL,
    client            TEXT NOT NULL,
    query             TEXT NOT NULL,
    hits              INTEGER NOT NULL,
    micros            INTEGER NOT NULL,
    excerpt_tokens    INTEGER NOT NULL,
    whole_file_tokens INTEGER NOT NULL,
    prev              TEXT NOT NULL,
    hash              TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS retrievals_at ON retrievals(at);
"#;

/// A chunk row joined with its file's path — what a search hit resolves to.
#[derive(Debug, Clone)]
pub struct ChunkRow {
    pub id: i64,
    pub path: String,
    pub ord: i64,
    pub start_line: u32,
    pub end_line: u32,
    pub text: String,
}

/// Open a store's database, laying down or upgrading its schema first.
///
/// Retried when SQLite answers busy or a short read. Several connections run
/// this at once as a matter of course — the daemon's writer, its readers, the
/// portal's index route and any CLI — and the first of them on a new store is
/// switching it to WAL while the others read it. The switch answers
/// `SQLITE_BUSY` at once rather than waiting out the busy timeout, which a
/// test with six openers hits within a few rounds. A read of a WAL file that
/// another connection shrank under it comes back short
/// (`SQLITE_IOERR_SHORT_READ`, the 522 in #132), and SQLite's own WAL recovery
/// answers that by retrying; the drive's 522 was never reproduced here, so it
/// is retried on that reasoning rather than on a measurement. Every step below
/// is idempotent, so running it again is safe. Anything else is a real error
/// and is returned.
pub fn open(path: &Path) -> Result<Connection> {
    // ponytail: a fixed two-second window, measured in time rather than
    // attempts because a step that waits out the busy timeout already took
    // five. A store still busy after that is held by something that will not
    // let go, and saying so beats hanging the caller.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
    loop {
        match open_once(path) {
            Err(e) if transient(&e) && std::time::Instant::now() < deadline => {
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            answer => return answer,
        }
    }
}

/// Whether an error from [`open_once`] is a race another connection will
/// finish by itself.
fn transient(e: &anyhow::Error) -> bool {
    matches!(
        e.downcast_ref::<rusqlite::Error>(),
        Some(rusqlite::Error::SqliteFailure(f, _))
            if f.code == rusqlite::ErrorCode::DatabaseBusy
                || f.code == rusqlite::ErrorCode::SchemaChanged
                || f.extended_code == rusqlite::ffi::SQLITE_IOERR_SHORT_READ
    )
}

fn open_once(path: &Path) -> Result<Connection> {
    // A store this process is creating is not one somebody else made.
    let fresh = std::fs::metadata(path).map_or(true, |m| m.len() == 0);
    let db = Connection::open(path)?;
    // A store this home did not create — a `.semlith` beside a corpus, which
    // a clone or a sync can carry — is checked before anything below writes
    // to it (audit S24): once, by SQLite's own quick check, and on every
    // read by its cell-size check, so a crafted file is refused rather than
    // parsed further.
    if !fresh && foreign(path) {
        defensive(&db)?;
        db.pragma_update(None, "cell_size_check", "ON")?;
        check_once(&db, path)?;
    }
    db.pragma_update(None, "journal_mode", "WAL")?;
    db.pragma_update(None, "synchronous", "NORMAL")?;
    db.pragma_update(None, "foreign_keys", "ON")?;
    // A deleted row's bytes are overwritten when its page is freed, not left
    // readable in the file until a vacuum. A store holds whatever a file said,
    // and a file refused after it was indexed -- a secret appeared in it -- is
    // exactly the one whose old text must not linger (#148).
    db.pragma_update(None, "secure_delete", "ON")?;
    // The writer's inserts run once per chunk, symbol and edge, each through
    // the statement cache (#198); the default of 16 is shared with every
    // other cached read.
    db.set_prepared_statement_cache_capacity(64);
    defensive(&db)?;
    db.execute_batch(SCHEMA)?;
    db.execute_batch(GLOB_INDEX)?;
    add_columns(&db)?;
    check_format(&db)?;
    backfill_fts(&db)?;
    // The keyword index's own secure delete (S10), written once. Best effort
    // here: a reader that opens a store while its writer is creating it must
    // not fail on a setting it does not need, and the scrub that does need it
    // sets it under the writer (`secure_delete_fts`).
    let _ = secure_delete_fts(&db);
    // Everything above is the schema this binary needs in place before the
    // store is usable at all; from here the connection writes only when a
    // writer asks.
    read_only(&db, true)?;
    Ok(db)
}

/// Whether this store file lies outside the semlith home.
fn foreign(path: &Path) -> bool {
    match crate::home::home_or_error() {
        Ok(home) => !crate::canonical(path).starts_with(crate::canonical(&home)),
        Err(_) => true,
    }
}

/// The marker a passed check leaves beside the store.
const CHECKED: &str = ".integrity-checked";

/// SQLite's quick check, the first time this store is opened here.
// ponytail: once per store, not per open, as decided for 0.41.0; a store
// replaced after its check is trusted on the marker. Hash the file into the
// marker if that ever matters.
fn check_once(db: &Connection, path: &Path) -> Result<()> {
    let Some(dir) = path.parent() else {
        return Ok(());
    };
    let marker = dir.join(CHECKED);
    if marker.exists() {
        return Ok(());
    }
    let verdict: String = db.query_row("PRAGMA quick_check", [], |r| r.get(0))?;
    if verdict != "ok" {
        anyhow::bail!(
            "{} failed SQLite's integrity check ({verdict}), so semlith will not open it: \
             it is damaged, or was made to attack whatever reads it. Index the corpus \
             again into a new store.",
            path.display()
        );
    }
    let _ = crate::home::write_private(&marker, b"quick_check ok\n");
    Ok(())
}

/// Treat the file as data rather than as a program.
///
/// A SQLite file is a schema as well as rows, and a schema can carry views,
/// triggers and generated columns that run when the database is merely opened
/// or read. semlith opens store files it did not necessarily write — a
/// `.semlith` that a user has trusted arrived from somewhere, and `--store`
/// opens anything the user names — so both settings are on for every
/// connection:
///
/// - `trusted_schema=OFF` stops a view or a trigger calling the functions
///   SQLite marks as unsafe for a schema it does not trust;
/// - `SQLITE_DBCONFIG_DEFENSIVE` refuses writes to shadow tables and to
///   `sqlite_schema`, which is how a corrupted or crafted FTS5 index turns a
///   read into something else.
///
/// Both are cheap and neither affects a query semlith itself issues, which is
/// what `tests/measure.rs` is there to keep true.
fn defensive(db: &Connection) -> Result<()> {
    db.pragma_update(None, "trusted_schema", "OFF")?;
    db.set_db_config(rusqlite::config::DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)?;
    Ok(())
}

/// Make this connection refuse writes until a writer says otherwise.
///
/// `query_only` rather than `SQLITE_OPEN_READ_ONLY`, because semlith opens one
/// connection per store and writes through the same handle it reads through:
/// a read-only open would mean two connections per store and a second answer to
/// "who holds the writer", which is the one thing the store's design keeps
/// singular. The property is the same from the file's point of view — a
/// connection in this state cannot write, whatever it is asked to do — and it
/// is lifted only by [`Writing`], which the three write paths take.
pub fn read_only(db: &Connection, on: bool) -> Result<()> {
    db.pragma_update(None, "query_only", if on { "ON" } else { "OFF" })?;
    Ok(())
}

/// Permission to write, given back when it goes out of scope.
///
/// Taken by the three methods that write — indexing, forgetting, and recording
/// a retrieval in the ledger — so every other path through the store is a path
/// SQLite itself will refuse to write from.
pub struct Writing<'a>(&'a Connection);

impl<'a> Writing<'a> {
    pub fn begin(db: &'a Connection) -> Result<Self> {
        read_only(db, false)?;
        Ok(Self(db))
    }
}

impl Drop for Writing<'_> {
    fn drop(&mut self) {
        // Best effort on purpose: a connection that cannot be put back into
        // read-only mode is one whose next statement will fail anyway, and a
        // panic in a destructor would replace a clear error with a confusing
        // one.
        let _ = read_only(self.0, true);
    }
}

/// The store layout this binary understands.
///
/// Written into a store when one is created, and absent from every store
/// written before 0.6.0 — which is what makes 1 the right reading of an absent
/// key rather than an unknown.
///
/// 1 is a single `index.tv`. 2 is a directory of shards, written by 0.7.0 and
/// later; see [`crate::index`]. 3 is a store written by 0.22.0 and later,
/// whose Markdown chunks are cut at their headings and carry the heading path
/// as embedding context. 4 is a store written by 0.25.0 and later, whose code
/// chunks carry the definition they sit inside — its signature and the first
/// line of its doc comment — as embedding context. 5 is a store 0.39.0 or
/// later has written to: its vector files may be turbovec's v8, which a binary
/// before 0.39.0 cannot load. A binary understands every format up to its own,
/// so this one reads all five and creates the newest.
pub const FORMAT_VERSION: u32 = 5;

/// The first format whose vector files may be turbovec's v8.
///
/// Nothing about the rows, the chunks or the vectors' values changes: turbovec
/// 1.1 reads a v7 file as it is and writes it back as v8 the next time that
/// file is saved, so a store moves shard by shard rather than in one pass.
/// What changes is which binaries can read it — turbovec 1.0 refuses a v8 file
/// as "not a turbovec index" — so the format number moves before the first
/// write, and an older semlith refuses the whole store with its own message
/// instead of failing on whichever shard it loads first. See
/// [`mark_vector_format`].
pub const TURBOVEC_V8: u32 = 5;

/// The first format that keeps its vectors in shards.
pub const SHARDED_FORMAT: u32 = 2;

/// The first format whose code chunks embed the definition they sit inside.
///
/// A store below this holds code chunks embedded from their own text alone.
/// They still answer — the row, the span and the bytes are identical, and only
/// what the model was shown differs — but a store half embedded one way and
/// half the other ranks its own files against each other unevenly, so the
/// first full index pass under 0.25.0 re-embeds everything it walks. `semlith
/// stats` says which rule a store is on until it has.
pub const CODE_CONTEXT: u32 = 4;

/// The first format whose Markdown chunks are cut at their headings.
///
/// A store below this holds fixed windows and still answers: a chunk is a chunk
/// whichever rule cut it, and nothing about the row or the vector changes. What
/// changes is where the boundaries fall, so a store that is half one rule and
/// half the other would rank its own files against each other unevenly — which
/// is why the first full index pass under 0.22.0 re-chunks everything it walks
/// rather than waiting for each file to be edited. `semlith stats` says which
/// rule a store is on until it has.
pub const DEFINITION_CHUNKS: u32 = 3;

/// Which chunking rule this store's chunks were cut by, in the words `stats`
/// and the portal print.
pub fn chunking(db: &Connection) -> Result<&'static str> {
    Ok(match format(db)? {
        v if v >= CODE_CONTEXT => "headings, and code with its definition",
        v if v >= DEFINITION_CHUNKS => {
            "headings; code carries no definition until it is re-indexed"
        }
        _ => "fixed windows",
    })
}

/// Which layout this store's vectors are in.
///
/// An absent key is format 1: every store written before 0.6.0 has no key, and
/// reading it as anything else would refuse the whole installed base.
pub fn format(db: &Connection) -> Result<u32> {
    Ok(get_meta(db, FORMAT_KEY)?
        .and_then(|v| v.parse().ok())
        .unwrap_or(1))
}

pub const FORMAT_KEY: &str = "format_version";

/// Move a format-4 store to [`TURBOVEC_V8`] before this binary writes to it.
///
/// Called where every write starts, because any write may save a vector file
/// and a saved file is v8. Only format 4 moves here: a store below it re-chunks
/// on its first full pass and is stamped with the current format when that
/// pass ends, and stamping it now would skip that pass. A format-1 store has no
/// key and a single `index.tv`; stamping it would make it read as sharded.
pub fn mark_vector_format(db: &Connection) -> Result<()> {
    if format(db)? == CODE_CONTEXT {
        set_meta(db, FORMAT_KEY, &TURBOVEC_V8.to_string())?;
    }
    Ok(())
}

/// Meta key present while a store's first import is under way (#210).
///
/// Set by the pass that finds the store empty and removed by the pass that
/// ends with nothing left pending, so a first import the cloud runs in slices
/// of a few hundred files is one first import, not one slice of it.
pub const FIRST_IMPORT_KEY: &str = "first_import";

/// Meta key holding the keyword index's `automerge` setting from before a
/// first import held it at 0: a number, or `default` when the store had none.
const AUTOMERGE_HELD_KEY: &str = "fts_automerge_held";

/// FTS5's own `automerge` when its config table has no row for it.
const AUTOMERGE_DEFAULT: i64 = 4;

/// Whether this pass is part of a store's first import, starting one when the
/// store is empty.
pub fn first_import(db: &Connection, empty: bool) -> Result<bool> {
    if get_meta(db, FIRST_IMPORT_KEY)?.is_some() {
        return Ok(true);
    }
    if empty {
        set_meta(db, FIRST_IMPORT_KEY, "1")?;
    }
    Ok(empty)
}

/// The first import ran to its end: later passes write as any other does.
pub fn end_first_import(db: &Connection) -> Result<()> {
    db.execute("DELETE FROM meta WHERE k = ?1", params![FIRST_IMPORT_KEY])?;
    Ok(())
}

/// Stop FTS5 merging segments while a first import writes (#210).
///
/// Every commit flushes the keyword index's pending terms into a new segment,
/// and with `automerge` on FTS5 merges segments as part of that commit: about
/// a sixth of a remote-GPU first import's commit time. Held at 0 a merge waits
/// until `crisismerge` segments pile up at one level, which still bounds what
/// a search reads. The setting persists in the store, so what it was is kept
/// in `meta` first and [`release_automerge`] puts it back — after the pass,
/// and at the start of the next write if a crash came between.
pub fn hold_automerge(db: &Connection) -> Result<()> {
    if get_meta(db, AUTOMERGE_HELD_KEY)?.is_some() {
        return Ok(());
    }
    let was: Option<i64> = db
        .query_row(
            "SELECT v FROM chunks_fts_config WHERE k = 'automerge'",
            [],
            |r| r.get(0),
        )
        .optional()?;
    set_meta(
        db,
        AUTOMERGE_HELD_KEY,
        &was.map_or_else(|| "default".to_string(), |n| n.to_string()),
    )?;
    db.execute(
        "INSERT INTO chunks_fts(chunks_fts, rank) VALUES('automerge', 0)",
        [],
    )?;
    Ok(())
}

/// Put back the `automerge` setting [`hold_automerge`] recorded, if any.
///
/// A store that had no row gets none back: the value is set through FTS5 so
/// every connection's cached copy is the default again, then the row is
/// removed with the connection's defensive mode lifted for that one statement,
/// since the config table is FTS5's and refuses ordinary writes.
pub fn release_automerge(db: &Connection) -> Result<()> {
    let Some(was) = get_meta(db, AUTOMERGE_HELD_KEY)? else {
        return Ok(());
    };
    let value = was.parse().unwrap_or(AUTOMERGE_DEFAULT);
    db.execute(
        "INSERT INTO chunks_fts(chunks_fts, rank) VALUES('automerge', ?1)",
        params![value],
    )?;
    if was == "default" {
        use rusqlite::config::DbConfig::SQLITE_DBCONFIG_DEFENSIVE;
        db.set_db_config(SQLITE_DBCONFIG_DEFENSIVE, false)?;
        let removed = db.execute("DELETE FROM chunks_fts_config WHERE k = 'automerge'", []);
        db.set_db_config(SQLITE_DBCONFIG_DEFENSIVE, true)?;
        removed?;
    }
    db.execute("DELETE FROM meta WHERE k = ?1", params![AUTOMERGE_HELD_KEY])?;
    Ok(())
}

/// Refuse a store a later semlith wrote, rather than misreading it.
///
/// Nothing is written here. A store from before this key existed is format 1
/// and stays exactly as it is: a read command that quietly rewrote the store
/// it was only asked to search would be a worse surprise than the one this
/// guards against.
fn check_format(db: &Connection) -> Result<()> {
    let Some(recorded) = get_meta(db, FORMAT_KEY)? else {
        return Ok(());
    };
    let found: u32 = recorded.parse().map_err(|_| {
        anyhow::anyhow!("store records {FORMAT_KEY} {recorded:?}, which is not a version number")
    })?;
    if found > FORMAT_VERSION {
        anyhow::bail!(
            "store is format {found}, and semlith {} understands format {FORMAT_VERSION}; \
             upgrade semlith to read this store",
            env!("CARGO_PKG_VERSION"),
        );
    }
    Ok(())
}

/// Meta key recording that the keyword index has been built for this store.
///
/// Counting rows in `chunks_fts` cannot answer this. An external-content FTS5
/// table reads through to its content table, so `COUNT(*)` returns the number
/// of chunks whether or not a single term has been indexed — a guard built on
/// it would skip the backfill on exactly the stores that need it.
const FTS_BUILT: &str = "fts_built";

/// Populate the keyword index for a store written before it existed.
///
/// A 0.1.0 store has chunks but no FTS index, and the triggers only fire on new
/// writes. Rebuilding from the text already in SQLite costs no embedding and
/// leaves the vectors untouched.
/// Columns added to tables that already exist in a store written by an older
/// binary.
///
/// `CREATE TABLE IF NOT EXISTS` is how every table here arrives, and it does
/// nothing at all to a table that is already there — so a column added to the
/// schema above reaches a fresh store and no other. This is the other half:
/// one `ALTER TABLE ADD COLUMN` per column, run on every open, skipped when
/// the column is present.
///
/// Every column here must be nullable with no default, which is what makes the
/// operation an O(1) catalogue edit rather than a table rewrite, and what lets
/// an older binary keep reading the store afterwards: it selects by name and
/// never sees them. That is the whole reason `format_version` does not move —
/// the same reasoning `docs/compatibility.md` records for the graph tables.
fn add_columns(db: &Connection) -> Result<()> {
    const ADDITIONS: [(&str, &str, &str); 24] = [
        ("edges", "hint", "TEXT"),
        // 0.16.0: the line the reference was written on.
        ("edges", "line", "INTEGER"),
        // The ledger's 0.15.0 columns. `session` groups the retrievals of one
        // agent conversation, `tool` says which tool was asked, `stale_hits`
        // counts the answers that came from a file edited since it was
        // indexed, and `tokenizer` names what counted the two token figures so
        // rows counted two different ways are never summed together.
        ("retrievals", "session", "TEXT"),
        ("retrievals", "tool", "TEXT"),
        ("retrievals", "stale_hits", "INTEGER"),
        ("retrievals", "tokenizer", "TEXT"),
        // 0.20.2: the id one retrieval shares across every store that
        // contributed to it. A search over six stores used to write six rows
        // and the Ledger page counted six retrievals, so every figure on it
        // scaled with how many stores happened to be open. The rows stay per
        // store — that is what keeps each store's chain verifiable and its
        // token counts its own — and this is what makes them one retrieval
        // again when they are counted.
        ("retrievals", "query_id", "TEXT"),
        // 0.33.0: the client's own version, beside the name `clientid` resolved.
        ("retrievals", "client_version", "TEXT"),
        // 0.34.0: the model request that made the call, read afterwards from
        // the client's own session log (`crate::usage`), and what it cost.
        // Outside the chain like `client_version`: they are filled in after
        // the row is written, which a hashed column could never allow.
        // `usage_source` is the log they came from, or why there is none;
        // NULL means not looked for yet.
        ("retrievals", "model", "TEXT"),
        ("retrievals", "input_tokens", "INTEGER"),
        ("retrievals", "output_tokens", "INTEGER"),
        ("retrievals", "cache_read_tokens", "INTEGER"),
        ("retrievals", "cache_write_tokens", "INTEGER"),
        ("retrievals", "reasoning_tokens", "INTEGER"),
        ("retrievals", "cost_usd", "REAL"),
        ("retrievals", "cost_source", "TEXT"),
        ("retrievals", "usage_source", "TEXT"),
        // 0.37.0: when ledger sync sent the row to the org's ledger, in unix
        // seconds; NULL is not sent. Outside the chain like the usage
        // columns: it is written after the row, which a hashed column could
        // never allow.
        ("retrievals", "synced_at", "INTEGER"),
        // 0.25.0: what the parser made of this file — "parsed", "timeout" or
        // "none" for a language that carries no grammar. Without it a file
        // with no definitions and a file the parser gave up on look the same
        // in the per-language coverage table, which is the one question that
        // table exists to answer.
        ("files", "graph", "TEXT"),
        // 0.34.0: the file's units — PDF pages, slides, non-empty spreadsheet
        // cells or notebook cells, by its format (`chunk::COUNTED`). NULL is
        // "not counted": a format with no unit, or a file an older binary
        // wrote, which the next index pass counts without re-embedding it.
        ("files", "units", "INTEGER"),
        // 0.40.0: the file's mtime in nanoseconds when it was read, which is
        // what freshness compares now (see `Stamp::fresh`). NULL on a row an
        // older binary wrote; an older binary ignores the column.
        ("files", "read_mtime", "INTEGER"),
        // 0.42.0: what the whole-file side of a row was counted from —
        // `bytes` (the file's size on disk, every row before 0.42.0, NULL
        // here) or `text` (the text a reader extracted, for a PDF, an Office
        // file, an image). The Ledger says which, row by row.
        ("retrievals", "whole_basis", "TEXT"),
        // 0.42.0: which chain formula hashed the row. NULL is the 0.15.0/0.41.0
        // formula (or 0.14.0's, told apart by `tool`), 2 is chain v2, which
        // covers every column a figure reads.
        ("retrievals", "chain", "INTEGER"),
        // 0.42.0: the hash over a v2 row's late columns (usage, synced_at),
        // rewritten whenever they are, so a late column cannot change without
        // the verify noticing.
        ("retrievals", "seal", "TEXT"),
    ];
    for (table, column, kind) in ADDITIONS {
        if has_column(db, table, column)? {
            continue;
        }
        // Asked again under the write lock. Two connections opening the same
        // new store both see the column missing, and the second `ALTER` then
        // fails the whole open with "duplicate column name" (#132).
        let tx =
            rusqlite::Transaction::new_unchecked(db, rusqlite::TransactionBehavior::Immediate)?;
        if !has_column(&tx, table, column)? {
            tx.execute_batch(&format!("ALTER TABLE {table} ADD COLUMN {column} {kind};"))?;
        }
        tx.commit()?;
    }
    Ok(())
}

fn has_column(db: &Connection, table: &str, column: &str) -> Result<bool> {
    let mut stmt = db.prepare(&format!("PRAGMA table_info({table})"))?;
    let mut rows = stmt.query([])?;
    while let Some(row) = rows.next()? {
        let name: String = row.get(1)?;
        if name == column {
            return Ok(true);
        }
    }
    Ok(false)
}

fn backfill_fts(db: &Connection) -> Result<()> {
    if get_meta(db, FTS_BUILT)?.is_some() {
        return Ok(());
    }
    // Asked again under the write lock, as in `add_columns`: a second
    // connection opening the store at the same moment would rebuild it again.
    let tx = rusqlite::Transaction::new_unchecked(db, rusqlite::TransactionBehavior::Immediate)?;
    if get_meta(&tx, FTS_BUILT)?.is_none() {
        // FTS5's own command for external content: discard the index and
        // rebuild it from the content table.
        tx.execute_batch("INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild');")?;
        set_meta(&tx, FTS_BUILT, "1")?;
    }
    tx.commit()?;
    Ok(())
}

/// `AND`ed groups of `OR`ed `GLOB` patterns as a SQL fragment, plus the values
/// to bind. An empty group list yields `1` — a predicate that selects
/// everything, so callers need no special case.
///
/// Patterns are matched against `lower(files.path)`: filtering is
/// case-insensitive, because `README.MD` and `readme.md` are the same file to
/// anyone typing `--ext md`, and no filesystem this runs on treats a path's
/// case as load-bearing.
fn glob_predicate(groups: &[Vec<String>]) -> (String, Vec<String>) {
    let mut binds = Vec::new();
    let mut clauses = Vec::new();
    for group in groups {
        // A pattern marked with a leading `!` by `filter::anchor` excludes.
        // Exclusions apply after the inclusions of their own kind, which is
        // what keeps them inside this group rather than becoming a group of
        // their own: `--path 'src/**' --path '!src/vendor/**'` is one
        // requirement, not two intersecting ones.
        let (excluded, included): (Vec<&String>, Vec<&String>) =
            group.iter().partition(|p| p.starts_with('!'));
        let placeholder = format!("{GLOB_PATH} GLOB ?");
        // Binds are positional, so they are pushed in the order the clause
        // below writes their placeholders — inclusions first — rather than in
        // the order the user typed them.
        let ors = included
            .into_iter()
            .map(|p| match literal_dir(p) {
                // The range is what the index answers; the GLOB stays, so the
                // rows are exactly the pattern's.
                Some((from, to)) => {
                    binds.extend([from, to, p.clone()]);
                    format!("({GLOB_PATH} >= ? AND {GLOB_PATH} < ? AND {placeholder})")
                }
                None => {
                    binds.push(p.clone());
                    placeholder.clone()
                }
            })
            .collect::<Vec<_>>()
            .join(" OR ");
        let nots = vec![placeholder; excluded.len()].join(" OR ");
        binds.extend(excluded.into_iter().map(|p| p[1..].to_string()));

        clauses.push(match (ors.is_empty(), nots.is_empty()) {
            (true, true) => continue,
            (false, true) => format!("({ors})"),
            // Exclusions with nothing beside them mean everything except.
            (true, false) => format!("(NOT ({nots}))"),
            (false, false) => format!("(({ors}) AND NOT ({nots}))"),
        });
    }
    if clauses.is_empty() {
        return ("1".to_string(), binds);
    }
    (clauses.join(" AND "), binds)
}

/// Run `work` over `conns`, interrupting their queries once `limit` passes.
///
/// For the reads a person asks for on a store of any size -- the Graph page's
/// drawing over every edge of a 879k-chunk store did not answer in twelve
/// minutes and held a worker the whole time (#173). An interrupted query fails
/// with SQLite's "interrupted", which [`is_interrupted`] recognises, so the
/// caller can say the request was too large rather than that it broke.
pub fn bounded<T>(
    conns: &[&Connection],
    limit: std::time::Duration,
    work: impl FnOnce() -> Result<T>,
) -> Result<T> {
    let handles: Vec<rusqlite::InterruptHandle> =
        conns.iter().map(|c| c.get_interrupt_handle()).collect();
    let (done, wait) = std::sync::mpsc::channel::<()>();
    let timer = std::thread::spawn(move || {
        if wait.recv_timeout(limit) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) {
            for handle in &handles {
                handle.interrupt();
            }
        }
    });
    let out = work();
    let _ = done.send(());
    let _ = timer.join();
    out
}

/// Whether an error is a query [`bounded`] interrupted.
pub fn is_interrupted(e: &anyhow::Error) -> bool {
    e.chain().any(|cause| {
        cause
            .downcast_ref::<rusqlite::Error>()
            .and_then(rusqlite::Error::sqlite_error_code)
            == Some(rusqlite::ErrorCode::OperationInterrupted)
    })
}

/// The highest chunk id, or 0 for none. One step down the rowid b-tree.
pub fn newest_chunk(db: &Connection) -> Result<i64> {
    Ok(db.query_row("SELECT COALESCE(MAX(id), 0) FROM chunks", [], |r| r.get(0))?)
}

/// Ids of every chunk whose file matches `groups`.
///
/// This is the single source of the subset. The vector index gets these ids as
/// an allowlist and [`keyword_search`] applies the same predicate, so the two
/// halves of a hybrid search can never rank a chunk the other was forbidden to
/// see.
pub fn filtered_chunk_ids(db: &Connection, groups: &[Vec<String>]) -> Result<Vec<u64>> {
    let (predicate, binds) = glob_predicate(groups);
    // Files first, then their chunks through `chunks_file_id`. A join planned
    // the other way scanned every chunk and tested its file's path, 250-680 ms
    // on the 879k-chunk corpus; this is 24-48 ms for the same rows (#170).
    let sql = format!(
        "SELECT id FROM chunks WHERE file_id IN (SELECT f.id FROM files f WHERE {predicate})"
    );
    let mut stmt = db.prepare(&sql)?;
    let args = binds.into_iter().map(Value::Text);
    let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| r.get::<_, i64>(0))?;
    Ok(rows
        .collect::<Result<Vec<i64>, _>>()?
        .into_iter()
        .map(|i| i as u64)
        .collect())
}

/// How many indexed files `groups` selects.
///
/// Zero means the filter itself is wrong — a typo in a glob, a subsystem that
/// was never indexed — which is a different thing to tell a user than "the
/// corpus does not contain this".
pub fn matching_files(db: &Connection, groups: &[Vec<String>]) -> Result<i64> {
    let (predicate, binds) = glob_predicate(groups);
    let sql = format!("SELECT COUNT(*) FROM files f WHERE {predicate}");
    let args = binds.into_iter().map(Value::Text);
    Ok(db.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0))?)
}

/// The keyword statement for a search with no filter.
///
/// Byte-identical to the one 0.2.0 issued: no join to `chunks` and `files`, so
/// a query that uses no filter pays nothing for the filtering feature. A test
/// pins the text, because the cheapest way to regress the common path is to
/// "tidy" the two branches into one.
const UNFILTERED_SQL: &str =
    "SELECT rowid FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?";

/// Chunk ids matching `query` as keywords, best first, restricted to files
/// matching `groups`.
///
/// The query is reduced to bare terms before it reaches FTS5. A raw query would
/// be parsed as FTS5 syntax, where a stray quote or `*` is a syntax error and a
/// bare `AND` is an operator — a search for "index AND search" would silently
/// mean something the user did not type, and a search for `foo(` would fail
/// outright.
/// English words too common to say what a chunk is about.
const STOPWORDS: &[&str] = &[
    "a", "an", "and", "are", "as", "at", "be", "but", "by", "can", "do", "does", "for", "from",
    "has", "have", "how", "i", "if", "in", "into", "is", "it", "its", "of", "on", "or", "not",
    "no", "so", "that", "the", "their", "then", "there", "these", "this", "to", "was", "were",
    "what", "when", "where", "which", "who", "why", "will", "with", "you", "your", "we", "our",
    "they", "them", "he", "she", "my", "me", "than", "also", "any", "all",
];

pub fn keyword_search(
    db: &Connection,
    query: &str,
    limit: usize,
    groups: &[Vec<String>],
) -> Result<Vec<u64>> {
    let Some(match_expr) = match_expr(query) else {
        return Ok(Vec::new());
    };
    if groups.is_empty() {
        let mut stmt = db.prepare(UNFILTERED_SQL)?;
        let rows = stmt.query_map(params![match_expr, limit as i64], |r| r.get::<_, i64>(0))?;
        return Ok(rows
            .collect::<Result<Vec<i64>, _>>()?
            .into_iter()
            .map(|i| i as u64)
            .collect());
    }
    let allowed: std::collections::HashSet<u64> =
        filtered_chunk_ids(db, groups)?.into_iter().collect();
    keyword_search_within(db, query, limit, &allowed)
}

/// The FTS5 expression for `query`: its words, quoted, OR-ed. `None` when it
/// has no word at all.
fn match_expr(query: &str) -> Option<String> {
    let words: Vec<&str> = query
        .split(|c: char| !c.is_alphanumeric() && c != '_')
        .filter(|t| !t.is_empty())
        .collect();
    // Stopwords out of the MATCH: an OR over "the" and "of" asks FTS5 to rank
    // nearly every chunk of a large store. On the 879k-chunk corpus that took
    // the keyword list from 884 to 226 ms at the median, and the 727-question
    // benchmark scored the same either way (408 against 407 scoped, 340 and
    // 340 unscoped, development split). A query of nothing but stopwords keeps
    // them all, so it still finds something.
    let content: Vec<&str> = words
        .iter()
        .copied()
        .filter(|w| !STOPWORDS.contains(&w.to_ascii_lowercase().as_str()))
        .collect();
    let kept = if content.is_empty() { &words } else { &content };
    let terms: Vec<String> = kept.iter().map(|t| format!("\"{t}\"")).collect();
    (!terms.is_empty()).then(|| terms.join(" OR "))
}

/// The keyword list inside a set of chunk ids, for a filtered search that has
/// the set already.
///
/// Every match is read with its rank and the set is applied here. Joining the
/// matches to their files in SQL stopped FTS5 applying its own `LIMIT`, so it
/// ranked and joined every match: 81-688 ms on the 879k-chunk corpus against
/// 14 ms unfiltered, which is most of why a scoped search was slower than an
/// unscoped one (#170). Reading the matches is the 14 ms, the filter well
/// under one, and the order is the same.
pub fn keyword_search_within(
    db: &Connection,
    query: &str,
    limit: usize,
    allowed: &std::collections::HashSet<u64>,
) -> Result<Vec<u64>> {
    let Some(match_expr) = match_expr(query) else {
        return Ok(Vec::new());
    };
    let mut stmt = db.prepare("SELECT rowid, rank FROM chunks_fts WHERE chunks_fts MATCH ?")?;
    let rows = stmt.query_map(params![match_expr], |r| {
        Ok((r.get::<_, i64>(0)? as u64, r.get::<_, f64>(1)?))
    })?;
    let mut kept: Vec<(u64, f64)> = Vec::new();
    for row in rows {
        let (id, rank) = row?;
        if allowed.contains(&id) {
            kept.push((id, rank));
        }
    }
    // FTS5's rank is ascending-is-better; ties by id, as the index gives them.
    kept.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
    Ok(kept.into_iter().take(limit).map(|(id, _)| id).collect())
}

pub fn get_meta(db: &Connection, k: &str) -> Result<Option<String>> {
    Ok(db
        .query_row("SELECT v FROM meta WHERE k = ?1", params![k], |r| r.get(0))
        .optional()?)
}

pub fn set_meta(db: &Connection, k: &str, v: &str) -> Result<()> {
    db.execute(
        "INSERT INTO meta (k, v) VALUES (?1, ?2)
         ON CONFLICT(k) DO UPDATE SET v = excluded.v",
        params![k, v],
    )?;
    Ok(())
}

/// Content hash recorded for `path`, if we have indexed it before.
pub fn file_hash(db: &Connection, path: &str) -> Result<Option<String>> {
    Ok(db
        .query_row(
            "SELECT hash FROM files WHERE path = ?1",
            params![path],
            |r| r.get(0),
        )
        .optional()?)
}

/// Every stored path's recorded hash, read once for a whole index pass so its
/// prepare stage can tell an unchanged file without the database.
pub fn all_hashes(db: &Connection) -> Result<std::collections::HashMap<String, String>> {
    let mut stmt = db.prepare("SELECT path, hash FROM files")?;
    let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Drop a file and its chunks, returning the chunk ids so the caller can
/// evict them from the vector index too.
/// The ids of a file's chunks.
pub fn chunk_ids_of(db: &Connection, path: &str) -> Result<Vec<u64>> {
    let mut stmt = db.prepare_cached(
        "SELECT c.id FROM chunks c JOIN files f ON f.id = c.file_id WHERE f.path = ?1",
    )?;
    let rows = stmt.query_map(params![path], |r| r.get::<_, i64>(0))?;
    Ok(rows
        .collect::<Result<Vec<i64>, _>>()?
        .into_iter()
        .map(|i| i as u64)
        .collect())
}

pub fn delete_file(db: &Connection, path: &str, now: i64) -> Result<Vec<u64>> {
    retire_symbols(db, path, now)?;
    delete_file_unretired(db, path)
}

/// [`delete_file`] without keeping the file's definitions as history: for a
/// stopped run's undo, whose files were never the store's to remember.
pub fn delete_file_unretired(db: &Connection, path: &str) -> Result<Vec<u64>> {
    let ids: Vec<u64> = {
        let mut stmt = db.prepare_cached(
            "SELECT c.id FROM chunks c JOIN files f ON f.id = c.file_id WHERE f.path = ?1",
        )?;
        let rows = stmt.query_map(params![path], |r| r.get::<_, i64>(0))?;
        rows.collect::<Result<Vec<i64>, _>>()?
            .into_iter()
            .map(|i| i as u64)
            .collect()
    };
    db.prepare_cached("DELETE FROM files WHERE path = ?1")?
        .execute(params![path])?;
    Ok(ids)
}

/// Copy a file's current definitions into `symbols_past` before the file row
/// takes them with it.
///
/// Stamped with the hash the file has right now, which is the hash they were
/// extracted from: `delete_file` runs before the new version is inserted, so
/// `files.hash` here is still the old content's.
///
/// A file with no symbols copies nothing, and a store opened by a binary that
/// never wrote this table simply has none to copy.
fn retire_symbols(db: &Connection, path: &str, now: i64) -> Result<()> {
    db.prepare_cached(
        "INSERT INTO symbols_past
             (path, kind, name, qualified, start_line, end_line, content_hash, retired_at)
         SELECT f.path, s.kind, s.name, s.qualified, s.start_line, s.end_line, f.hash, ?2
         FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE f.path = ?1",
    )?
    .execute(params![path, now])?;
    Ok(())
}

/// What a symbol used to be, newest first.
///
/// The live definitions are what `symbols_named` answers; these are the ones a
/// re-index replaced, each with the content hash of the file version it was
/// true for. An empty list means the store has never seen this name change --
/// or has never re-indexed since 0.23.0, which is the same answer from the
/// outside and is why `semlith stats` says whether the store keeps history.
pub fn symbols_past_named(db: &Connection, name: &str, limit: usize) -> Result<Vec<PastSymbol>> {
    let mut stmt = db.prepare(
        "SELECT path, kind, name, qualified, start_line, end_line, content_hash, retired_at
         FROM symbols_past WHERE name = ?1 ORDER BY retired_at DESC, id DESC LIMIT ?2",
    )?;
    let rows = stmt.query_map(params![name, limit as i64], |r| {
        Ok(PastSymbol {
            path: r.get(0)?,
            kind: r.get(1)?,
            name: r.get(2)?,
            qualified: r.get(3)?,
            start_line: r.get(4)?,
            end_line: r.get(5)?,
            content_hash: r.get(6)?,
            retired_at: r.get(7)?,
            store: None,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// How many definitions this store has retired, over all names.
pub fn symbols_past_count(db: &Connection) -> Result<i64> {
    Ok(db.query_row("SELECT COUNT(*) FROM symbols_past", [], |r| r.get(0))?)
}

/// Drop the definitions retired before `before` (unix seconds). The retention
/// is the caller's; see `compact`.
pub fn prune_history(db: &Connection, before: i64) -> Result<usize> {
    Ok(db.execute(
        "DELETE FROM symbols_past WHERE retired_at < ?1",
        params![before],
    )?)
}

/// How many definitions were retired before `before`.
pub fn history_count_before(db: &Connection, before: i64) -> Result<i64> {
    Ok(db.query_row(
        "SELECT COUNT(*) FROM symbols_past WHERE retired_at < ?1",
        params![before],
        |r| r.get(0),
    )?)
}

/// Every chunk row, durable or not: what the sidecar can hold a record for.
pub fn chunk_count(db: &Connection) -> Result<i64> {
    Ok(db.query_row("SELECT COUNT(*) FROM chunks", [], |r| r.get(0))?)
}

/// Roughly what the definitions retired before `before` take: their text plus
/// a row's fixed cost. An estimate for `stats`, not an accounting — SQLite
/// packs rows into pages and the count cannot see that.
pub fn history_bytes_before(db: &Connection, before: i64) -> Result<i64> {
    Ok(db.query_row(
        "SELECT COALESCE(SUM(LENGTH(path) + LENGTH(kind) + LENGTH(name) + LENGTH(qualified)
                             + LENGTH(content_hash) + 32), 0)
         FROM symbols_past WHERE retired_at < ?1",
        params![before],
        |r| r.get(0),
    )?)
}

/// Pages SQLite holds free inside the file, in bytes: what a vacuum gives back
/// before anything else is dropped.
pub fn free_bytes(db: &Connection) -> Result<i64> {
    let pages: i64 = db.query_row("PRAGMA freelist_count", [], |r| r.get(0))?;
    let size: i64 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
    Ok(pages * size)
}

/// Give the database's dead pages back to the filesystem.
///
/// FTS5 keeps a deleted chunk's terms in its segments until they are merged,
/// so the keyword index is optimised first; then the file is rebuilt, and the
/// write-ahead log, which still holds the pages as they were, is checkpointed
/// and truncated. A reader still inside a snapshot keeps the log from being
/// truncated, and that is not an error: the next checkpoint does it.
///
/// The connection must be writable and outside any transaction.
pub fn reclaim(db: &Connection) -> Result<()> {
    db.execute("INSERT INTO chunks_fts(chunks_fts) VALUES('optimize')", [])?;
    db.execute_batch("VACUUM")?;
    db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
    Ok(())
}

/// A definition a re-index replaced.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PastSymbol {
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    pub kind: String,
    pub name: String,
    pub qualified: String,
    pub start_line: u32,
    pub end_line: u32,
    /// The content hash of the file version this definition belonged to.
    pub content_hash: String,
    pub retired_at: i64,
    /// Which store this came from, set only when more than one was searched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store: Option<String>,
}

pub fn insert_file(db: &Connection, path: &str, hash: &str, bytes: u64, now: i64) -> Result<i64> {
    db.prepare_cached("INSERT INTO files (path, hash, bytes, indexed_at) VALUES (?1, ?2, ?3, ?4)")?
        .execute(params![path, hash, bytes as i64, now])?;
    Ok(db.last_insert_rowid())
}

/// Record what the parser made of a file: `parsed`, `timeout`, or `none` for
/// a language semlith carries no grammar for.
///
/// Written beside the file row rather than derived later, because the two
/// failures it separates are invisible afterwards: a file whose parse expired
/// and a file whose language has no grammar both arrive at the store with no
/// symbols at all.
pub fn set_file_graph(db: &Connection, file_id: i64, state: &str) -> Result<()> {
    db.prepare_cached("UPDATE files SET graph = ?1 WHERE id = ?2")?
        .execute(params![state, file_id])?;
    Ok(())
}

/// Record a file's units (see `chunk::COUNTED`), by row id or, for a file
/// whose row is already there, by path.
pub fn set_file_units(db: &Connection, file_id: i64, units: i64) -> Result<()> {
    db.prepare_cached("UPDATE files SET units = ?1 WHERE id = ?2")?
        .execute(params![units, file_id])?;
    Ok(())
}

pub fn set_units_by_path(db: &Connection, path: &str, units: i64) -> Result<()> {
    db.execute(
        "UPDATE files SET units = ?1 WHERE path = ?2",
        params![units, path],
    )?;
    Ok(())
}

/// Stored files of a counted format whose units were never recorded — written
/// by a binary older than 0.34.0. The index pass reads each one again for its
/// count alone.
pub fn uncounted(db: &Connection) -> Result<std::collections::HashSet<String>> {
    let mut stmt = db.prepare("SELECT path FROM files WHERE units IS NULL")?;
    let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
    let mut out = std::collections::HashSet::new();
    for path in rows {
        let path = path?;
        if crate::chunk::is_counted(std::path::Path::new(&path)) {
            out.insert(path);
        }
    }
    Ok(out)
}

/// What the graph covers, per language, read from the rows themselves.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct LanguageCoverage {
    pub language: String,
    /// Files of this language the store holds.
    pub files: usize,
    /// Files whose parse expired, so the store holds their text and none of
    /// their structure.
    pub parser_failed: usize,
    pub definitions: usize,
    /// Call edges whose target was found in the file that made the call.
    pub extracted: usize,
    /// Call edges whose target name has exactly one definition in the store.
    pub resolved: usize,
    /// Call edges whose target name has several, and nothing here says which.
    pub ambiguous: usize,
    /// Call edges naming something no definition in this store satisfies —
    /// the standard library, a dependency nobody indexed, a typo.
    pub unresolved: usize,
}

impl LanguageCoverage {
    /// The share of this language's answerable call edges that settled on one
    /// definition, which is the figure the README quotes for the whole store.
    #[must_use]
    pub fn settled_share(&self) -> usize {
        let answerable = self.extracted + self.resolved + self.ambiguous;
        if answerable == 0 {
            return 0;
        }
        (self.extracted + self.resolved) * 100 / answerable
    }
}

/// Per-language coverage for every language the store holds.
///
/// Sorted by files descending then by name, so the language that dominates a
/// corpus is the first line a reader sees and two runs over one store print
/// the same table.
///
/// The edge classes are the same four the resolver reports, decided the same
/// way: `extracted` is stored on the edge, and an `inferred` edge is resolved,
/// ambiguous or unresolved according to how many definitions of its target
/// name this store holds. A second rule here would be a second answer to "what
/// share resolves", and the README quotes this one.
pub fn coverage_by_language(db: &Connection) -> Result<Vec<LanguageCoverage>> {
    cached_by_graph(db, "coverage", || coverage_by_language_uncached(db))
}

fn coverage_by_language_uncached(db: &Connection) -> Result<Vec<LanguageCoverage>> {
    use std::collections::{BTreeMap, HashMap};
    let mut by_language: BTreeMap<String, LanguageCoverage> = BTreeMap::new();
    // Each file's language worked out once, by id. The edge pass below used
    // to parse a path per edge: three million of them on the 879k-chunk
    // corpus, which made the Index health report take half a minute.
    let mut language_of: HashMap<i64, String> = HashMap::new();

    let mut stmt = db.prepare("SELECT id, path, graph FROM files")?;
    let rows = stmt.query_map([], |r| {
        Ok((
            r.get::<_, i64>(0)?,
            r.get::<_, String>(1)?,
            r.get::<_, Option<String>>(2)?,
        ))
    })?;
    for row in rows {
        let (id, path, graph) = row?;
        let language = crate::graph::language_of(std::path::Path::new(&path))
            .unwrap_or("other")
            .to_string();
        let entry = by_language.entry(language.clone()).or_default();
        entry.files += 1;
        if graph.as_deref() == Some("timeout") {
            entry.parser_failed += 1;
        }
        language_of.insert(id, language);
    }
    let lang = |id: i64| {
        language_of
            .get(&id)
            .cloned()
            .unwrap_or_else(|| "other".to_string())
    };

    let mut stmt = db.prepare("SELECT file_id, COUNT(*) FROM symbols GROUP BY file_id")?;
    let rows = stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))?;
    for row in rows {
        let (file, count) = row?;
        by_language.entry(lang(file)).or_default().definitions +=
            usize::try_from(count).unwrap_or(0);
    }

    // Counted per file, whether the extractor settled the edge, and how many
    // definitions its target has -- none, one or several, which is all the
    // row needs, so the count stops at two.
    //
    // A call through a receiver (`edges.hint` starting `.`) settles only on a
    // method of the receiver's stated type, as `store::through_receiver`
    // decides, so for one of those `typed` counts the definitions owned by
    // that type: one settles it, anything else is ambiguous. `-1` is any
    // other edge.
    let mut stmt = db.prepare(
        "SELECT s.file_id, e.confidence = 'extracted',
                (SELECT COUNT(*) FROM (SELECT 1 FROM symbols d WHERE d.name = e.dst LIMIT 2)) AS defs,
                CASE WHEN substr(e.hint, 1, 1) = '.' THEN
                  CASE WHEN substr(e.hint, 2, 1) BETWEEN 'A' AND 'Z' THEN
                    (SELECT COUNT(*) FROM (SELECT 1 FROM symbols d WHERE d.name = e.dst
                       AND d.qualified = substr(e.hint, 2) || '::' || e.dst LIMIT 2))
                  ELSE 0 END
                ELSE -1 END AS typed,
                COUNT(*)
         FROM edges e JOIN symbols s ON s.id = e.src
         WHERE e.kind = 'calls'
         GROUP BY s.file_id, 2, defs, typed",
    )?;
    let rows = stmt.query_map([], |r| {
        Ok((
            r.get::<_, i64>(0)?,
            r.get::<_, bool>(1)?,
            r.get::<_, i64>(2)?,
            r.get::<_, i64>(3)?,
            r.get::<_, i64>(4)?,
        ))
    })?;
    for row in rows {
        let (file, extracted, definitions, typed, count) = row?;
        let count = usize::try_from(count).unwrap_or(0);
        let entry = by_language.entry(lang(file)).or_default();
        if typed >= 0 {
            match (definitions, typed) {
                (0, _) => entry.unresolved += count,
                (_, 1) if extracted => entry.extracted += count,
                (_, 1) => entry.resolved += count,
                _ => entry.ambiguous += count,
            }
        } else if extracted {
            entry.extracted += count;
        } else {
            match definitions {
                0 => entry.unresolved += count,
                1 => entry.resolved += count,
                _ => entry.ambiguous += count,
            }
        }
    }

    let mut coverage: Vec<LanguageCoverage> = by_language
        .into_iter()
        .map(|(language, mut row)| {
            row.language = language;
            row
        })
        .collect();
    coverage.sort_by(|a, b| {
        b.files
            .cmp(&a.files)
            .then_with(|| a.language.cmp(&b.language))
    });
    Ok(coverage)
}

pub fn insert_chunk(
    db: &Connection,
    file_id: i64,
    ord: usize,
    start_line: u32,
    end_line: u32,
    text: &str,
) -> Result<i64> {
    db.prepare_cached(
        "INSERT INTO chunks (file_id, ord, start_line, end_line, text)
         VALUES (?1, ?2, ?3, ?4, ?5)",
    )?
    .execute(params![file_id, ord as i64, start_line, end_line, text])?;
    let id = db.last_insert_rowid();
    db.prepare_cached("INSERT INTO chunks_fts(rowid, text) VALUES (?1, ?2)")?
        .execute(params![id, text])?;
    Ok(id)
}

/// Drop the insert trigger an older semlith's schema puts back when it opens
/// this store, inside the writer's transaction so it cannot come back before
/// the commit. With it in place every chunk would be indexed twice.
pub fn drop_insert_trigger(db: &Connection) -> Result<()> {
    let present: bool = db
        .prepare_cached(
            "SELECT EXISTS (SELECT 1 FROM sqlite_schema
             WHERE type = 'trigger' AND name = 'chunks_fts_insert')",
        )?
        .query_row([], |r| r.get(0))?;
    if present {
        db.execute_batch("DROP TRIGGER chunks_fts_insert")?;
    }
    Ok(())
}

/// Indexed files whose path ends with `suffix`, most specific first.
///
/// A locate answer prints a store-relative path and a user types one, while
/// `files.path` is absolute. Rather than teach every caller to rebuild the
/// absolute form — which needs the store's roots and gets it wrong for a file
/// reached through a symlink — the suffix is matched against what was actually
/// indexed. `/` is prepended so `one.rs` cannot match `alone.rs`.
pub fn files_ending_with(db: &Connection, suffix: &str, limit: usize) -> Result<Vec<String>> {
    let suffix = suffix
        .trim_start_matches(['.', '/', '\\'])
        .replace('\\', "/");
    let mut stmt = db.prepare(&format!(
        "SELECT path FROM files WHERE path = ?1 OR {PATH_AS_TYPED} LIKE '%/' || ?1
         ORDER BY LENGTH(path) LIMIT ?2",
    ))?;
    let rows = stmt.query_map(params![suffix, limit as i64], |r| r.get::<_, String>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// `files.path` with separators in the form a person types, for the comparisons
/// that take a path from one.
///
/// A Windows store holds `C:\work\api\src\lock.rs` — or the verbatim form of
/// it — and every locator, glob and `--lang` pattern is written with `/`, which
/// is what `semlith read src/main.rs:28-40` hands back. Comparing the two
/// without this matched nothing on that platform, which is the half of #74 that
/// is not the prefix. On unix the column is used as it is: a backslash there is
/// an ordinary character in a filename and rewriting it would make
/// `a\b.rs` answer to `a/b.rs`.
#[cfg(windows)]
const PATH_AS_TYPED: &str = r#"replace(path, '\', '/')"#;
#[cfg(not(windows))]
const PATH_AS_TYPED: &str = "path";

/// The same, for the queries that alias the table as `f` and lowercase it.
#[cfg(windows)]
const GLOB_PATH: &str = r#"replace(lower(f.path), '\', '/')"#;
#[cfg(not(windows))]
const GLOB_PATH: &str = "lower(f.path)";

/// An index on exactly [`GLOB_PATH`]'s expression, so a pattern with a literal
/// directory in front -- `<root>/**`, how a scope to one repository is written
/// -- is a range scan of it rather than a GLOB over every path (#183). Additive:
/// a binary that predates it never names it and SQLite keeps it current.
#[cfg(windows)]
const GLOB_INDEX: &str =
    r#"CREATE INDEX IF NOT EXISTS files_glob_path ON files(replace(lower(path), '\', '/'));"#;
#[cfg(not(windows))]
const GLOB_INDEX: &str = "CREATE INDEX IF NOT EXISTS files_glob_path ON files(lower(path));";

/// The literal directory an absolute pattern starts with, `/` included, and the
/// bound just past every path under it: `/` is followed by `0` in byte order.
/// `None` for a pattern that starts with a wildcard or names no directory.
fn literal_dir(pattern: &str) -> Option<(String, String)> {
    let wild = pattern.find(['*', '?', '['])?;
    let dir = &pattern[..pattern[..wild].rfind('/')? + 1];
    if dir.len() < 2 || !(dir.starts_with('/') || dir.as_bytes().get(1) == Some(&b':')) {
        return None;
    }
    Some((dir.to_string(), format!("{}0", &dir[..dir.len() - 1])))
}

/// Every chunk of one file whose lines overlap `start..=end`, in file order.
///
/// The second stage of a retrieval: a locate answer says `src/store.rs:1041-1080`
/// and this is what returns those lines and nothing else. Chunks overlap by two
/// lines by design, so the caller stitches rather than concatenates — which is
/// [`crate::Span::text`]'s job, not this one's.
pub fn chunks_overlapping(
    db: &Connection,
    path: &str,
    start: u32,
    end: u32,
) -> Result<Vec<ChunkRow>> {
    let mut stmt = db.prepare(
        "SELECT c.id, f.path, c.ord, c.start_line, c.end_line, c.text
         FROM chunks c JOIN files f ON f.id = c.file_id
         WHERE f.path = ?1 AND c.start_line <= ?2 AND c.end_line >= ?3
         ORDER BY c.ord",
    )?;
    let rows = stmt.query_map(params![path, end, start], |r| {
        Ok(ChunkRow {
            id: r.get(0)?,
            path: r.get(1)?,
            ord: r.get(2)?,
            start_line: r.get(3)?,
            end_line: r.get(4)?,
            text: r.get(5)?,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

pub fn chunk(db: &Connection, id: u64) -> Result<Option<ChunkRow>> {
    Ok(db
        .query_row(
            "SELECT c.id, f.path, c.ord, c.start_line, c.end_line, c.text
             FROM chunks c JOIN files f ON f.id = c.file_id
             WHERE c.id = ?1",
            params![id as i64],
            |r| {
                Ok(ChunkRow {
                    id: r.get(0)?,
                    path: r.get(1)?,
                    ord: r.get(2)?,
                    start_line: r.get(3)?,
                    end_line: r.get(4)?,
                    text: r.get(5)?,
                })
            },
        )
        .optional()?)
}

/// One row per indexed file: path, bytes, chunks, the last line any chunk of
/// it covers, and when it was last indexed.
#[derive(Debug, Clone)]
pub struct FileRow {
    pub path: String,
    pub bytes: i64,
    pub chunks: i64,
    pub lines: i64,
    pub indexed_at: i64,
}

/// The column a Files listing is ordered by.
///
/// An enum rather than a string spliced into the SQL: the sort column arrives
/// from a query parameter, and the only safe way to put a caller's value in an
/// `ORDER BY` — which cannot be bound as a parameter — is to never put their
/// bytes there at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileSort {
    Path,
    Bytes,
    Chunks,
    Lines,
    Indexed,
    /// Which store holds the row. Not a column of this table at all — it is
    /// which database the row came out of — so it is ordered by the merge.
    Store,
    /// The reader that parsed the file, derived from its extension.
    Reader,
    /// The language the file was recognised as, derived from its extension.
    Lang,
}

impl FileSort {
    pub fn parse(name: &str) -> Option<Self> {
        match name {
            "path" => Some(Self::Path),
            "bytes" => Some(Self::Bytes),
            "chunks" => Some(Self::Chunks),
            "lines" => Some(Self::Lines),
            "indexed" => Some(Self::Indexed),
            "store" => Some(Self::Store),
            "reader" => Some(Self::Reader),
            "lang" => Some(Self::Lang),
            _ => None,
        }
    }

    /// Whether this ordering is over a value the database does not hold.
    ///
    /// Three of the seven columns are derived by the route from the path, or
    /// from which store answered. They cannot be an `ORDER BY`, so the rows
    /// are ordered by the merge instead — which needs every matching row
    /// rather than one page of each store's.
    pub fn derived(self) -> bool {
        matches!(self, Self::Store | Self::Reader | Self::Lang)
    }

    fn sql(self) -> &'static str {
        match self {
            Self::Path => "f.path",
            Self::Bytes => "f.bytes",
            Self::Chunks => "COUNT(c.id)",
            Self::Lines => "COALESCE(MAX(c.end_line), 0)",
            Self::Indexed => "f.indexed_at",
            // The base order under a derived sort: deterministic, and the
            // tie-break the merge uses anyway.
            Self::Store | Self::Reader | Self::Lang => "f.path",
        }
    }
}

/// How many indexed files match `groups`.
///
/// Separate from the rows because the Files table pages: the page is bounded
/// and the total is not, and returning every row to count them is what the old
/// silent truncation was hiding.
pub fn file_count(db: &Connection, groups: &[Vec<String>]) -> Result<i64> {
    let (predicate, binds) = glob_predicate(groups);
    let sql = format!("SELECT COUNT(*) FROM files f WHERE {predicate}");
    let mut stmt = db.prepare(&sql)?;
    let args = binds.into_iter().map(Value::Text);
    Ok(stmt.query_row(rusqlite::params_from_iter(args), |r| r.get(0))?)
}

/// The first `take` matching files in the requested order.
///
/// The Files view's row, in one query. Asking per file would be one statement
/// per file, and a corpus is tens of thousands of them. The ordering is done
/// here rather than in the browser so that sorting orders the whole store
/// rather than the page of it that happens to be loaded — with several stores
/// open the caller takes `offset + limit` from each and merges, which is why
/// this takes a count rather than an offset.
pub fn file_rows(
    db: &Connection,
    groups: &[Vec<String>],
    sort: FileSort,
    desc: bool,
    take: i64,
) -> Result<Vec<FileRow>> {
    let (predicate, binds) = glob_predicate(groups);
    let direction = if desc { "DESC" } else { "ASC" };
    let sql = format!(
        "SELECT f.path, f.bytes, COUNT(c.id), COALESCE(MAX(c.end_line), 0), f.indexed_at \
         FROM files f LEFT JOIN chunks c ON c.file_id = f.id \
         WHERE {predicate} GROUP BY f.id ORDER BY {} {direction}, f.path ASC LIMIT ?",
        sort.sql()
    );
    let mut stmt = db.prepare(&sql)?;
    let mut args: Vec<Value> = binds.into_iter().map(Value::Text).collect();
    args.push(Value::Integer(take.max(0)));
    let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| {
        Ok(FileRow {
            path: r.get(0)?,
            bytes: r.get(1)?,
            chunks: r.get(2)?,
            lines: r.get(3)?,
            indexed_at: r.get(4)?,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// What a listing spans: the distinct file extensions in it, and the total
/// number of lines across every file.
///
/// Both are things the Stores and Files pages state and neither `stats()` nor
/// a page of rows can answer — a page knows about its own rows, and a header
/// that reports "9 formats" from the fifteen rows on screen is reporting the
/// page rather than the store.
#[derive(Debug, Default, Clone)]
pub struct Facets {
    pub extensions: Vec<String>,
    pub lines: i64,
}

pub fn file_facets(db: &Connection, groups: &[Vec<String>]) -> Result<Facets> {
    let (predicate, binds) = glob_predicate(groups);

    // The extension is taken in Rust rather than in SQL. SQLite has no
    // right-hand search, and the usual `rtrim`/`replace` idiom for it reads a
    // dot in a directory name as the start of an extension — which is a wrong
    // answer in a column that exists to say what the corpus is made of.
    let sql = format!("SELECT f.path FROM files f WHERE {predicate}");
    let mut stmt = db.prepare(&sql)?;
    let args = binds.clone().into_iter().map(Value::Text);
    let paths = stmt.query_map(rusqlite::params_from_iter(args), |r| r.get::<_, String>(0))?;
    let mut extensions: Vec<String> = paths
        .collect::<Result<Vec<String>, _>>()?
        .iter()
        .filter_map(|p| {
            std::path::Path::new(p)
                .extension()
                .and_then(|e| e.to_str())
                .map(|e| e.to_ascii_lowercase())
        })
        .collect();
    extensions.sort();
    extensions.dedup();

    let sql = format!(
        "SELECT COALESCE(SUM(n), 0) FROM ( \
           SELECT COALESCE(MAX(c.end_line), 0) AS n \
           FROM files f LEFT JOIN chunks c ON c.file_id = f.id \
           WHERE {predicate} GROUP BY f.id)"
    );
    let mut stmt = db.prepare(&sql)?;
    let args = binds.into_iter().map(Value::Text);
    let lines: i64 = stmt.query_row(rusqlite::params_from_iter(args), |r| r.get(0))?;

    Ok(Facets { extensions, lines })
}

/// An indexed image: its file's path and the pixel size.
#[derive(Debug, Clone)]
pub struct ImageRow {
    pub id: i64,
    pub path: String,
    pub width: u32,
    pub height: u32,
}

pub fn insert_image(db: &Connection, file_id: i64, width: u32, height: u32) -> Result<i64> {
    db.execute(
        "INSERT INTO images (file_id, width, height) VALUES (?1, ?2, ?3)",
        params![file_id, width, height],
    )?;
    Ok(db.last_insert_rowid())
}

/// One image row, joined with its file's path.
pub fn image(db: &Connection, id: i64) -> Result<Option<ImageRow>> {
    Ok(db
        .query_row(
            "SELECT i.id, f.path, i.width, i.height FROM images i \
             JOIN files f ON f.id = i.file_id WHERE i.id = ?1",
            params![id],
            |r| {
                Ok(ImageRow {
                    id: r.get(0)?,
                    path: r.get(1)?,
                    width: r.get(2)?,
                    height: r.get(3)?,
                })
            },
        )
        .optional()?)
}

/// `(tool, excerpt_tokens)` for every ledger row that names its tool, the
/// newest `limit` of them: what the Agents page's typical answer sizes are
/// the median of.
pub fn excerpt_tokens_by_tool(db: &Connection, limit: usize) -> Result<Vec<(String, i64)>> {
    let mut stmt = db.prepare(
        "SELECT tool, excerpt_tokens FROM retrievals WHERE tool IS NOT NULL \
         ORDER BY id DESC LIMIT ?1",
    )?;
    let rows = stmt.query_map(params![limit as i64], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// Every indexed image, for the decisions table's "read as image" rows.
pub fn image_rows(db: &Connection) -> Result<Vec<ImageRow>> {
    let mut stmt = db.prepare(
        "SELECT i.id, f.path, i.width, i.height FROM images i \
         JOIN files f ON f.id = i.file_id ORDER BY f.path",
    )?;
    let rows = stmt.query_map([], |r| {
        Ok(ImageRow {
            id: r.get(0)?,
            path: r.get(1)?,
            width: r.get(2)?,
            height: r.get(3)?,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The image ids belonging to `path`, before its row is deleted.
///
/// Read rather than returned by `delete_file`, because the cascade that removes
/// them is what makes the ids unreadable — and the vectors they address still
/// have to be evicted from the image index afterwards.
pub fn image_ids_of(db: &Connection, path: &str) -> Result<Vec<i64>> {
    let mut stmt =
        db.prepare("SELECT i.id FROM images i JOIN files f ON f.id = i.file_id WHERE f.path = ?1")?;
    let rows = stmt.query_map(params![path], |r| r.get::<_, i64>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// How many images this store holds.
pub fn image_count(db: &Connection) -> Result<i64> {
    Ok(db.query_row("SELECT COUNT(*) FROM images", [], |r| r.get(0))?)
}

/// Every image id, for the ids a filtered search may consider.
pub fn image_ids(db: &Connection) -> Result<Vec<i64>> {
    let mut stmt = db.prepare("SELECT id FROM images")?;
    let rows = stmt.query_map([], |r| r.get::<_, i64>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The image ids whose file matches `groups`, for a filtered search.
pub fn filtered_image_ids(db: &Connection, groups: &[Vec<String>]) -> Result<Vec<i64>> {
    let (predicate, binds) = glob_predicate(groups);
    let sql =
        format!("SELECT i.id FROM images i JOIN files f ON f.id = i.file_id WHERE {predicate}");
    let mut stmt = db.prepare(&sql)?;
    let args = binds.into_iter().map(Value::Text);
    let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| r.get::<_, i64>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

pub fn all_paths(db: &Connection) -> Result<Vec<String>> {
    filtered_paths(db, &[])
}

/// Everything this store holds for one file, its chunks in order, joined.
///
/// What `semlith scan` reads. The store's own copy rather than the file on
/// disk: the question the scan answers is what this store is holding, and a
/// file that has since been cleaned or deleted is still a credential sitting
/// in an index an agent can search.
pub fn text_of(db: &Connection, path: &str) -> Result<String> {
    let mut stmt = db.prepare(
        "SELECT c.text FROM chunks c JOIN files f ON f.id = c.file_id
         WHERE f.path = ?1 ORDER BY c.ord",
    )?;
    let rows = stmt.query_map([path], |r| r.get::<_, String>(0))?;
    let mut out = String::new();
    for row in rows {
        out.push_str(&row?);
        out.push('\n');
    }
    Ok(out)
}

/// Indexed paths whose file matches `groups`, in path order.
///
/// The same predicate the search halves are built on, so "which files would
/// this filter reach" and "which files did this filter search" cannot drift
/// apart and give an agent two different answers about one store.
pub fn filtered_paths(db: &Connection, groups: &[Vec<String>]) -> Result<Vec<String>> {
    let (predicate, binds) = glob_predicate(groups);
    let sql = format!("SELECT f.path FROM files f WHERE {predicate} ORDER BY f.path");
    let mut stmt = db.prepare(&sql)?;
    let args = binds.into_iter().map(Value::Text);
    let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| r.get::<_, String>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// Chunks whose file has a committed hash — the ones whose vectors are on disk.
///
/// A file is recorded with the [`PENDING`](crate::PENDING) empty hash until its
/// vectors are durable, so this is exactly what the vector index holds at rest,
/// and it costs one indexed count instead of reading the index to find out.
pub fn durable_chunks(db: &Connection) -> Result<i64> {
    Ok(db.query_row(
        "SELECT COUNT(*) FROM chunks c JOIN files f ON f.id = c.file_id WHERE f.hash != ''",
        [],
        |r| r.get(0),
    )?)
}

/// Of `ids`, the chunks whose file is still being embedded, with their text:
/// what a search mid-run embeds on the query path.
pub fn pending_among(db: &Connection, ids: &[u64]) -> Result<Vec<(u64, String)>> {
    let mut stmt = db.prepare_cached(
        "SELECT c.text FROM chunks c JOIN files f ON f.id = c.file_id
         WHERE c.id = ?1 AND f.hash = ''",
    )?;
    let mut out = Vec::new();
    for id in ids {
        if let Some(text) = stmt
            .query_row(params![*id as i64], |r| r.get::<_, String>(0))
            .optional()?
        {
            out.push((*id, text));
        }
    }
    Ok(out)
}

/// The share of the store's chunks still being embedded, or `None` when
/// nothing is: one indexed probe on every search, and the counts only when
/// the probe finds a run in progress.
pub fn pending_share(db: &Connection) -> Result<Option<f64>> {
    let busy: bool = db
        .query_row(
            "SELECT 1 FROM files WHERE hash = '' LIMIT 1",
            [],
            |_| Ok(()),
        )
        .optional()?
        .is_some();
    if !busy {
        return Ok(None);
    }
    let (pending, all): (i64, i64) = db.query_row(
        "SELECT SUM(f.hash = ''), COUNT(*) FROM chunks c JOIN files f ON f.id = c.file_id",
        [],
        |r| Ok((r.get::<_, Option<i64>>(0)?.unwrap_or(0), r.get(1)?)),
    )?;
    Ok((all > 0 && pending > 0).then(|| pending as f64 / all as f64))
}

/// Apply the schema to a bare in-memory connection, for tests in other
/// modules that need somewhere to put symbols and edges.
#[cfg(test)]
pub fn prepare_for_tests(db: &Connection) {
    db.execute_batch(SCHEMA).unwrap();
    db.pragma_update(None, "foreign_keys", "ON").unwrap();
}

/// A symbol row joined with its file's path — what a graph answer resolves to.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SymbolRow {
    pub id: i64,
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    pub kind: String,
    pub name: String,
    pub qualified: String,
    pub start_line: u32,
    pub end_line: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chunk_id: Option<i64>,
    /// Which store this came from, when more than one is open. Absent for a
    /// single store, so one store's output is what it would have been before
    /// stores could be combined.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store: Option<String>,
}

/// One end of a traversal: the symbol reached, and the edge that reached it.
///
/// Serialised flat, as the symbol's fields beside the edge's, with the
/// symbol's kind as `symbol_kind`: both were `kind`, so `symbol --json` printed
/// the key twice and a parser kept the edge's (2026-10-14 audit, G7).
#[derive(Debug, Clone, serde::Serialize)]
pub struct EdgeEnd {
    #[serde(flatten, serialize_with = "reached_symbol")]
    pub symbol: SymbolRow,
    pub kind: String,
    pub confidence: String,
    /// How many definitions of this name the store holds.
    ///
    /// `1` for an edge that could only ever mean one thing. Greater than one
    /// on an `ambiguous` row, where it is the number a renderer prints instead
    /// of listing every candidate as though each were a separate call — and on
    /// a `resolved` row, where it is how many candidates the ranking had to
    /// choose between, which is the difference between "there was only one"
    /// and "there were four and the source said which".
    pub definitions: usize,
    /// The definition this edge actually leaves from.
    ///
    /// [`edges_out`] is asked about a name, and a name can have several
    /// definitions, each with its own edges. Without this the answer says only
    /// that *something* called `index` reaches here — which is how a path
    /// finder ends up walking out of one definition of a name and into
    /// another without anything on the page saying so.
    ///
    /// `None` from [`edges_in`], where the queried name is the far end of the
    /// edge and there is no single row it leaves from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_line: Option<u32>,
    /// The line the call, import or reference was written on, in the source
    /// file named by `from_path`.
    ///
    /// `None` for an edge written before 0.16.0, and for one whose source file
    /// has not been re-indexed since. A renderer says nothing rather than
    /// guessing when it is absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    /// For a caller of a name with several definitions, the one this call
    /// resolves to — `Fleet::search_preferring` rather than "one of two".
    /// `None` when the name has one definition or the call did not settle.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub means: Option<String>,
}

/// A [`SymbolRow`] inside an [`EdgeEnd`]: every field, `kind` as `symbol_kind`.
fn reached_symbol<S: serde::Serializer>(row: &SymbolRow, s: S) -> Result<S::Ok, S::Error> {
    use serde::ser::SerializeMap;
    let mut map = s.serialize_map(None)?;
    map.serialize_entry("id", &row.id)?;
    map.serialize_entry("path", &crate::plain(&row.path))?;
    map.serialize_entry("symbol_kind", &row.kind)?;
    map.serialize_entry("name", &row.name)?;
    map.serialize_entry("qualified", &row.qualified)?;
    map.serialize_entry("start_line", &row.start_line)?;
    map.serialize_entry("end_line", &row.end_line)?;
    if let Some(chunk) = row.chunk_id {
        map.serialize_entry("chunk_id", &chunk)?;
    }
    if let Some(store) = &row.store {
        map.serialize_entry("store", store)?;
    }
    map.end()
}

const SYMBOL_COLUMNS: &str =
    "s.id, f.path, s.kind, s.name, s.qualified, s.start_line, s.end_line, s.chunk_id";

fn symbol_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<SymbolRow> {
    Ok(SymbolRow {
        id: r.get(0)?,
        path: r.get(1)?,
        kind: r.get(2)?,
        name: r.get(3)?,
        qualified: r.get(4)?,
        start_line: r.get(5)?,
        end_line: r.get(6)?,
        chunk_id: r.get(7)?,
        store: None,
    })
}

pub fn insert_symbol(
    db: &Connection,
    file_id: i64,
    chunk_id: Option<i64>,
    symbol: &crate::graph::Symbol,
) -> Result<i64> {
    db.prepare_cached(
        "INSERT INTO symbols (file_id, chunk_id, kind, name, qualified, start_line, end_line)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
    )?
    .execute(params![
        file_id,
        chunk_id,
        symbol.kind,
        symbol.name,
        symbol.qualified,
        symbol.start_line,
        symbol.end_line
    ])?;
    Ok(db.last_insert_rowid())
}

pub fn insert_edge(
    db: &Connection,
    src: i64,
    dst: &str,
    kind: &str,
    confidence: &str,
    hint: Option<&str>,
    line: Option<u32>,
) -> Result<()> {
    db.prepare_cached(
        "INSERT INTO edges (src, dst, kind, confidence, hint, line)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
    )?
    .execute(params![src, dst, kind, confidence, hint, line])?;
    Ok(())
}

/// Write one file's extraction: its symbols, then its edges by source name.
///
/// `spans` are the file's chunks as `(start_line, end_line, chunk_id)`, so each
/// symbol points at the chunk its first line sits in. Returns `(symbols,
/// edges)` written. The one writer `index_set` and the graph tests share, so a
/// test of what a file yields is a test of what the store holds.
pub fn write_extraction(
    db: &Connection,
    extraction: &crate::graph::Extraction,
    file_id: i64,
    spans: &[(u32, u32, i64)],
) -> Result<(usize, usize)> {
    // Name to id, for the edges below. A file may define the same name
    // twice — two `new` methods on two types — so an edge leaves from the
    // narrowest of them whose lines hold the line it was written on, and from
    // the first when none does. Until 0.44.1 the first always won, and every
    // call the second made was lost.
    let mut ids: std::collections::HashMap<&str, (i64, bool)> = std::collections::HashMap::new();
    let mut extents: std::collections::HashMap<&str, Vec<(i64, u32, u32)>> =
        std::collections::HashMap::new();
    // The file's own symbol, which an edge marked `from_module` leaves from
    // even when a definition shares its name.
    let mut module_id: Option<i64> = None;
    for symbol in &extraction.symbols {
        let chunk_id = spans
            .iter()
            .find(|(start, end, _)| symbol.start_line >= *start && symbol.start_line <= *end)
            .map(|(_, _, id)| *id);
        let id = insert_symbol(db, file_id, chunk_id, symbol)?;
        // A definition outranks the file's module symbol of the same name:
        // `fn brief` in `brief.rs` is where its calls come from, and giving
        // them to the module put every caller of it at line 1.
        let module = symbol.kind == "module";
        if module && module_id.is_none() {
            module_id = Some(id);
        }
        if !module {
            extents.entry(symbol.name.as_str()).or_default().push((
                id,
                symbol.start_line,
                symbol.end_line,
            ));
        }
        match ids.get(symbol.name.as_str()) {
            None => {
                ids.insert(symbol.name.as_str(), (id, module));
            }
            Some((_, true)) if !module => {
                ids.insert(symbol.name.as_str(), (id, false));
            }
            _ => {}
        }
    }
    let ids: std::collections::HashMap<&str, i64> =
        ids.into_iter().map(|(k, (id, _))| (k, id)).collect();

    let mut written = 0;
    for edge in &extraction.edges {
        let covering = edge.line.and_then(|line| {
            extents
                .get(edge.from.as_str())?
                .iter()
                .filter(|(_, start, end)| (*start..=*end).contains(&line))
                .min_by_key(|(_, start, end)| end - start)
                .map(|(id, _, _)| *id)
        });
        let src = match module_id {
            Some(id) if edge.from_module => id,
            _ => match covering.or_else(|| ids.get(edge.from.as_str()).copied()) {
                Some(id) => id,
                None => continue,
            },
        };
        insert_edge(
            db,
            src,
            &edge.to,
            &edge.kind,
            &edge.confidence,
            edge.hint.as_deref(),
            edge.line,
        )?;
        written += 1;
    }
    Ok((extraction.symbols.len(), written))
}

/// Every definition of `name`, across the whole store.
///
/// Exact match, not a glob: `semlith symbol acquire` asking about `acquire` and
/// being handed `acquire_timeout` as well would make the answer something the
/// caller has to re-filter.
pub fn symbols_named(db: &Connection, name: &str, limit: usize) -> Result<Vec<SymbolRow>> {
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE s.name = ?1 ORDER BY f.path, s.start_line LIMIT ?2"
    );
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map(params![name, limit as i64], symbol_row)?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// [`symbols_named`] with code first — definitions before the headings, keys
/// and selectors that share the name — and how many there are in all.
pub fn symbols_named_counted(
    db: &Connection,
    name: &str,
    limit: usize,
) -> Result<(Vec<SymbolRow>, usize)> {
    let navigational = crate::graph::not_navigational("s.kind");
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE s.name = ?1 ORDER BY NOT ({navigational}), f.path, s.start_line LIMIT ?2"
    );
    let mut stmt = db.prepare(&sql)?;
    let limit = i64::try_from(limit).unwrap_or(i64::MAX);
    let rows = stmt.query_map(params![name, limit], symbol_row)?;
    let rows = rows.collect::<Result<Vec<_>, _>>()?;
    let total: i64 = db.query_row(
        "SELECT COUNT(*) FROM symbols WHERE name = ?1",
        [name],
        |r| r.get(0),
    )?;
    Ok((rows, total as usize))
}

/// Symbols to draw for a scope, newest-defined first within each file.
///
/// `prefix` narrows to a directory or a file the way the Files view does.
/// Module symbols are left out: every file has one, so they would fill the
/// budget with nodes that say only "this file exists".
pub fn symbols_scoped(
    db: &Connection,
    prefix: Option<&str>,
    limit: usize,
) -> Result<Vec<SymbolRow>> {
    // Busiest first. A scope filled with symbols that touch nothing draws a
    // field of dots: technically the graph, and of no use to anyone looking at
    // it. Ordering by how connected a symbol is puts the shape on the screen.
    let Some(p) = prefix else {
        return busiest_symbols(db, limit);
    };
    let pattern = format!("*{}*", p.to_ascii_lowercase());
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE lower(f.path) GLOB ?1 AND s.kind != 'module'
         ORDER BY (
           (SELECT COUNT(*) FROM edges e WHERE e.src = s.id)
           + (SELECT COUNT(*) FROM edges e WHERE e.dst = s.name)
         ) DESC, f.path, s.start_line LIMIT ?2"
    );
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map(params![pattern, limit as i64], symbol_row)?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The busiest symbols of a whole store, for [`symbols_scoped`] with no scope.
///
/// Ordering every symbol by two correlated counts took 32 s on the 879k-chunk
/// corpus, and it is the Graph page's first fetch. Here each direction is
/// counted once, on its own index, for the most-targeted names and the busiest
/// sources, and only those are ordered: about a second on the same corpus. A
/// symbol is missed only by being busy in neither direction on its own, which
/// a symbol worth opening on is not. A name counted as a target counts for
/// every definition of it, as the full count did.
fn busiest_symbols(db: &Connection, limit: usize) -> Result<Vec<SymbolRow>> {
    let candidates = (limit * 4).max(64) as i64;
    let sql = format!(
        "WITH ins AS (SELECT dst AS name, COUNT(*) AS n FROM edges GROUP BY dst ORDER BY n DESC LIMIT ?1),
              outs AS (SELECT src AS id, COUNT(*) AS n FROM edges GROUP BY src ORDER BY n DESC LIMIT ?1),
              picked AS (
                SELECT s.id FROM symbols s JOIN ins ON s.name = ins.name
                UNION
                SELECT id FROM outs
              )
         SELECT {SYMBOL_COLUMNS} FROM picked
         JOIN symbols s ON s.id = picked.id
         JOIN files f ON f.id = s.file_id
         WHERE s.kind != 'module'
         ORDER BY (
           COALESCE((SELECT n FROM outs WHERE outs.id = s.id), (SELECT COUNT(*) FROM edges e WHERE e.src = s.id))
           + COALESCE((SELECT n FROM ins WHERE ins.name = s.name), 0)
         ) DESC, f.path, s.start_line LIMIT ?2"
    );
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map(params![candidates, limit as i64], symbol_row)?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// Symbols defined in files matching `groups` whose name is one of `names`.
///
/// The resolution step every traversal shares: an edge names its target, and
/// this is what turns that name back into rows. The filter is threaded through
/// so graph expansion obeys the same chunk-id set as the other two search
/// halves rather than reaching outside it.
pub fn symbols_by_names(
    db: &Connection,
    names: &[String],
    groups: &[Vec<String>],
) -> Result<Vec<SymbolRow>> {
    // In batches, because SQLite refuses a statement with more than 32 766
    // variables, and a walk over the 70-repository benchmark corpus reached more
    // names than that: every search there failed with "too many SQL variables".
    const BATCH: usize = 1000;
    let (predicate, filter_binds) = glob_predicate(groups);
    let mut out = Vec::new();
    for batch in names.chunks(BATCH) {
        let holes = vec!["?"; batch.len()].join(", ");
        let sql = format!(
            "SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id
             WHERE {predicate} AND s.name IN ({holes})"
        );
        let mut stmt = db.prepare(&sql)?;
        let args = filter_binds.iter().chain(batch).cloned().map(Value::Text);
        let rows = stmt.query_map(rusqlite::params_from_iter(args), symbol_row)?;
        for row in rows {
            out.push(row?);
        }
    }
    out.sort_by(|a, b| (&a.path, a.start_line, a.id).cmp(&(&b.path, b.start_line, b.id)));
    Ok(out)
}

/// What the symbols named `name` point at: callees, imports, references out.
///
/// One hop. `kinds` empty means every edge kind.
///
/// # Resolution
///
/// `edges.dst` is a name, and a name is not an address: a store of any size
/// holds four `get`s and seven `index`es. Until 0.15.0 this returned every
/// definition that shared the name, each as its own row and each looking
/// exactly like a call the source makes — which is how `semlith path` came to
/// answer "yes, connected" to questions whose honest answer is "no".
///
/// Each edge is now resolved against its candidates by [`rank`], and the
/// confidence it comes back with says how it was settled:
///
/// - `extracted` — the file named where the target came from. Stored, and
///   never overwritten here: a fact from the syntax tree outranks a ranking.
/// - `resolved` — the candidates narrowed to exactly one. Either the source
///   narrowed them (same file, the hint, an import) or the corpus did, by
///   holding only one definition of the name.
/// - `ambiguous` — several candidates survived and nothing chose between them.
///   Every candidate is returned, each marked `ambiguous` and each carrying
///   the count, so a renderer can collapse them to one row and a traversal can
///   refuse to cross them.
///
/// `inferred` is the stored value and is what [`edges_in`] and the edge census
/// still show. It does not come back from here, because by the time a target
/// has been looked up there is always something to say about it: either one
/// definition answers to the name or several do.
///
/// A resolution is against the indexed corpus, not against the world. One
/// definition of `parse` in the store does not prove the call went to it
/// rather than to a dependency that was never indexed — that is what the
/// hidden-by-default unresolved targets are about, not this.
pub fn edges_out(db: &Connection, name: &str, kinds: &[String]) -> Result<Vec<EdgeEnd>> {
    edges_out_below(db, name, kinds, None, None)
}

/// How many edges touch `name`, and how many of them are certain, counted on
/// the indexes alone: `(resolved, total)`.
///
/// For the graph page's choice of where to open, which only compares counts.
/// An edge in counts as certain when the extractor said so; an edge out when
/// the extractor said so or its target has exactly one definition, which is
/// how [`edges_out`] settles the common case. An out edge to a name nothing
/// defines is not counted, as [`edges_out`] does not return it.
pub fn edge_counts(db: &Connection, name: &str) -> Result<(usize, usize)> {
    let navigational = crate::graph::not_navigational("h.kind");
    let (in_total, in_sure): (i64, i64) = db.query_row(
        "SELECT COUNT(*), COALESCE(SUM(confidence IN ('extracted', 'resolved')), 0)
         FROM edges WHERE dst = ?1",
        [name],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    let (out_total, out_sure): (i64, i64) = db.query_row(
        &format!(
            "SELECT COUNT(*), COALESCE(SUM(e.confidence = 'extracted' OR
                 (substr(COALESCE(e.hint, ''), 1, 1) != '.' AND
                  (SELECT COUNT(*) FROM (SELECT 1 FROM symbols h WHERE h.name = e.dst AND {navigational} LIMIT 2)) = 1)), 0)
             FROM edges e JOIN symbols src ON src.id = e.src
             WHERE src.name = ?1
               AND EXISTS (SELECT 1 FROM symbols h WHERE h.name = e.dst AND {navigational})"
        ),
        [name],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    Ok((
        (in_sure + out_sure) as usize,
        (in_total + out_total) as usize,
    ))
}

/// [`edges_out`] restricted to edges whose target is one of `targets`, settled
/// exactly as [`edges_out`] settles them.
///
/// For the graph page, which draws only edges with both ends on the canvas: on
/// the 879k-chunk corpus `edges_out("main")` joins 706,461 candidate rows in
/// about ten seconds to keep the handful that point at a drawn name, and the
/// page asks once per drawn node.
pub fn edges_out_to(db: &Connection, name: &str, targets: &[String]) -> Result<Vec<EdgeEnd>> {
    if targets.is_empty() {
        return Ok(Vec::new());
    }
    edges_out_below(db, name, &[], None, Some(targets))
}

/// [`edges_out`] without the edges whose target has more than `hub`
/// definitions, dropped before their candidates are joined.
///
/// For search's graph walk, which crosses no ambiguous edge anyway. An edge to
/// `get` in a store holding seven hundred of them joins seven hundred candidate
/// rows and nearly always resolves to "ambiguous"; on the 879k-chunk benchmark
/// corpus those rows were most of the walk's cost. `neighbors`, `impact` and
/// `path` keep [`edges_out`], because an answer about one symbol can afford to
/// settle every edge.
pub fn edges_out_short_of_hubs(
    db: &Connection,
    name: &str,
    kinds: &[String],
    hub: usize,
) -> Result<Vec<EdgeEnd>> {
    edges_out_below(db, name, kinds, Some(hub), None)
}

fn edges_out_below(
    db: &Connection,
    name: &str,
    kinds: &[String],
    hub: Option<usize>,
    targets: Option<&[String]>,
) -> Result<Vec<EdgeEnd>> {
    let filter = kind_predicate(kinds, "e.kind");
    // An edge's target is resolved by name, so without this a configuration key
    // named `path` is a candidate definition of every `path` any code calls.
    let target = crate::graph::not_navigational("s.kind");
    // Written on `e` alone, so SQLite tests it per edge, before the join to
    // the candidates it exists to avoid. The count stops at `hub + 1`.
    let short_of_hub = match hub {
        Some(hub) => format!(
            "AND (SELECT COUNT(*) FROM (SELECT 1 FROM symbols h WHERE h.name = e.dst AND {} LIMIT {})) <= {hub}",
            crate::graph::not_navigational("h.kind"),
            hub + 1
        ),
        None => String::new(),
    };
    // Bound after the kinds, in the order the holes appear.
    let to_targets = match targets {
        Some(t) => format!("AND e.dst IN ({})", vec!["?"; t.len()].join(", ")),
        None => String::new(),
    };
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS}, e.kind, e.confidence, e.hint, srcf.path, src.start_line, e.line,
                src.id, src.kind, src.qualified
         FROM symbols src
         JOIN files srcf ON srcf.id = src.file_id
         JOIN edges e ON e.src = src.id
         JOIN symbols s ON s.name = e.dst AND {target}
         JOIN files f ON f.id = s.file_id
         WHERE src.name = ?1 AND {filter} {to_targets} {short_of_hub}
         ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let mut binds: Vec<Value> = vec![Value::Text(name.to_string())];
    binds.extend(kinds.iter().map(|k| Value::Text(k.clone())));
    binds.extend(
        targets
            .unwrap_or(&[])
            .iter()
            .map(|t| Value::Text(t.clone())),
    );
    let rows = stmt.query_map(rusqlite::params_from_iter(binds), |r| {
        Ok(Reached {
            symbol: symbol_row(r)?,
            kind: r.get(8)?,
            confidence: r.get(9)?,
            hint: r.get(10)?,
            src_path: r.get(11)?,
            src_line: r.get(12)?,
            line: r.get(13)?,
            src_id: r.get(14)?,
            src_top_level: top_level(
                &r.get::<_, String>(15)?,
                &r.get::<_, String>(16)?,
                &r.get::<_, String>(11)?,
            ),
        })
    })?;
    let reached = rows.collect::<Result<Vec<_>, _>>()?;
    resolve(db, reached)
}

/// One row of the join behind [`edges_out`]: a candidate for an edge's target,
/// with everything the ranking needs about the edge itself.
struct Reached {
    symbol: SymbolRow,
    kind: String,
    confidence: String,
    hint: Option<String>,
    src_path: String,
    src_line: u32,
    line: Option<u32>,
    /// The definition the edge leaves from, and whether it sits at its file's
    /// top level (see [`top_level`]).
    src_id: i64,
    src_top_level: bool,
}

/// Turn candidate rows into resolved edges.
///
/// The rows arrive as the cross product of edges and the definitions their
/// targets could mean, so they are grouped back into edges first. Order is
/// preserved: the first time an edge is seen decides where its rows sit in the
/// answer, so a caller that used to read this list top to bottom still reads
/// it in the same order.
fn resolve(db: &Connection, reached: Vec<Reached>) -> Result<Vec<EdgeEnd>> {
    // (source definition, source file, target name, edge kind, hint) — one
    // edge in the source.
    type Key = (i64, String, String, String, Option<String>);
    let mut order: Vec<Key> = Vec::new();
    let mut groups: std::collections::HashMap<Key, Vec<Reached>> = std::collections::HashMap::new();
    for row in reached {
        let key = (
            row.src_id,
            row.src_path.clone(),
            row.symbol.name.clone(),
            row.kind.clone(),
            row.hint.clone(),
        );
        if !groups.contains_key(&key) {
            order.push(key.clone());
        }
        groups.entry(key).or_default().push(row);
    }

    // The imports of each source file, read once and only when a group
    // actually needs them: the first two tiers settle most edges, and a file's
    // imports are a query this should not pay for on every hop of a traversal.
    let mut imports: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();

    let mut out = Vec::new();
    for key in order {
        let mut candidates = groups.remove(&key).unwrap_or_default();
        let (_, src_path, _, kind, hint) = &key;
        let top = candidates.first().is_some_and(|c| c.src_top_level);
        // What the call cannot mean (see `reachable`) is not ranked, and an
        // unsettled call does not list it either.
        let rows: Vec<&SymbolRow> = candidates.iter().map(|c| &c.symbol).collect();
        let mut reach = reachable(kind, &rows, src_path, hint.as_deref(), top).into_iter();
        candidates.retain(|_| reach.next().unwrap_or(true));
        // A structural edge names a definition in its own file, on the line
        // the edge records; anything elsewhere with that name is not it.
        if structural(kind) {
            candidates.retain(|c| {
                c.symbol.path == c.src_path && c.line.is_none_or(|l| l == c.symbol.start_line)
            });
            for row in candidates {
                out.push(EdgeEnd {
                    symbol: row.symbol,
                    kind: row.kind,
                    confidence: row.confidence,
                    definitions: 1,
                    from_path: Some(row.src_path),
                    from_line: Some(row.src_line),
                    line: row.line,
                    means: None,
                });
            }
            continue;
        }
        let definitions = candidates.len();

        let rows: Vec<&SymbolRow> = candidates.iter().map(|c| &c.symbol).collect();
        let (picked, settled) = choose_for(
            db,
            kind,
            &rows,
            src_path,
            hint.as_deref(),
            top,
            &mut imports,
        )?;
        // A receiver's edge that did not settle lists only what a method call
        // can mean; any other unsettled edge lists every candidate, as before.
        let receiver = hint
            .as_deref()
            .is_some_and(|h| h.starts_with(crate::graph::RECEIVER));
        let listed = if settled || receiver {
            picked.iter().filter(|p| **p).count()
        } else {
            definitions
        };
        for (row, keep) in candidates.into_iter().zip(&picked) {
            if (settled || receiver) && !*keep {
                continue;
            }
            let confidence = if settled && row.confidence == crate::graph::EXTRACTED {
                crate::graph::EXTRACTED
            } else if settled {
                crate::graph::RESOLVED
            } else {
                crate::graph::AMBIGUOUS
            };
            out.push(EdgeEnd {
                symbol: row.symbol,
                kind: row.kind,
                confidence: confidence.to_string(),
                definitions: if settled { definitions } else { listed },
                from_path: Some(row.src_path),
                from_line: Some(row.src_line),
                line: row.line,
                means: None,
            });
        }
    }
    Ok(out)
}

/// Whether an edge kind says where a definition sits rather than what it uses.
fn structural(kind: &str) -> bool {
    matches!(kind, "defines" | "contains")
}

/// [`choose`] for an edge of `kind`, over only the candidates it can reach
/// (see [`reachable`]).
fn choose_for(
    db: &Connection,
    kind: &str,
    candidates: &[&SymbolRow],
    src_path: &str,
    hint: Option<&str>,
    caller_top_level: bool,
    imports: &mut std::collections::HashMap<String, Vec<String>>,
) -> Result<(Vec<bool>, bool)> {
    let reach = reachable(kind, candidates, src_path, hint, caller_top_level);
    if reach.iter().all(|r| *r) {
        return choose(db, candidates, src_path, hint, imports);
    }
    let callable: Vec<&SymbolRow> = candidates
        .iter()
        .zip(&reach)
        .filter(|(_, r)| **r)
        .map(|(c, _)| *c)
        .collect();
    let (picked, settled) = choose(db, &callable, src_path, hint, imports)?;
    let mut picked = picked.into_iter();
    let keep = reach
        .iter()
        .map(|r| *r && picked.next().unwrap_or(false))
        .collect();
    Ok((keep, settled))
}

/// Which of `candidates` an edge of `kind` written in `src_path` with `hint`
/// can mean at all, before anything is ranked.
///
/// A call never means a module: ripgrep's main.rs declares `mod search;`
/// beside `fn search`, and the module made the bare call `search(&args, mode)`
/// a tie. Modules are candidates only when nothing else answers to the name.
///
/// And a call with no receiver never means a method where the language has no
/// implicit receiver ([`crate::graph::no_implicit_receiver`]): `lane(id)` beside
/// `impl Enabled { fn lane(&self, ..) }` in accel.rs, or
/// `crate::accel::lane("ane")` in daemon.rs, can only be the free fn
/// `accel::lane`, and the tie with `Enabled::lane` hid both callers from the
/// cloud's impact check when semlith#245 changed its return type. The mirror
/// of [`through_receiver`], which never lets a receiver call mean a free
/// function. Only when a free function answers to the name: with none, the
/// call may leave the corpus and is ranked as before. A hint that reads as a
/// type (`Enabled::lane(..)`, `Self::new`) is a path to a method and keeps
/// every candidate. In any language, a bare call made at a file's top level
/// (`caller_top_level`, see [`top_level`]) has no `this` to imply either:
/// `helper()` in Kotlin's top-level `main` is not `class A`'s member.
fn reachable(
    kind: &str,
    candidates: &[&SymbolRow],
    src_path: &str,
    hint: Option<&str>,
    caller_top_level: bool,
) -> Vec<bool> {
    let mut keep = vec![true; candidates.len()];
    if kind != "calls" {
        return keep;
    }
    if candidates.iter().any(|c| c.kind != "module") {
        for (k, c) in keep.iter_mut().zip(candidates) {
            *k = c.kind != "module";
        }
    }
    let lang = crate::filter::language_of_path(src_path).map(|l| l.name);
    // A Rust file under a crate's `tests/`, `benches/` or `examples/` is a
    // crate of its own, reachable only from beside it: the cloud's
    // `semlith::accel::lane(..)` tied src/accel.rs's `lane` with a helper of
    // that name in tests/accel.rs. ponytail: a `tests` module directory
    // inside `src/` reads as one too; only test code calls into it.
    if lang == Some("rust") {
        let reached = |p: &str| {
            !p.ends_with(".rs") || separate_crate(p).is_none_or(|dir| src_path.starts_with(dir))
        };
        if candidates
            .iter()
            .zip(&keep)
            .any(|(c, k)| *k && reached(&c.path))
        {
            for (k, c) in keep.iter_mut().zip(candidates) {
                *k = *k && reached(&c.path);
            }
        }
    }
    // Go writes `pkg.F()` and `t.F()` alike, and JavaScript `ns.f()` and
    // `obj.f()`: only the extractor knows which leads are receivers, so
    // there only a call with no lead at all is bare.
    let bare = match lang {
        Some("go" | "javascript" | "typescript" | "svelte" | "vue") => hint.is_none(),
        _ => hint.is_none_or(|h| {
            !h.starts_with(crate::graph::RECEIVER)
                && !h.chars().next().is_some_and(char::is_uppercase)
        }),
    };
    let receiver_free = lang.is_some_and(crate::graph::no_implicit_receiver);
    let no_this = (bare && receiver_free) || (caller_top_level && hint.is_none());
    // A module path drops methods only for a free function it places: in
    // flask's drive, `d.fixtures.bulk()` named fixtures.py, which holds the
    // method `Fixtures.bulk` and no free `bulk`.
    let placed = |c: &SymbolRow| {
        hint.is_none_or(|h| names_file(h, &c.path, src_path) || owner_of(&c.qualified) == Some(h))
    };
    let free_left = candidates
        .iter()
        .zip(&keep)
        .any(|(c, k)| *k && free_function(c) && placed(c));
    if no_this && free_left {
        for (k, c) in keep.iter_mut().zip(candidates) {
            *k = *k && !owned_by_type(c);
        }
    }
    keep
}

/// Which of `candidates` an edge written in `src_path` with `hint` means, and
/// whether that settled it.
///
/// Every candidate at the best rank is kept, so one `true` is a settled edge
/// and several are an ambiguous one — except through a receiver, which
/// [`through_receiver`] decides. The imports of the calling file are read
/// only when the first pass left more than one and something unplaced, and
/// cached in `imports` across calls.
///
/// A tie between candidates that a signal did place — two `fleet.rs` files
/// both named by an import, one of them a copy under `tests/fixtures` — goes
/// to the one sharing the most directories with the caller. A tie that
/// nothing placed stays a tie: nearness is a reason to prefer one of two
/// plausible answers, not a reason to pick one of twenty-four `get`s.
fn choose(
    db: &Connection,
    candidates: &[&SymbolRow],
    src_path: &str,
    hint: Option<&str>,
    imports: &mut std::collections::HashMap<String, Vec<String>>,
) -> Result<(Vec<bool>, bool)> {
    if let Some(lead) = hint.and_then(|h| h.strip_prefix(crate::graph::RECEIVER)) {
        return Ok(through_receiver(candidates, src_path, lead));
    }
    // A module path (`std::env::current_dir()`, `os.getcwd()`) says where the
    // target lives, so one that names no candidate's file, module or import
    // went somewhere the store does not hold: the edge stays unsettled even
    // with one candidate left. ripgrep's `std::env::current_dir()` was
    // resolved onto `hiargs::current_dir` this way.
    let path_hint = hint.filter(|h| !h.chars().next().is_some_and(char::is_uppercase));
    if candidates.len() == 1 && path_hint.is_none() {
        return Ok((vec![true], true));
    }
    let mut ranks: Vec<u8> = candidates
        .iter()
        .map(|c| rank(c, src_path, hint, &[]))
        .collect();
    if (survivors(&ranks) != 1 || path_hint.is_some()) && ranks.contains(&UNRANKED) {
        if !imports.contains_key(src_path) {
            let found = file_imports(db, src_path)?;
            imports.insert(src_path.to_string(), found);
        }
        let of_file = &imports[src_path];
        ranks = candidates
            .iter()
            .map(|c| rank(c, src_path, hint, of_file))
            .collect();
    }
    let best = ranks.iter().copied().min().unwrap_or(UNRANKED);
    let mut keep: Vec<bool> = ranks.iter().map(|r| *r == best).collect();
    if path_hint.is_some() && best == UNRANKED {
        return Ok((keep, false));
    }
    if best < UNRANKED && keep.iter().filter(|k| **k).count() > 1 {
        let near: Vec<usize> = candidates
            .iter()
            .map(|c| shared_directories(&c.path, src_path))
            .collect();
        let nearest = near
            .iter()
            .zip(&keep)
            .filter(|(_, k)| **k)
            .map(|(n, _)| *n)
            .max()
            .unwrap_or(0);
        for (k, n) in keep.iter_mut().zip(&near) {
            *k = *k && *n == nearest;
        }
    }
    let settled = keep.iter().filter(|k| **k).count() == 1;
    Ok((keep, settled))
}

/// The directory, separator included, that makes a Rust file a crate of its
/// own: `semlith/tests/` for `semlith/tests/accel.rs`. `None` for a file of
/// the library or binary.
fn separate_crate(path: &str) -> Option<&str> {
    let mut start = 0;
    for (i, c) in path.char_indices() {
        if c == '/' || c == '\\' {
            if matches!(&path[start..i], "tests" | "benches" | "examples") {
                return Some(&path[..=i]);
            }
            start = i + 1;
        }
    }
    None
}

/// Whether a definition sits at its file's top level, where no `this` is in
/// scope: the file's module symbol, or a function the file's own module name
/// qualifies (`accel::lane` in accel.rs, `A::helper` in A.kt).
fn top_level(kind: &str, qualified: &str, path: &str) -> bool {
    let module = std::path::Path::new(path).file_stem();
    kind == "module"
        || (kind == "function" && owner_of(qualified).is_none_or(|o| module == Some(o.as_ref())))
}

/// Whether a definition is a function no receiver can reach: not a method,
/// and not owned by a type (`main::run`, Python's `helpers::make_response`,
/// a function in `mod tests`). A method's owner is a type, upper case first —
/// unless it is the file's own module name: `fun helper()` at the top of
/// A.kt is qualified `A::helper`, and is no member of anything.
fn free_function(c: &SymbolRow) -> bool {
    let module = std::path::Path::new(&c.path).file_stem();
    c.kind == "function"
        && owner_of(&c.qualified).is_none_or(|o| {
            !o.chars().next().is_some_and(char::is_uppercase) || module == Some(o.as_ref())
        })
}

/// What only a receiver can call: a method, or a function a type owns
/// (Python's `C::f`).
fn owned_by_type(c: &SymbolRow) -> bool {
    c.kind == "method" || (c.kind == "function" && !free_function(c))
}

/// What a call through a receiver (`x.run()`, `self.flush()`) means.
///
/// Never a free function: `.build_parallel().run(||` in ripgrep's main.rs was
/// settled on `main::run` because that `run` sat in the calling file, which put
/// a false two-hop chain into `path` (2026-10-14 audit, G1). It settles only
/// on a method of the receiver's stated type — the ranking signals that place
/// a bare call, the calling file and its imports, say nothing about which type
/// a receiver is — and a receiver nothing typed leaves the edge ambiguous
/// among the methods of that name. Typing it is a type checker's job, which
/// semlith is not. One exception, for Python only, where `x.f()` is also how a
/// module's function is called: a lower-case receiver naming the file of
/// exactly one free function, as `views.render()` names `views.py`.
fn through_receiver(candidates: &[&SymbolRow], src_path: &str, lead: &str) -> (Vec<bool>, bool) {
    // What a receiver can call: a method, or a function a type owns. With
    // none in the store the call leaves the corpus, and the edge lists what
    // shares the name, never a module (`searcher.search()` is not search.rs).
    let methods: Vec<bool> = candidates.iter().map(|c| owned_by_type(c)).collect();
    let callable: Vec<bool> = candidates.iter().map(|c| c.kind != "module").collect();
    let pool = if methods.contains(&true) {
        methods
    } else if callable.contains(&true) {
        callable
    } else {
        vec![true; candidates.len()]
    };
    let upper = lead.chars().next().is_some_and(char::is_uppercase);
    let python = |p: &str| p.ends_with(".py") || p.ends_with(".pyi");
    if python(src_path) && !lead.is_empty() && !upper {
        let module: Vec<bool> = candidates
            .iter()
            .map(|c| free_function(c) && names_file(lead, &c.path, src_path))
            .collect();
        if module.iter().filter(|m| **m).count() == 1 {
            return (module, true);
        }
    }
    if upper {
        let mut typed: Vec<bool> = candidates
            .iter()
            .zip(&pool)
            .map(|(c, p)| *p && owned_by_type(c) && owner_of(&c.qualified) == Some(lead))
            .collect();
        if typed.iter().filter(|t| **t).count() > 1 {
            let near: Vec<usize> = candidates
                .iter()
                .map(|c| shared_directories(&c.path, src_path))
                .collect();
            let nearest = near
                .iter()
                .zip(&typed)
                .filter(|(_, t)| **t)
                .map(|(n, _)| *n)
                .max()
                .unwrap_or(0);
            for (t, n) in typed.iter_mut().zip(&near) {
                *t = *t && *n == nearest;
            }
        }
        match typed.iter().filter(|t| **t).count() {
            1 => return (typed, true),
            0 => {}
            _ => return (typed, false),
        }
    }
    // `this.close()` where `this` is an object literal or a function's own
    // object, a type the extractor cannot name: the one method of that name
    // in the calling file is the one meant.
    if lead.is_empty() {
        let here: Vec<bool> = candidates
            .iter()
            .zip(&pool)
            .map(|(c, p)| *p && c.path == src_path)
            .collect();
        if here.iter().filter(|h| **h).count() == 1 {
            return (here, true);
        }
    }
    (pool, false)
}

/// How many leading directories two paths share.
fn shared_directories(a: &str, b: &str) -> usize {
    let a = std::path::Path::new(a).parent();
    let b = std::path::Path::new(b).parent();
    match (a, b) {
        (Some(a), Some(b)) => a
            .components()
            .zip(b.components())
            .take_while(|(x, y)| x == y)
            .count(),
        _ => 0,
    }
}

/// The rank of a candidate that nothing placed. Sorts last, and is what says
/// "the imports are worth reading for this group".
const UNRANKED: u8 = 4;

/// How many candidates sit at the best rank.
fn survivors(ranks: &[u8]) -> usize {
    match ranks.iter().min() {
        Some(best) => ranks.iter().filter(|r| *r == best).count(),
        None => 0,
    }
}

/// The type or module a definition's `qualified` name puts it in:
/// `Fleet` for `Fleet::search_preferring`, `store` for `store::edges_out`.
pub fn owner_of(qualified: &str) -> Option<&str> {
    let (owner, _) = qualified.rsplit_once("::")?;
    Some(owner.rsplit("::").next().unwrap_or(owner))
}

/// Where a candidate definition sits in the ranking, lower being better.
///
/// 0. The type the source says the receiver is. `self.search_preferring()`
///    inside `impl Semlith`, or `x.search_preferring()` with `x: Fleet`, is a
///    statement about which method, stronger than where the call sits. Only a
///    hint that reads as a type (upper case first) counts here: a variable
///    named `fleet` is a lead about a file, and tier 2 reads it as one.
/// 1. The same file as the call. A file that defines a name and calls it means
///    its own — unless the call went through a module path that names
///    another file.
/// 2. A file the hint names. `store::edges_out` in the presence of
///    `src/store.rs` is not a coincidence.
/// 3. A file the calling file imports. Weaker than the hint because an import
///    list is a set of possibilities rather than a statement about this call.
/// 4. Nothing placed it.
fn rank(candidate: &SymbolRow, src_path: &str, hint: Option<&str>, imports: &[String]) -> u8 {
    let typed = hint.filter(|h| h.chars().next().is_some_and(char::is_uppercase));
    // A top-level function its upper-case file names (`A::helper` in A.kt)
    // shares the qualified name of `class A`'s member, and is no member.
    let in_type = !top_level(&candidate.kind, &candidate.qualified, &candidate.path);
    if in_type && typed.is_some_and(|t| owner_of(&candidate.qualified) == Some(t)) {
        return 0;
    }
    // An inline `mod m { fn f() }` is named by `m::f()` as surely as m.rs is.
    let in_named_module = hint.is_some_and(|h| owner_of(&candidate.qualified) == Some(h));
    let candidate = candidate.path.as_str();
    // A module path (`flask.Flask`, `index::read`) names where the target
    // is, so the calling file's own namesake wins only when the path names
    // the calling file: in flask's test_config.py, `flask.Flask(...)` was
    // settled on a test's subclass defined a few lines up.
    let path_hint = hint.filter(|h| {
        !h.starts_with(crate::graph::RECEIVER) && !h.chars().next().is_some_and(char::is_uppercase)
    });
    let names_caller = |h: &str| {
        std::path::Path::new(src_path)
            .file_stem()
            .is_some_and(|stem| stem == h)
    };
    if candidate == src_path && path_hint.is_none_or(names_caller) {
        return 1;
    }
    if in_named_module || hint.is_some_and(|h| names_file(h, candidate, src_path)) {
        return 2;
    }
    // Split on anything that is not part of a name, so a grouped
    // `use super::{gdrive::{url, get_json}, oauth::TokenSet}` yields
    // `gdrive` rather than one segment of braces, commas and newlines. A
    // call that names its module counts only the imports that name it too:
    // `std::env::current_dir()` is not placed by `use crate::dir::{..}`.
    fn segments(i: &str) -> Vec<&str> {
        i.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-'))
            .filter(|s| !s.is_empty())
            .collect()
    }
    if imports.iter().any(|i| {
        let parts = segments(i);
        path_hint.is_none_or(|h| parts.contains(&h))
            && parts.iter().any(|s| names_file(s, candidate, src_path))
    }) {
        return 3;
    }
    // A same-language tier was tried here and removed
    // (US-SEMLITH-0.17.0-I01). The reasoning was sound — semlith's own portal
    // is five thousand lines of JavaScript sharing twenty-five symbol names
    // with the Rust beside it, and a Rust `calls` edge does not mean a
    // JavaScript function — but the harness scored it two hits worse: it
    // settles an ambiguous name in favour of a same-language candidate that is
    // not always the right one, and a confidently wrong edge costs more than a
    // refused one. Ambiguity across languages is a ranking problem, and it is
    // not solved by preferring the nearest guess.
    UNRANKED
}

/// Whether `word` names the file at `path` — its stem, or one of its
/// directories below the ones it shares with `from`, the calling file.
///
/// `store` names `src/store.rs` and `src/store/mod.rs` alike, which is the
/// point: a module is a file or a directory depending on how the author felt
/// that day, and a hint knows neither. A directory both files sit in names
/// nothing: flask's tests call `flask.Flask(...)`, the repository's own folder
/// is called `flask`, and every candidate under it — a test's subclass of
/// `Flask` included — read as named by the hint, so the nearest won as
/// "extracted" (72 such edges in the 2026-10-14 audit's flask store).
fn names_file(word: &str, path: &str, from: &str) -> bool {
    let path = std::path::Path::new(path);
    if path.file_stem().is_some_and(|stem| stem == word) {
        return true;
    }
    let shared = shared_directories(&path.to_string_lossy(), from);
    path.parent()
        .into_iter()
        .flat_map(|parent| parent.components().skip(shared))
        .any(|component| component.as_os_str() == word)
}

/// Everything one file imports, as the raw strings the extractor recorded.
fn file_imports(db: &Connection, path: &str) -> Result<Vec<String>> {
    let mut stmt = db.prepare(
        "SELECT DISTINCT e.dst FROM edges e
         JOIN symbols s ON s.id = e.src
         JOIN files f ON f.id = s.file_id
         WHERE f.path = ?1 AND e.kind = 'imports'",
    )?;
    let rows = stmt.query_map(params![path], |r| r.get(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// Targets of `name`'s edges that the store holds no definition for.
///
/// [`edges_out`] joins to `symbols`, so an edge pointing at something outside
/// the corpus — a standard-library call, a crate that was never indexed —
/// simply does not appear there. That is the right default: a list of names
/// the store knows nothing about is noise in an answer about this codebase.
/// It is not the right *only* option, because "semlith shows no callees" and
/// "everything this calls lives outside the index" are different facts, and
/// only one of them means the graph is working.
pub fn unresolved_out(db: &Connection, name: &str, kinds: &[String]) -> Result<Vec<Unresolved>> {
    let filter = kind_predicate(kinds, "e.kind");
    let sql = format!(
        "SELECT DISTINCT e.dst, e.kind, e.confidence
         FROM symbols src
         JOIN edges e ON e.src = src.id
         WHERE src.name = ?1 AND {filter}
           AND NOT EXISTS (SELECT 1 FROM symbols s WHERE s.name = e.dst)
         ORDER BY e.dst"
    );
    let mut stmt = db.prepare(&sql)?;
    let mut binds: Vec<Value> = vec![Value::Text(name.to_string())];
    binds.extend(kinds.iter().map(|k| Value::Text(k.clone())));
    let rows = stmt.query_map(rusqlite::params_from_iter(binds), |r| {
        Ok(Unresolved {
            name: r.get(0)?,
            kind: r.get(1)?,
            confidence: r.get(2)?,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// An edge whose target this store has no definition for.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Unresolved {
    pub name: String,
    pub kind: String,
    pub confidence: String,
}

/// What points at `name`: callers, importers, references in.
///
/// The direction a reverse walk takes, and the reason `edges_dst` exists —
/// `semlith neighbors` reads it to answer "what calls this".
pub fn edges_in(db: &Connection, name: &str, kinds: &[String]) -> Result<Vec<EdgeEnd>> {
    let filter = kind_predicate(kinds, "e.kind");
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS}, e.kind, e.confidence, e.line
         FROM edges e
         JOIN symbols s ON s.id = e.src
         JOIN files f ON f.id = s.file_id
         WHERE e.dst = ?1 AND {filter}
         ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let mut binds: Vec<Value> = vec![Value::Text(name.to_string())];
    binds.extend(kinds.iter().map(|k| Value::Text(k.clone())));
    let rows = stmt.query_map(rusqlite::params_from_iter(binds), |r| {
        Ok(EdgeEnd {
            symbol: symbol_row(r)?,
            kind: r.get(8)?,
            confidence: r.get(9)?,
            // A caller is a symbol, not a name: the row came from the edge's
            // own `src` id, so there is nothing to resolve and nothing to be
            // ambiguous about. This direction is unchanged from 0.14.0.
            definitions: 1,
            from_path: None,
            from_line: None,
            line: r.get(10)?,
            means: None,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// At most `limit` of [`edges_in`], the extractor's certain edges first.
///
/// For a drawing, which has room for a few dozen callers: `new` has hundreds
/// of thousands of them on the 879k-chunk corpus, and reading them all to draw
/// sixty took most of the Graph page's twenty seconds.
pub fn edges_in_first(db: &Connection, name: &str, limit: usize) -> Result<Vec<EdgeEnd>> {
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS}, e.kind, e.confidence, e.line
         FROM edges e
         JOIN symbols s ON s.id = e.src
         JOIN files f ON f.id = s.file_id
         WHERE e.dst = ?1
         ORDER BY CASE e.confidence WHEN 'extracted' THEN 0 WHEN 'resolved' THEN 0 WHEN 'ambiguous' THEN 1 ELSE 2 END,
                  f.path, s.start_line
         LIMIT ?2"
    );
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map(params![name, limit as i64], |r| {
        Ok(EdgeEnd {
            symbol: symbol_row(r)?,
            kind: r.get(8)?,
            confidence: r.get(9)?,
            definitions: 1,
            from_path: None,
            from_line: None,
            line: r.get(10)?,
            means: None,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The names with the most edges in or out, busiest first, each counted once
/// on its own index. For the graph page's choice of where to open: a name with
/// seven hundred definitions is one candidate, not seven hundred.
pub fn busiest_names(db: &Connection, limit: usize) -> Result<Vec<String>> {
    let candidates = (limit * 4).max(64) as i64;
    let mut stmt = db.prepare(
        "WITH ins AS (SELECT dst AS name, COUNT(*) AS n FROM edges GROUP BY dst ORDER BY n DESC LIMIT ?1),
              outs AS (SELECT s.name AS name, COUNT(*) AS n FROM edges e JOIN symbols s ON s.id = e.src
                       WHERE s.kind != 'module' GROUP BY s.name ORDER BY n DESC LIMIT ?1)
         SELECT name FROM (SELECT name, n FROM ins UNION ALL SELECT name, n FROM outs)
         GROUP BY name ORDER BY SUM(n) DESC, name LIMIT ?2",
    )?;
    let rows = stmt.query_map(params![candidates, limit as i64], |r| r.get::<_, String>(0))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// One edge into a name, with the definitions of that name it resolves to.
#[derive(Debug, Clone)]
pub struct Incoming {
    /// The caller, as [`edges_in`] returns it, with the confidence the
    /// resolution earned rather than the one stored.
    pub end: EdgeEnd,
    /// Ids of the definitions of the target name this edge means: one when it
    /// settled, several when it did not.
    pub means: Vec<i64>,
}

/// What points at `name`, each edge resolved against the name's definitions
/// the way [`edges_out`] resolves it from the other end.
///
/// [`edges_in`] answers "what calls something called `search_preferring`",
/// which on a store holding two such methods is two answers mixed together.
/// This is what lets impact walk from one definition: an edge is kept for a
/// definition only when the ranking says the edge means it.
pub fn edges_in_resolved(db: &Connection, name: &str, kinds: &[String]) -> Result<Vec<Incoming>> {
    let filter = kind_predicate(kinds, "e.kind");
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS}, e.kind, e.confidence, e.line, e.hint
         FROM edges e
         JOIN symbols s ON s.id = e.src
         JOIN files f ON f.id = s.file_id
         WHERE e.dst = ?1 AND {filter}
         ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let mut binds: Vec<Value> = vec![Value::Text(name.to_string())];
    binds.extend(kinds.iter().map(|k| Value::Text(k.clone())));
    let rows = stmt.query_map(rusqlite::params_from_iter(binds), |r| {
        Ok((
            symbol_row(r)?,
            r.get::<_, String>(8)?,
            r.get::<_, String>(9)?,
            r.get::<_, Option<u32>>(10)?,
            r.get::<_, Option<String>>(11)?,
        ))
    })?;
    let rows = rows.collect::<Result<Vec<_>, _>>()?;
    if rows.is_empty() {
        return Ok(Vec::new());
    }
    let navigational = crate::graph::not_navigational("s.kind");
    let sql = format!(
        "SELECT {SYMBOL_COLUMNS} FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE s.name = ?1 AND {navigational} ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let definitions = stmt
        .query_map(params![name], symbol_row)?
        .collect::<Result<Vec<_>, _>>()?;
    let refs: Vec<&SymbolRow> = definitions.iter().collect();
    let mut imports = std::collections::HashMap::new();
    let mut out = Vec::with_capacity(rows.len());
    for (caller, kind, stored, line, hint) in rows {
        // A structural edge is the file saying where its own definition sits:
        // nothing to rank, and nothing in another file it could mean. Ranked,
        // a YAML `steps` holding its `run:` key read as maybe containing one
        // of ripgrep's Rust `run`s.
        if structural(&kind) {
            let means: Vec<i64> = definitions
                .iter()
                .filter(|d| d.path == caller.path && line.is_none_or(|l| l == d.start_line))
                .map(|d| d.id)
                .collect();
            out.push(Incoming {
                end: EdgeEnd {
                    symbol: caller,
                    kind,
                    confidence: stored,
                    definitions: definitions.len(),
                    from_path: None,
                    from_line: None,
                    line,
                    means: None,
                },
                means,
            });
            continue;
        }
        let (picked, settled) = if refs.is_empty() {
            (Vec::new(), false)
        } else {
            choose_for(
                db,
                &kind,
                &refs,
                &caller.path,
                hint.as_deref(),
                top_level(&caller.kind, &caller.qualified, &caller.path),
                &mut imports,
            )?
        };
        let means: Vec<i64> = definitions
            .iter()
            .zip(&picked)
            .filter(|(_, p)| **p)
            .map(|(d, _)| d.id)
            .collect();
        let confidence = if means.is_empty() {
            // No definition at all: an edge to a name the store holds only as
            // a heading or a key. Kept as stored so nothing is invented.
            stored.as_str()
        } else if settled && stored == crate::graph::EXTRACTED {
            crate::graph::EXTRACTED
        } else if settled {
            crate::graph::RESOLVED
        } else {
            crate::graph::AMBIGUOUS
        }
        .to_string();
        out.push(Incoming {
            end: EdgeEnd {
                symbol: caller,
                kind,
                confidence,
                definitions: definitions.len(),
                from_path: None,
                from_line: None,
                line,
                means: None,
            },
            means,
        });
    }
    Ok(out)
}

fn kind_predicate(kinds: &[String], column: &str) -> String {
    if kinds.is_empty() {
        return "1".to_string();
    }
    let holes = vec!["?"; kinds.len()].join(", ");
    format!("{column} IN ({holes})")
}

/// One recorded retrieval.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Retrieval {
    pub id: i64,
    pub at: i64,
    pub client: String,
    pub query: String,
    pub hits: i64,
    pub micros: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
    pub hash: String,
    /// Which stores answered this one retrieval, so several rows can be shown
    /// as the one search they came from. Empty for a row written before
    /// 0.20.2, which was its own retrieval.
    pub query_id: String,
    /// The model request behind the call, once a reader has looked for it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<RowUsage>,
}

/// A row's usage columns as they are stored. Every figure is optional: a
/// client that logs the model and not the tokens gets the model.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
pub struct RowUsage {
    pub model: Option<String>,
    pub input_tokens: Option<i64>,
    pub output_tokens: Option<i64>,
    pub cache_read_tokens: Option<i64>,
    pub cache_write_tokens: Option<i64>,
    pub reasoning_tokens: Option<i64>,
    pub cost_usd: Option<f64>,
    pub cost_source: Option<String>,
    /// The log the figures came from, or why there are none.
    pub source: String,
}

/// The usage columns, from column `at` of a row onwards, in the order
/// `USAGE_COLUMNS` lists them. `None` until a reader has looked.
pub const USAGE_COLUMNS: &str = "model, input_tokens, output_tokens, cache_read_tokens, \
     cache_write_tokens, reasoning_tokens, cost_usd, cost_source, usage_source";

pub fn usage_at(r: &rusqlite::Row<'_>, at: usize) -> rusqlite::Result<Option<RowUsage>> {
    let Some(source) = r.get::<_, Option<String>>(at + 8)? else {
        return Ok(None);
    };
    Ok(Some(RowUsage {
        model: r.get(at)?,
        input_tokens: r.get(at + 1)?,
        output_tokens: r.get(at + 2)?,
        cache_read_tokens: r.get(at + 3)?,
        cache_write_tokens: r.get(at + 4)?,
        reasoning_tokens: r.get(at + 5)?,
        cost_usd: r.get(at + 6)?,
        cost_source: r.get(at + 7)?,
        source,
    }))
}

/// Append one retrieval, chained to the row before it.
///
/// The chain is the point: a row cannot be quietly edited or removed without
/// every hash after it failing to recompute.
pub fn record_retrieval(db: &Connection, row: &NewRetrieval<'_>) -> Result<()> {
    record_counted(db, row, BASIS_BYTES)
}

/// The connections holding a run's snapshot ([`pin_snapshot`]), by address.
///
/// A reader's connection lives inside a `Semlith` inside a fleet behind its
/// reader's mutex, and does not move between the pin and the release, so its
/// address names it for exactly as long as the mark matters.
static PINNED: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());

fn address(db: &Connection) -> usize {
    std::ptr::from_ref(db) as usize
}

/// Hold this reader at the store as it is now, until [`unpin_snapshot`].
///
/// A run re-indexing files the store already holds deletes a file's rows and
/// writes its new ones file by file, and embeds them after; a reader between
/// those moments answered from half a run — old chunks gone, new ones not yet
/// embedded (item 17). A WAL reader inside one read transaction sees one
/// committed state however much is committed after it, so the daemon opens
/// one on every reader before the run's first write and ends it when the run
/// commits. The cost is the WAL keeping the run's pages until then.
pub fn pin_snapshot(db: &Connection) -> Result<()> {
    if !db.is_autocommit() {
        return Ok(());
    }
    db.execute_batch("BEGIN DEFERRED")?;
    // A deferred transaction takes its snapshot at its first read.
    let _: i64 = db.query_row("SELECT COUNT(*) FROM meta", [], |r| r.get(0))?;
    PINNED
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push(address(db));
    Ok(())
}

/// End [`pin_snapshot`]'s read transaction: the reader sees the run's commit.
pub fn unpin_snapshot(db: &Connection) -> Result<()> {
    let mut pinned = PINNED.lock().unwrap_or_else(|e| e.into_inner());
    let at = address(db);
    if let Some(i) = pinned.iter().position(|a| *a == at) {
        pinned.swap_remove(i);
        drop(pinned);
        if !db.is_autocommit() {
            db.execute_batch("COMMIT")?;
        }
    }
    Ok(())
}

/// Whether this connection is holding a run's snapshot.
pub fn is_pinned(db: &Connection) -> bool {
    PINNED
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .contains(&address(db))
}

/// A connection of its own for a write a pinned reader must make — a ledger
/// row, a usage fill — which its read transaction cannot: a write there would
/// fail as soon as the run had committed anything since the pin.
fn beside(db: &Connection) -> Result<Option<Connection>> {
    if !is_pinned(db) {
        return Ok(None);
    }
    match db.path().filter(|p| !p.is_empty()) {
        Some(path) => Ok(Some(open(Path::new(path))?)),
        None => Ok(None),
    }
}

/// What the whole-file side of a row was counted from: the file's bytes.
pub const BASIS_BYTES: &str = "bytes";
/// What the whole-file side of a row was counted from: the text a reader
/// extracted from it, counted the way the excerpt was.
pub const BASIS_TEXT: &str = "text";

/// [`record_retrieval`], saying what the whole-file side was counted from.
pub fn record_counted(db: &Connection, row: &NewRetrieval<'_>, basis: &str) -> Result<()> {
    if let Some(side) = beside(db)? {
        return record_counted(&side, row, basis);
    }
    // A key pasted as a search is text a person typed, and nothing else in the
    // store keeps one in full: every file passes the scan before it is held.
    // The same scan, the same marker, before the row is hashed, so the chain
    // covers what is stored (#147). A declared dummy stays as typed.
    let found: Vec<crate::keyscan::Match> = crate::keyscan::scan("", row.query)
        .into_iter()
        .filter(|m| m.dummy.is_none())
        .collect();
    let masked_text;
    let masked_row;
    let row = if found.is_empty() {
        row
    } else {
        masked_text = crate::keyscan::redact(row.query, &found);
        masked_row = NewRetrieval {
            query: &masked_text,
            ..row.clone()
        };
        &masked_row
    };
    let (client, query) = (row.client, row.query);
    let (hits, micros) = (row.hits, row.micros);
    let (excerpt_tokens, whole_file_tokens) = (row.excerpt_tokens, row.whole_file_tokens);
    // The ledger is the one write that happens on a read: a retrieval is
    // recorded by the search that answered it. It asks for the same permission
    // an index run does.
    let _writing = Writing::begin(db)?;
    let at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let key = ledger_key(db, true);
    append_chained(db, |prev| {
        let hash = v2_hash(key.as_ref(), prev, at, row, basis);
        db.execute(
            "INSERT INTO retrievals
             (at, client, query, hits, micros, excerpt_tokens, whole_file_tokens, prev, hash,
              session, tool, stale_hits, tokenizer, query_id, client_version, whole_basis, chain)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, 2)",
            params![
                at,
                client,
                query,
                hits,
                micros,
                excerpt_tokens,
                whole_file_tokens,
                prev,
                hash,
                row.session,
                row.tool,
                row.stale_hits,
                row.tokenizer,
                row.query_id,
                (!row.client_version.is_empty()).then_some(row.client_version),
                basis,
            ],
        )?;
        set_head(db, key.as_ref(), db.last_insert_rowid(), &hash)?;
        Ok(())
    })?;
    // The one place a retrieval is written, so the one place the portal's
    // ledger counter moves — every surface that records goes through here.
    crate::daemon::changes::bump(crate::daemon::changes::Domain::Ledger);
    Ok(())
}

/// One retrieval, before it has a timestamp or a place in the chain.
///
/// A struct rather than thirteen positional arguments, because two adjacent
/// `i64`s that mean different things are a bug waiting for a refactor.
#[derive(Debug, Clone)]
pub struct NewRetrieval<'a> {
    /// Who asked: one of the documented clients (`Claude Code`, `Zed`, …, see
    /// `clientid::label`), or `cli`, `portal`.
    pub client: &'a str,
    /// The client's own version string. Deliberately not in the chain, for the
    /// reason `query_id` is not: a rolled-back binary recomputes the formula it
    /// knows, and a verify that fails every row written since cries wolf.
    pub client_version: &'a str,
    /// Which conversation, so one agent's session can be read as a unit.
    pub session: &'a str,
    /// Which tool: `search`, `neighbors`, `path`, `symbol`.
    pub tool: &'a str,
    pub query: &'a str,
    pub hits: i64,
    pub micros: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
    /// How many of those hits came from a file edited since it was indexed.
    pub stale_hits: i64,
    /// What counted the two token figures. Rows counted two different ways are
    /// never summed together, so the label travels with the row rather than
    /// being assumed from its age.
    pub tokenizer: &'a str,
    /// The id shared by every row one retrieval wrote.
    ///
    /// A cross-store search writes a row in each store that answered it, so
    /// each store's chain stays its own and its token figures describe its own
    /// hits. This is what says those rows are one retrieval rather than
    /// several, and it is what "queries recorded" counts.
    pub query_id: &'a str,
}

/// A ledger row whose usage has not been looked for, as the readers in
/// `crate::usage` need it to find the model request that made the call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unfilled {
    pub id: i64,
    pub at: i64,
    pub client: String,
    pub session: String,
    pub tool: String,
    pub query: String,
    pub query_id: String,
}

/// Rows written by an AI client since `since` (unix seconds) with no usage
/// yet, oldest first. `cli` and `portal` rows have no model behind them, and
/// neither has a `raw-read` row, which the steering hook writes for a read
/// the agent made without semlith.
pub fn unfilled(db: &Connection, since: i64) -> Result<Vec<Unfilled>> {
    let mut q = db.prepare(
        "SELECT id, at, client, COALESCE(session, ''), COALESCE(tool, ''), query,
                COALESCE(query_id, '')
           FROM retrievals
          WHERE usage_source IS NULL AND at >= ?1 AND client NOT IN ('cli', 'portal')
            AND COALESCE(tool, '') NOT IN ('raw-read', 'note', 'refused')
          ORDER BY at, id",
    )?;
    let rows = q.query_map(params![since], |r| {
        Ok(Unfilled {
            id: r.get(0)?,
            at: r.get(1)?,
            client: r.get(2)?,
            session: r.get(3)?,
            tool: r.get(4)?,
            query: r.get(5)?,
            query_id: r.get(6)?,
        })
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// What a reader found for one row: the usage, or only why there is none.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Filled {
    pub model: Option<String>,
    pub tokens: Option<crate::prices::Tokens>,
    pub cost_usd: Option<f64>,
    pub cost_source: Option<String>,
    /// The log it came from, or why nothing did (`not recorded by Zed`).
    pub usage_source: String,
}

/// Write a row's usage. Every row sharing its `query_id` is the same call,
/// written once per store that answered, so all of them are filled.
pub fn fill_usage(db: &Connection, row: &Unfilled, filled: &Filled) -> Result<()> {
    if let Some(side) = beside(db)? {
        return fill_usage(&side, row, filled);
    }
    let _writing = Writing::begin(db)?;
    let t = filled.tokens;
    db.execute(
        "UPDATE retrievals
            SET model = ?1, input_tokens = ?2, output_tokens = ?3, cache_read_tokens = ?4,
                cache_write_tokens = ?5, reasoning_tokens = ?6, cost_usd = ?7,
                cost_source = ?8, usage_source = ?9
          WHERE id = ?10 OR (?11 != '' AND query_id = ?11)",
        params![
            filled.model,
            t.map(|t| t.input),
            t.map(|t| t.output),
            t.map(|t| t.cache_read),
            t.map(|t| t.cache_write),
            t.map(|t| t.reasoning),
            filled.cost_usd,
            filled.cost_source,
            filled.usage_source,
            row.id,
            row.query_id,
        ],
    )?;
    let ids: Vec<i64> = {
        let mut q =
            db.prepare("SELECT id FROM retrievals WHERE id = ?1 OR (?2 != '' AND query_id = ?2)")?;
        q.query_map(params![row.id, row.query_id], |r| r.get(0))?
            .collect::<Result<_, _>>()?
    };
    reseal(db, &ids)?;
    Ok(())
}

/// One ledger row as ledger sync sends it: what was retrieved, never the
/// query text, which this struct does not carry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncRow {
    pub id: i64,
    pub at: i64,
    pub client: String,
    pub session: String,
    pub tool: String,
    pub excerpt_tokens: i64,
    /// What a saving is credited against (0.43.0, cloud audit C26): without
    /// these a member's local use reached the org's ledger as net 0.
    pub hits: i64,
    pub whole_file_tokens: i64,
    /// `measured` or `modelled`, as [`SessionRow::tier`] says it per row.
    pub tier: &'static str,
    /// The id one retrieval shares across stores, so the cloud counts a
    /// cross-store call once. `None` on rows written before 0.20.2.
    pub query_id: Option<String>,
}

/// Rows written at or after `since` and not yet sent, oldest first, at most
/// `limit`.
pub fn unsynced(db: &Connection, since: i64, limit: usize) -> Result<Vec<SyncRow>> {
    let mut q = db.prepare(
        "SELECT id, at, client, COALESCE(session, ''), COALESCE(tool, ''), excerpt_tokens,
                hits, whole_file_tokens, tokenizer IS NOT NULL AND tokenizer <> 'chars4',
                query_id
           FROM retrievals
          WHERE synced_at IS NULL AND at >= ?1
          ORDER BY id LIMIT ?2",
    )?;
    let rows = q.query_map(params![since, limit as i64], |r| {
        Ok(SyncRow {
            id: r.get(0)?,
            at: r.get(1)?,
            client: r.get(2)?,
            session: r.get(3)?,
            tool: r.get(4)?,
            excerpt_tokens: r.get(5)?,
            hits: r.get(6)?,
            whole_file_tokens: r.get(7)?,
            tier: if r.get(8)? { "measured" } else { "modelled" },
            query_id: r.get(9)?,
        })
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// How many rows since `since` are still to send.
pub fn unsynced_count(db: &Connection, since: i64) -> Result<i64> {
    Ok(db.query_row(
        "SELECT COUNT(*) FROM retrievals WHERE synced_at IS NULL AND at >= ?1",
        params![since],
        |r| r.get(0),
    )?)
}

/// Record that these rows reached the org's ledger.
pub fn mark_synced(db: &Connection, ids: &[i64], at: i64) -> Result<()> {
    if let Some(side) = beside(db)? {
        return mark_synced(&side, ids, at);
    }
    let _writing = Writing::begin(db)?;
    let tx = rusqlite::Transaction::new_unchecked(db, rusqlite::TransactionBehavior::Immediate)?;
    {
        let mut q = tx.prepare("UPDATE retrievals SET synced_at = ?1 WHERE id = ?2")?;
        for id in ids {
            q.execute(params![at, id])?;
        }
    }
    reseal(&tx, ids)?;
    tx.commit()?;
    Ok(())
}

/// Every row with usage, keyed as [`ledger_keys`] keys it, for totals per
/// client and per model that count a cross-store call once.
pub fn usage_rows(db: &Connection, store: &str) -> Result<Vec<(String, String, RowUsage)>> {
    let mut q = db.prepare(&format!(
        "SELECT id, COALESCE(query_id, ''), client, {USAGE_COLUMNS}
           FROM retrievals WHERE model IS NOT NULL"
    ))?;
    let rows = q.query_map([], |r| {
        let id: i64 = r.get(0)?;
        let qid: String = r.get(1)?;
        let key = if qid.is_empty() {
            format!("{store}#{id}")
        } else {
            qid
        };
        Ok((
            key,
            r.get::<_, String>(2)?,
            usage_at(r, 3)?.unwrap_or_default(),
        ))
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// The hash covering one row and the one before it.
///
/// # Two formulas
///
/// A row written before 0.15.0 has four columns this one does not, and its
/// hash was computed without them. Recomputing such a row under the new
/// formula would report every 0.14.0 ledger as broken — which is the one thing
/// a verify must never do, because a verify that cries wolf is worse than no
/// verify at all.
///
/// So the formula is chosen per row, by the row itself: `tool` is NULL on
/// every row written before 0.15.0 and set on every row written since. There
/// is no version column and no migration, and a store holding rows of both
/// kinds walks end to end.
/// The file beside a store's database holding its ledger key.
const LEDGER_KEY: &str = "ledger.key";

/// What a keyed row's hash starts with, so a verify knows which formula
/// wrote it.
const KEYED: &str = "k1:";

/// This store's ledger key, made the first time a row is recorded when
/// `create`. A file of its own, 0600, rather than a meta row: whoever can
/// rewrite `store.db` could otherwise recompute every hash after an edit, and
/// a copied or synced database travels without it (audit S24). `None` for an
/// in-memory database or a key that cannot be read or made.
fn ledger_key(db: &Connection, create: bool) -> Option<[u8; 32]> {
    let file = Path::new(db.path().filter(|p| !p.is_empty())?)
        .parent()?
        .join(LEDGER_KEY);
    if let Ok(bytes) = std::fs::read(&file) {
        return bytes.try_into().ok();
    }
    if !create {
        return None;
    }
    let mut key = [0u8; 32];
    getrandom::fill(&mut key).ok()?;
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(crate::home::FILE_MODE);
    }
    match options.open(&file) {
        Ok(mut out) => {
            std::io::Write::write_all(&mut out, &key).ok()?;
            Some(key)
        }
        // Another process made it first: use theirs.
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            std::fs::read(&file).ok()?.try_into().ok()
        }
        Err(_) => None,
    }
}

/// [`chain_hash`]'s payload under the store's key, marked [`KEYED`].
/// From 0.41.0; an older binary reads these rows as not verifying.
fn keyed_chain_hash(key: &[u8; 32], prev: &str, at: i64, row: &NewRetrieval<'_>) -> String {
    format!(
        "{KEYED}{}",
        blake3::keyed_hash(key, chain_payload(prev, at, row).as_bytes()).to_hex()
    )
}

fn chain_hash(prev: &str, at: i64, row: &NewRetrieval<'_>) -> String {
    blake3::hash(chain_payload(prev, at, row).as_bytes())
        .to_hex()
        .to_string()
}

fn chain_payload(prev: &str, at: i64, row: &NewRetrieval<'_>) -> String {
    let NewRetrieval {
        client,
        query,
        hits,
        micros,
        excerpt_tokens: excerpt,
        whole_file_tokens: whole,
        ..
    } = row;
    let mut payload = format!(
        "{prev}\u{1f}{at}\u{1f}{client}\u{1f}{query}\u{1f}{hits}\u{1f}{micros}\u{1f}{excerpt}\u{1f}{whole}"
    );
    payload.push_str(&format!(
        "\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}",
        row.session, row.tool, row.stale_hits, row.tokenizer
    ));
    // `query_id` is deliberately NOT in the payload.
    //
    // Adding it would be a third formula, and a 0.20.1 binary — which is this
    // release's own rollback path — recomputes the second one. Every row
    // written since would then fail to verify under the version somebody
    // rolled back to, which is the one thing a verify must never do: a verify
    // that cries wolf is worse than no verify at all.
    //
    // What that costs is stated rather than hidden: the id can be altered
    // without breaking the chain, so the grouping of rows into retrievals is
    // not tamper-evident. What a retrieval *was* — who asked, what they asked,
    // how many hits, what it cost — is covered exactly as before.
    payload
}

/// What a v2 row's hash starts with: keyed by the store's ledger key, or
/// plain where no key could be made (an in-memory database).
const V2_KEYED: &str = "k2:";
const V2_PLAIN: &str = "v2:";

/// The meta key holding the chain's head: the newest v2 row's id and hash,
/// and a MAC over both, so deleting the newest rows fails `--verify`.
const LEDGER_HEAD: &str = "ledger_head";

/// Chain v2 (0.42.0): every column a figure reads.
///
/// v1 left out `query_id`, so rewriting every id collapsed a ledger's
/// "16 retrievals, coverage 75 %" into "1 of 1, coverage 100 %" and the chain
/// still read intact. It also had no head, so deleting the newest row
/// verified. v2 covers the id, the client's version and the whole-file
/// basis, the row says it is v2 in `chain`, and [`set_head`] records the head.
/// The late columns (usage, `synced_at`) cannot be in a hash written before
/// them; [`reseal`] covers them in `seal` whenever they are written.
///
/// An older binary does not know the formula and reports the first v2 row as
/// the break; rows it wrote itself keep verifying here, under v1.
fn v2_hash(
    key: Option<&[u8; 32]>,
    prev: &str,
    at: i64,
    row: &NewRetrieval<'_>,
    basis: &str,
) -> String {
    let payload = format!(
        "{}\u{1f}{}\u{1f}{}\u{1f}{basis}\u{1f}v2",
        chain_payload(prev, at, row),
        row.query_id,
        row.client_version,
    );
    mac(key, V2_KEYED, V2_PLAIN, &payload)
}

/// A keyed blake3 under the store's key, or a plain one marked as such.
fn mac(key: Option<&[u8; 32]>, keyed: &str, plain: &str, payload: &str) -> String {
    match key {
        Some(key) => format!(
            "{keyed}{}",
            blake3::keyed_hash(key, payload.as_bytes()).to_hex()
        ),
        None => format!("{plain}{}", blake3::hash(payload.as_bytes()).to_hex()),
    }
}

fn head_mac(key: Option<&[u8; 32]>, id: i64, hash: &str) -> String {
    mac(key, "k:", "p:", &format!("head\u{1f}{id}\u{1f}{hash}"))
}

/// Record the newest v2 row as the chain's head, in the append's transaction.
fn set_head(db: &Connection, key: Option<&[u8; 32]>, id: i64, hash: &str) -> Result<()> {
    set_meta(
        db,
        LEDGER_HEAD,
        &format!("{id}:{hash}:{}", head_mac(key, id, hash)),
    )
}

/// The late columns of a v2 row, as `seal` covers them.
fn seal_payload(r: &rusqlite::Row<'_>) -> rusqlite::Result<String> {
    let mut payload: String = r.get::<_, String>(0)?;
    for at in 1..=10 {
        let value: rusqlite::types::Value = r.get(at)?;
        payload.push('\u{1f}');
        payload.push_str(&match value {
            rusqlite::types::Value::Null => String::from("\u{0}"),
            rusqlite::types::Value::Integer(n) => n.to_string(),
            rusqlite::types::Value::Real(f) => format!("{f:?}"),
            rusqlite::types::Value::Text(t) => t,
            rusqlite::types::Value::Blob(b) => blake3::hash(&b).to_hex().to_string(),
        });
    }
    Ok(payload)
}

const SEAL_COLUMNS: &str = "hash, model, input_tokens, output_tokens, cache_read_tokens, \
     cache_write_tokens, reasoning_tokens, cost_usd, cost_source, usage_source, synced_at";

/// Rewrite `seal` on the v2 rows among `ids`, after their late columns moved.
fn reseal(db: &Connection, ids: &[i64]) -> Result<()> {
    let key = ledger_key(db, true);
    let mut read = db.prepare(&format!(
        "SELECT {SEAL_COLUMNS} FROM retrievals WHERE id = ?1 AND chain = 2"
    ))?;
    let mut write = db.prepare("UPDATE retrievals SET seal = ?1 WHERE id = ?2")?;
    for id in ids {
        let Some(payload) = read.query_row([id], seal_payload).optional()? else {
            continue;
        };
        write.execute(params![mac(key.as_ref(), "k:", "p:", &payload), id])?;
    }
    Ok(())
}

/// Append a row in the shape 0.14.0 wrote, for the test that proves a store
/// holding both kinds still verifies.
///
/// Public because that test is an integration test and cannot reach a private
/// function — and because the property it proves is worth proving. A verify
/// that reported every ledger written before this release as broken would be
/// worse than no verify at all, and nothing but a real pre-0.15.0 row in a
/// real store demonstrates that it does not.
pub fn record_legacy_retrieval(
    db: &Connection,
    client: &str,
    query: &str,
    excerpt_tokens: i64,
    whole_file_tokens: i64,
) -> Result<()> {
    let _writing = Writing::begin(db)?;
    let at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let (hits, micros) = (1, 1000);
    append_chained(db, |prev| {
        let hash = legacy_chain_hash(
            prev,
            at,
            client,
            query,
            hits,
            micros,
            excerpt_tokens,
            whole_file_tokens,
        );
        // The four 0.15.0 columns are left NULL, which is what makes this a row
        // of the older kind and what `ledger_break` reads to choose the formula.
        db.execute(
            "INSERT INTO retrievals
             (at, client, query, hits, micros, excerpt_tokens, whole_file_tokens, prev, hash)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
            params![
                at,
                client,
                query,
                hits,
                micros,
                excerpt_tokens,
                whole_file_tokens,
                prev,
                hash
            ],
        )?;
        Ok(())
    })
}

/// Append a row the way 0.15.0 to 0.41.0 wrote it — chain v1, no basis, no
/// head — for the test that proves a store holding v1 and v2 rows verifies.
pub fn record_v1_retrieval(db: &Connection, row: &NewRetrieval<'_>) -> Result<()> {
    let _writing = Writing::begin(db)?;
    let at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let key = ledger_key(db, true);
    append_chained(db, |prev| {
        let hash = match &key {
            Some(key) => keyed_chain_hash(key, prev, at, row),
            None => chain_hash(prev, at, row),
        };
        db.execute(
            "INSERT INTO retrievals
             (at, client, query, hits, micros, excerpt_tokens, whole_file_tokens, prev, hash,
              session, tool, stale_hits, tokenizer, query_id)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
            params![
                at,
                row.client,
                row.query,
                row.hits,
                row.micros,
                row.excerpt_tokens,
                row.whole_file_tokens,
                prev,
                hash,
                row.session,
                row.tool,
                row.stale_hits,
                row.tokenizer,
                row.query_id
            ],
        )?;
        Ok(())
    })
}

/// Read the chain's last hash and append the row chained to it, as one write.
///
/// Two statements on their own were a race. Two connections to one store —
/// the daemon and a `semlith search` from a terminal, or the portal's fleet
/// beside the daemon's `/mcp` fleet — could each read the same last hash and
/// each insert a row chained to it, and `ledger_break` then reported the second
/// as edited or removed though nothing was. `BEGIN IMMEDIATE` takes the write
/// lock before the read, so the second writer waits out the busy timeout for
/// the first and reads its row.
///
/// A caller already inside a transaction keeps it rather than being refused a
/// nested one; its write lock is taken at the insert, as it always was.
fn append_chained(db: &Connection, append: impl FnOnce(&str) -> Result<()>) -> Result<()> {
    let tx = if db.is_autocommit() {
        Some(rusqlite::Transaction::new_unchecked(
            db,
            rusqlite::TransactionBehavior::Immediate,
        )?)
    } else {
        None
    };
    let prev: String = db
        .query_row(
            "SELECT hash FROM retrievals ORDER BY id DESC LIMIT 1",
            [],
            |r| r.get(0),
        )
        .optional()?
        .unwrap_or_default();
    append(&prev)?;
    if let Some(tx) = tx {
        tx.commit()?;
    }
    Ok(())
}

/// The 0.14.0 formula, for rows written under it.
#[allow(clippy::too_many_arguments)]
fn legacy_chain_hash(
    prev: &str,
    at: i64,
    client: &str,
    query: &str,
    hits: i64,
    micros: i64,
    excerpt: i64,
    whole: i64,
) -> String {
    let payload = format!(
        "{prev}\u{1f}{at}\u{1f}{client}\u{1f}{query}\u{1f}{hits}\u{1f}{micros}\u{1f}{excerpt}\u{1f}{whole}"
    );
    blake3::hash(payload.as_bytes()).to_hex().to_string()
}

/// The most recent `limit` retrievals, newest first.
pub fn retrievals(db: &Connection, limit: usize) -> Result<Vec<Retrieval>> {
    let mut stmt = db.prepare(&format!(
        "SELECT id, at, client, query, hits, micros, excerpt_tokens, whole_file_tokens, hash,
                query_id, {USAGE_COLUMNS}
         FROM retrievals WHERE COALESCE(tool, '') NOT IN ('note', 'refused') ORDER BY id DESC LIMIT ?1"
    ))?;
    let rows = stmt.query_map(params![limit as i64], |r| {
        Ok(Retrieval {
            id: r.get(0)?,
            at: r.get(1)?,
            client: r.get(2)?,
            query: r.get(3)?,
            hits: r.get(4)?,
            micros: r.get(5)?,
            excerpt_tokens: r.get(6)?,
            whole_file_tokens: r.get(7)?,
            hash: r.get(8)?,
            query_id: r.get::<_, Option<String>>(9)?.unwrap_or_default(),
            usage: usage_at(r, 10)?,
        })
    })?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The rows that are an agent's retrievals, as SQL: what `ledger::figures`
/// counts by default. Not a refund (`raw-read`), not the chain's own
/// bookkeeping (a note, a refused write, an accept or revoke), and not a
/// person at the portal or the CLI. Every per-store reader below takes it, so
/// a store's card and its report say what the Ledger page says.
pub const AGENT_RETRIEVAL: &str = "COALESCE(tool, '') NOT IN ('raw-read', 'note', 'refused', 'accept', 'revoke') \
     AND client NOT IN ('cli', 'portal')";

/// Which rows of the ledger a count is about.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LedgerScope {
    /// Every retrieval.
    All,
    /// Those that found something, which are the only ones credited with a
    /// saving.
    Credited,
    /// Those credited whose tokens were estimated rather than counted by the
    /// store's own tokenizer.
    Estimated,
}

/// The distinct retrievals this store holds, as keys that can be unioned
/// across stores.
///
/// One search over six stores writes a row in each that answered it, sharing a
/// query id. Summing six stores' own counts turns that back into six
/// retrievals, which is the multiplier the Ledger page was reporting — so the
/// portal unions these keys instead of adding counts. A row written before
/// 0.20.2 has no id and is keyed by its own row id in its own store, which is
/// what it was.
pub fn ledger_keys(db: &Connection, store: &str, scope: LedgerScope) -> Result<Vec<String>> {
    let sql = match scope {
        LedgerScope::All => {
            format!("SELECT DISTINCT query_id, id FROM retrievals WHERE {AGENT_RETRIEVAL}")
        }
        LedgerScope::Credited => {
            format!(
                "SELECT DISTINCT query_id, id FROM retrievals WHERE hits > 0 AND {AGENT_RETRIEVAL}"
            )
        }
        LedgerScope::Estimated => format!(
            "SELECT DISTINCT query_id, id FROM retrievals
             WHERE hits > 0 AND (tokenizer IS NULL OR tokenizer != 'model') AND {AGENT_RETRIEVAL}"
        ),
    };
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map([], |r| {
        let id: Option<String> = r.get(0)?;
        let row: i64 = r.get(1)?;
        Ok(id.unwrap_or_else(|| format!("{store}:row:{row}")))
    })?;
    let mut out: Vec<String> = rows.collect::<Result<Vec<_>, _>>()?;
    out.sort_unstable();
    out.dedup();
    Ok(out)
}

/// `(queries, clients, excerpt tokens, whole-file tokens)` over the whole/// `(queries, clients, excerpt tokens, whole-file tokens)` over the whole
/// ledger — what the Ledger page shows.
pub fn ledger_totals(db: &Connection) -> Result<(i64, i64, i64, i64)> {
    // Retrievals, not rows. One search across six stores writes a row in each
    // store that answered it and they share one `query_id`, so counting rows
    // here is what made every figure on the Ledger page scale with how many
    // stores happened to be open. A row written before 0.20.2 has no id and is
    // its own retrieval, which is what it was.
    Ok(db.query_row(
        &format!(
            "SELECT COUNT(DISTINCT COALESCE(query_id, 'row:' || id)), COUNT(DISTINCT client),
                    COALESCE(SUM(CASE WHEN hits > 0 THEN excerpt_tokens ELSE 0 END), 0),
                    COALESCE(SUM(CASE WHEN hits > 0 THEN whole_file_tokens ELSE 0 END), 0)
               FROM retrievals WHERE {AGENT_RETRIEVAL}"
        ),
        [],
        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
    )?)
}

/// The one savings figure, with the denominators that make it readable.
///
/// `net` is what the ledger says was not read: the whole-file cost of the
/// files an answer named, less what the answer itself cost. Rows that found
/// nothing are excluded from it and counted separately — a retrieval that
/// returned no hits saved nothing, and a ledger that quietly dropped those
/// rows would report a ratio that no honest denominator supports.
///
/// `tier` is `measured` when every credited row was counted with the store's
/// own tokenizer, and `modelled` when any of them was estimated at four
/// characters per token. The two are never summed: a mixed ledger reports
/// `modelled`, because that is what the weaker half makes the whole.
///
/// # What this figure does not do
///
/// It does not deduplicate files across the retrievals of one session. If an
/// agent searches twice and both answers name `src/lib.rs`, the denominator
/// counts that file twice, and the real alternative — one read — is cheaper
/// than the figure implies. Fixing it needs the file set stored per row, which
/// this release does not add. The number is therefore an upper bound on what
/// was saved, and `semlith stats` says so rather than presenting it as exact.
pub fn ledger_savings(db: &Connection) -> Result<Savings> {
    ledger_savings_since(db, 0)
}

/// The savings, over retrievals recorded at or after `since`.
///
/// `since` of 0 is every row, which is what [`ledger_savings`] asks for and
/// what every caller before 0.27.0 meant. The ledger has always carried `at`
/// and an index on it; what it did not have was a reader that took a bound, so
/// the Reports page drew a window control over a figure that could not honour
/// one. A control that cannot change the thing it claims to change is worse
/// than no control.
pub fn ledger_savings_since(db: &Connection, since: i64) -> Result<Savings> {
    // Retrievals rather than rows on both sides of the ratio, for the reason
    // `ledger_totals` gives: the rows of one cross-store search are one search.
    // The token sums stay sums of rows, because each row holds its own store's
    // hits and nothing is double-counted by adding them.
    let (credited, net): (i64, i64) = db.query_row(
        &format!(
            "SELECT COUNT(DISTINCT COALESCE(query_id, 'row:' || id)),
                    COALESCE(SUM(whole_file_tokens - excerpt_tokens), 0)
               FROM retrievals WHERE hits > 0 AND at >= ?1 AND {AGENT_RETRIEVAL}"
        ),
        [since],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    let total: i64 = db.query_row(
        &format!(
            "SELECT COUNT(DISTINCT COALESCE(query_id, 'row:' || id)) FROM retrievals
              WHERE at >= ?1 AND {AGENT_RETRIEVAL}"
        ),
        [since],
        |r| r.get(0),
    )?;
    let estimated: i64 = db.query_row(
        &format!(
            "SELECT COUNT(DISTINCT COALESCE(query_id, 'row:' || id)) FROM retrievals
              WHERE hits > 0 AND at >= ?1 AND (tokenizer IS NULL OR tokenizer != 'model')
                AND {AGENT_RETRIEVAL}"
        ),
        [since],
        |r| r.get(0),
    )?;
    // Summed as it is, never clamped: a figure a person recomputes from the
    // rows must come out the same (the tile used to read 18 tokens above the
    // tables beside it).
    Ok(Savings {
        net,
        credited,
        total,
        measured: credited > 0 && estimated == 0,
    })
}

/// What the ledger adds up to.
#[derive(Debug, Clone, Copy, serde::Serialize)]
pub struct Savings {
    /// Whole-file tokens less excerpt tokens, over rows that found something.
    pub net: i64,
    /// How many retrievals that was over.
    pub credited: i64,
    /// How many retrievals there are in total, credited or not. The
    /// denominator, so a figure is never shown without one.
    pub total: i64,
    /// Whether every credited row was counted with the store's own tokenizer.
    pub measured: bool,
}

impl Savings {
    /// `measured` or `modelled`.
    pub fn tier(&self) -> &'static str {
        if self.measured {
            "measured"
        } else {
            "modelled"
        }
    }

    /// What share of retrievals the figure covers, as a percentage.
    pub fn coverage(&self) -> i64 {
        if self.total == 0 {
            return 0;
        }
        self.credited * 100 / self.total
    }
}

/// What the ledger says about the questions semlith did *not* answer.
///
/// `refunds` counts the whole-file reads the steering hook saw on a file this
/// store holds: semlith could have answered them and was not asked. `zero_hit`
/// counts the retrievals semlith *was* asked and found nothing for. They are
/// separate figures because they call for opposite things — a refund means the
/// agent is not reaching for semlith, a zero hit means semlith is not reaching
/// the answer — and adding them together would say neither.
///
/// `measured` is false when no hook has ever written into this store, which is
/// what makes `refunds` a floor rather than a count on such a machine.
pub fn ledger_misses(db: &Connection) -> Result<Misses> {
    let refunds: i64 = db.query_row(
        "SELECT COUNT(*) FROM retrievals WHERE tool = ?1",
        params![crate::ledger::RAW_READ],
        |r| r.get(0),
    )?;
    // A retrieval is a zero hit when none of its rows found anything: one
    // search over five stores that two answered is not three zero hits.
    let zero_hit: i64 = db.query_row(
        &format!(
            "SELECT COUNT(*) FROM (SELECT COALESCE(query_id, 'row:' || id) AS k
               FROM retrievals WHERE {AGENT_RETRIEVAL}
              GROUP BY k HAVING MAX(hits) = 0)"
        ),
        [],
        |r| r.get(0),
    )?;
    Ok(Misses {
        refunds,
        zero_hit,
        measured: refunds > 0,
    })
}

/// The two figures for what semlith did not answer.
#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
pub struct Misses {
    /// Whole-file reads of a file this store holds, seen by the steering hook.
    pub refunds: i64,
    /// Retrievals semlith answered with nothing.
    pub zero_hit: i64,
    /// Whether a hook has ever written here. Without one, `refunds` is a floor.
    pub measured: bool,
}

/// How many retrievals each client made, most first.
pub fn ledger_clients(db: &Connection) -> Result<Vec<(String, i64)>> {
    let mut stmt = db.prepare(&format!(
        "SELECT client, COUNT(DISTINCT COALESCE(query_id, 'row:' || id)) AS n FROM retrievals
          WHERE {AGENT_RETRIEVAL}
          GROUP BY client ORDER BY n DESC, client"
    ))?;
    let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// The `tool` of a ledger note: a row the chain carries that is not a
/// retrieval, and no total counts.
pub const NOTE_TOOL: &str = "note";

/// The `tool` of a call refused because the agent key is read-only; `query`
/// names the tool. Not a retrieval, so no total counts it either.
pub const REFUSED_TOOL: &str = "refused";

/// The rows a note has re-anchored the chain after: their ids.
fn acknowledged(db: &Connection) -> Result<std::collections::HashSet<i64>> {
    let mut stmt = db.prepare("SELECT query FROM retrievals WHERE tool = ?1")?;
    let rows = stmt.query_map(params![NOTE_TOOL], |r| r.get::<_, String>(0))?;
    let mut out = std::collections::HashSet::new();
    for text in rows {
        let text = text?;
        if let Some(rest) = text.split("after row ").nth(1) {
            let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
            if let Ok(id) = digits.parse() {
                out.insert(id);
            }
        }
    }
    Ok(out)
}

/// Re-anchor the chain after a row that does not verify, by appending a
/// note row onto the current head (0.35.0's Re-verify with repair).
///
/// Nothing recorded is edited or deleted: the note says which row broke, and
/// [`ledger_break`] accepts that row as it stands from then on. The edit is
/// still visible, in the note, which is what an audit trail owes its reader.
pub fn ledger_note(db: &Connection, broken: i64) -> Result<()> {
    let query = format!("chain re-anchored after row {broken} was edited or removed");
    record_retrieval(
        db,
        &NewRetrieval {
            client_version: "",
            client: "semlith",
            session: "",
            tool: NOTE_TOOL,
            query: &query,
            hits: 0,
            micros: 0,
            excerpt_tokens: 0,
            whole_file_tokens: 0,
            stale_hits: 0,
            tokenizer: crate::ledger::CHARS4,
            query_id: "",
        },
    )
}

/// Append a note for every unacknowledged break, first to last, and say which
/// rows they were. Bounded, so a chain broken at every row is not a loop.
pub fn ledger_repair(db: &Connection) -> Result<Vec<i64>> {
    let mut noted = Vec::new();
    while let Some(id) = ledger_break(db)? {
        if noted.contains(&id) || noted.len() >= 1_000 {
            break;
        }
        ledger_note(db, id)?;
        noted.push(id);
    }
    Ok(noted)
}

/// When a ledger row was written, by id.
pub fn retrieval_at(db: &Connection, id: i64) -> Result<Option<i64>> {
    Ok(db
        .query_row(
            "SELECT at FROM retrievals WHERE id = ?1",
            params![id],
            |r| r.get(0),
        )
        .optional()?)
}

/// How many rows the chain holds, notes included: what a verify walked.
pub fn ledger_rows(db: &Connection) -> Result<i64> {
    Ok(db.query_row("SELECT COUNT(*) FROM retrievals", [], |r| r.get(0))?)
}

/// Re-walk the chain and return the id of the first row that does not verify.
///
/// `None` means the ledger is intact. A row a note re-anchored after
/// ([`ledger_note`]) is accepted as it stands, and the walk goes on from it.
pub fn ledger_break(db: &Connection) -> Result<Option<i64>> {
    let acked = acknowledged(db)?;
    let key = ledger_key(db, false);
    let mut stmt = db.prepare(
        "SELECT id, at, client, query, hits, micros, excerpt_tokens, whole_file_tokens, prev, hash,
                session, tool, stale_hits, tokenizer, chain, COALESCE(query_id, ''),
                COALESCE(client_version, ''), COALESCE(whole_basis, ''), seal
         FROM retrievals ORDER BY id",
    )?;
    let mut sealed = db.prepare(&format!(
        "SELECT {SEAL_COLUMNS} FROM retrievals WHERE id = ?1"
    ))?;
    // The head: the newest v2 row as it was written. A v2 row after it, or no
    // row at its id with its hash, is a tail somebody cut or a row somebody
    // forged; v1 rows after it are an older binary's, and allowed.
    let head: Option<(i64, String)> = get_meta(db, LEDGER_HEAD)?.and_then(|text| {
        let mut parts = text.splitn(3, ':');
        let id: i64 = parts.next()?.parse().ok()?;
        let rest = parts.next()?;
        // The hash itself holds a colon (`k2:…`), so it is two parts.
        let mut tail = parts.next()?.splitn(2, ':');
        let hash = format!("{rest}:{}", tail.next()?);
        let mac = tail.next()?;
        (head_mac(key.as_ref(), id, &hash) == mac).then_some((id, hash))
    });
    // Erasing every row is one documented `DELETE`, and an empty ledger has
    // nothing left to vouch for; a head with no rows under it is that, not a
    // cut tail.
    let empty: bool = db.query_row("SELECT NOT EXISTS (SELECT 1 FROM retrievals)", [], |r| {
        r.get(0)
    })?;
    if empty {
        return Ok(None);
    }
    let head_claimed = get_meta(db, LEDGER_HEAD)?.is_some();
    if head_claimed && head.is_none() {
        // A head that does not verify is a head somebody wrote by hand.
        return Ok(Some(db.query_row(
            "SELECT COALESCE(MAX(id), 0) FROM retrievals",
            [],
            |r| r.get(0),
        )?));
    }
    let mut head_seen = false;
    let mut rows = stmt.query([])?;
    let mut expected = String::new();
    while let Some(r) = rows.next()? {
        let (id, at): (i64, i64) = (r.get(0)?, r.get(1)?);
        let client: String = r.get(2)?;
        let query: String = r.get(3)?;
        let (hits, micros, excerpt, whole): (i64, i64, i64, i64) =
            (r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?);
        let prev: String = r.get(8)?;
        let hash: String = r.get(9)?;
        if acked.contains(&id) {
            expected = hash;
            continue;
        }
        if prev != expected {
            return Ok(Some(id));
        }
        // `tool` is NULL on every row written before 0.15.0 and set on every
        // row written since, which is what says which formula wrote this hash.
        let tool: Option<String> = r.get(11)?;
        let chain: Option<i64> = r.get(14)?;
        if let Some((head_id, head_hash)) = &head {
            if id == *head_id {
                if hash != *head_hash {
                    return Ok(Some(id));
                }
                head_seen = true;
            } else if id > *head_id && chain == Some(2) && !acked.contains(&id) {
                return Ok(Some(id));
            }
        }
        let recomputed = match tool {
            Some(tool) if chain == Some(2) => {
                let session: String = r.get(10)?;
                let stale: i64 = r.get(12)?;
                let tokenizer: String = r.get(13)?;
                let query_id: String = r.get(15)?;
                let version: String = r.get(16)?;
                let basis: String = r.get(17)?;
                let seal: Option<String> = r.get(18)?;
                let row = NewRetrieval {
                    client_version: &version,
                    client: &client,
                    session: &session,
                    tool: &tool,
                    query: &query,
                    hits,
                    micros,
                    excerpt_tokens: excerpt,
                    whole_file_tokens: whole,
                    stale_hits: stale,
                    tokenizer: &tokenizer,
                    query_id: &query_id,
                };
                if hash.starts_with(V2_KEYED) && key.is_none() {
                    return Ok(Some(id));
                }
                let k = if hash.starts_with(V2_KEYED) {
                    key.as_ref()
                } else {
                    None
                };
                // The late columns: a seal over what they say now, or none at
                // all while none of them has been written.
                let late = sealed.query_row([id], seal_payload)?;
                let blank = late.split('\u{1f}').skip(1).all(|v| v == "\u{0}");
                match seal {
                    Some(seal) if seal != mac(k, "k:", "p:", &late) => return Ok(Some(id)),
                    None if !blank => return Ok(Some(id)),
                    _ => {}
                }
                v2_hash(k, &prev, at, &row, &basis)
            }
            Some(tool) => {
                let session: String = r.get(10)?;
                let stale: i64 = r.get(12)?;
                let tokenizer: String = r.get(13)?;
                let row = NewRetrieval {
                    client_version: "",
                    client: &client,
                    session: &session,
                    tool: &tool,
                    query: &query,
                    hits,
                    micros,
                    excerpt_tokens: excerpt,
                    whole_file_tokens: whole,
                    stale_hits: stale,
                    tokenizer: &tokenizer,
                    // Not covered by the hash; see `chain_hash`.
                    query_id: "",
                };
                match (hash.starts_with(KEYED), &key) {
                    (false, _) => chain_hash(&prev, at, &row),
                    (true, Some(key)) => keyed_chain_hash(key, &prev, at, &row),
                    // A keyed row with no key beside the database cannot be
                    // verified, so it is the break.
                    (true, None) => return Ok(Some(id)),
                }
            }
            None => legacy_chain_hash(&prev, at, &client, &query, hits, micros, excerpt, whole),
        };
        if recomputed != hash {
            return Ok(Some(id));
        }
        expected = hash;
    }
    if let Some((head_id, _)) = head
        && !head_seen
        && !acked.contains(&head_id)
    {
        // The head's row is gone: the tail was cut.
        return Ok(Some(head_id));
    }
    Ok(None)
}

/// One ledger row, every column a figure is made of.
///
/// The input to `ledger::figures`, the one aggregation every surface renders
/// (0.42.0). Read whole rather than summed here, because the figures union
/// retrievals across stores (one search over five stores is five rows and one
/// query), and SQL inside one store cannot see the other four.
#[derive(Debug, Clone, serde::Serialize)]
pub struct LedgerFact {
    pub id: i64,
    pub at: i64,
    pub client: String,
    pub session: String,
    /// Empty on a row written before 0.15.0.
    pub tool: String,
    pub query: String,
    pub hits: i64,
    pub micros: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
    pub stale_hits: i64,
    pub tokenizer: String,
    /// Empty on a row written before 0.20.2, which was its own retrieval.
    pub query_id: String,
    pub client_version: String,
    /// `bytes`, `text`, or empty for a row written before 0.42.0 (bytes).
    pub whole_basis: String,
    /// 2 for chain v2, 1 otherwise.
    pub chain: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<RowUsage>,
}

/// Every ledger row with `since <= at < until`, oldest first.
pub fn ledger_facts(db: &Connection, since: i64, until: Option<i64>) -> Result<Vec<LedgerFact>> {
    let mut stmt = db.prepare(&format!(
        "SELECT id, at, client, COALESCE(session, ''), COALESCE(tool, ''), query, hits, micros,
                excerpt_tokens, whole_file_tokens, COALESCE(stale_hits, 0),
                COALESCE(tokenizer, ''), COALESCE(query_id, ''), COALESCE(client_version, ''),
                COALESCE(whole_basis, ''), COALESCE(chain, 1), {USAGE_COLUMNS}
           FROM retrievals WHERE at >= ?1 AND at < ?2 ORDER BY id"
    ))?;
    let rows = stmt.query_map(params![since, until.unwrap_or(i64::MAX)], |r| {
        Ok(LedgerFact {
            id: r.get(0)?,
            at: r.get(1)?,
            client: r.get(2)?,
            session: r.get(3)?,
            tool: r.get(4)?,
            query: r.get(5)?,
            hits: r.get(6)?,
            micros: r.get(7)?,
            excerpt_tokens: r.get(8)?,
            whole_file_tokens: r.get(9)?,
            stale_hits: r.get(10)?,
            tokenizer: r.get(11)?,
            query_id: r.get(12)?,
            client_version: r.get(13)?,
            whole_basis: r.get(14)?,
            chain: r.get(15)?,
            usage: usage_at(r, 16)?,
        })
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// The text the store holds for `path`, stitched by line from its chunks.
///
/// The whole-file side of a row for a file a reader extracted (a PDF, an
/// Office file): reading the file would have meant reading this text, not its
/// bytes — 2.2 MB of PDF is 45,849 characters. `None` for a file not held.
pub fn held_text(db: &Connection, path: &str) -> Result<Option<String>> {
    let mut stmt = db.prepare(
        "SELECT c.start_line, c.text FROM chunks c JOIN files f ON f.id = c.file_id
          WHERE f.path = ?1 ORDER BY c.start_line, c.id",
    )?;
    let mut lines: std::collections::BTreeMap<i64, String> = Default::default();
    let mut any = false;
    let rows = stmt.query_map(params![path], |r| {
        Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
    })?;
    for row in rows {
        let (start, text) = row?;
        any = true;
        for (offset, line) in text.split('\n').enumerate() {
            lines
                .entry(start + offset as i64)
                .or_insert_with(|| line.to_string());
        }
    }
    Ok(any.then(|| lines.into_values().collect::<Vec<_>>().join("\n")))
}

/// The total bytes of every file a grep for `name` would have to read.
///
/// The honest denominator for a graph answer's saving. A search's denominator
/// is the files its hits came from; a graph answer has no hits, but it does
/// have an answer that would otherwise have been assembled by grepping for the
/// name and reading what came back. These are those files: the ones that
/// define the name, and the ones whose code points at it.
pub fn grep_cost(db: &Connection, name: &str) -> Result<i64> {
    Ok(db.query_row(
        "SELECT COALESCE(SUM(bytes), 0) FROM files WHERE id IN (
            SELECT s.file_id FROM symbols s WHERE s.name = ?1
            UNION
            SELECT s.file_id FROM symbols s JOIN edges e ON e.src = s.id WHERE e.dst = ?1
         )",
        params![name],
        |r| r.get(0),
    )?)
}

/// Whether this store has `path` indexed.
///
/// Compared the way every filter compares a path — normalised separators,
/// lowercased — so a Windows store answers the same question a unix one does
/// about the same file. The steering hook's ledger row depends on it: a raw
/// read is only a refund against the store that could have answered it.
pub fn holds_path(db: &Connection, path: &str) -> Result<bool> {
    // Canonical, because that is the form a store records and a caller may hand
    // over whatever the client said — a relative path, a symlink, or on macOS a
    // `/var` that is really `/private/var`.
    let canonical = crate::canonical(std::path::Path::new(path));
    let wanted = canonical
        .to_string_lossy()
        .to_ascii_lowercase()
        .replace('\\', "/");
    let sql = format!("SELECT 1 FROM files f WHERE {GLOB_PATH} = ?1 LIMIT 1");
    Ok(db
        .query_row(&sql, params![wanted], |_| Ok(()))
        .optional()?
        .is_some())
}

/// One definition's span and identity: `(start, end, name, kind)`.
pub type SymbolSpan = (u32, u32, String, String);

/// Every symbol defined in each of `paths`.
///
/// What turns a line range into a place a person recognises. A hit that says
/// `src/store.rs:1041-1090` makes a reader open the file to find out what is
/// there; one that says `record_retrieval` does not.
///
/// Read per file rather than per hit, because eight hits in one file are one
/// question about that file.
pub fn symbols_in_files(
    db: &Connection,
    paths: &[String],
) -> Result<std::collections::HashMap<String, Vec<SymbolSpan>>> {
    let mut out: std::collections::HashMap<String, Vec<SymbolSpan>> = Default::default();
    if paths.is_empty() {
        return Ok(out);
    }
    let holes = vec!["?"; paths.len()].join(", ");
    let sql = format!(
        "SELECT f.path, s.start_line, s.end_line, s.name, s.kind
         FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE f.path IN ({holes}) AND s.kind != 'module'
         ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let args = paths.iter().cloned().map(Value::Text);
    let mut rows = stmt.query(rusqlite::params_from_iter(args))?;
    while let Some(r) = rows.next()? {
        let path: String = r.get(0)?;
        out.entry(path)
            .or_default()
            .push((r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?));
    }
    Ok(out)
}

/// `(bytes, indexed_at)` for each of `paths` the store knows.
///
/// The cheap half of a freshness check: what the store recorded about a file
/// when it read it. The other half is one `stat` of the file as it is now.
pub fn file_stamps(
    db: &Connection,
    paths: &[String],
) -> Result<std::collections::HashMap<String, Stamp>> {
    if paths.is_empty() {
        return Ok(Default::default());
    }
    let holes = vec!["?"; paths.len()].join(", ");
    let sql =
        format!("SELECT path, bytes, indexed_at, read_mtime FROM files WHERE path IN ({holes})");
    let mut stmt = db.prepare(&sql)?;
    let args = paths.iter().cloned().map(Value::Text);
    let rows = stmt.query_map(rusqlite::params_from_iter(args), |r| {
        Ok((
            r.get::<_, String>(0)?,
            Stamp {
                bytes: r.get(1)?,
                indexed_at: r.get(2)?,
                read_mtime: r.get(3)?,
            },
        ))
    })?;
    Ok(rows.collect::<Result<std::collections::HashMap<_, _>, _>>()?)
}

/// What a file looked like when it was read for the store, and the one rule
/// every surface judges "edited since it was indexed" by.
#[derive(Debug, Clone, Copy)]
pub struct Stamp {
    pub bytes: i64,
    pub indexed_at: i64,
    /// The file's modification time when it was read, in nanoseconds. `None`
    /// on a row an older binary wrote.
    pub read_mtime: Option<i64>,
}

/// A file's modification time in nanoseconds since the epoch.
pub fn mtime_ns(meta: &std::fs::Metadata) -> Option<i64> {
    meta.modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .map(|d| d.as_nanos() as i64)
}

impl Stamp {
    /// Whether the file on disk is still the one the store read.
    ///
    /// With the mtime the read saw, the two must be equal. Before 0.40.0 the
    /// rule was "not modified after `indexed_at`", and `indexed_at` is when the
    /// row was written, after the read: an edit that kept the size and landed
    /// between the read and the write read as fresh, and the store's old text
    /// was served as current. A row an older binary wrote keeps that rule.
    pub fn fresh(&self, meta: &std::fs::Metadata) -> bool {
        if meta.len() as i64 != self.bytes {
            return false;
        }
        match self.read_mtime {
            Some(ns) => mtime_ns(meta) == Some(ns),
            None => meta
                .modified()
                .ok()
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .is_none_or(|d| d.as_secs() as i64 <= self.indexed_at),
        }
    }
}

/// Record the modification time a file's read saw. See [`Stamp::fresh`].
pub fn set_read_mtime(db: &Connection, file_id: i64, read_mtime: Option<i64>) -> Result<()> {
    db.prepare_cached("UPDATE files SET read_mtime = ?1 WHERE id = ?2")?
        .execute(params![read_mtime, file_id])?;
    Ok(())
}

/// The classes a not-indexed row falls into (2.3), and the dummy list.
pub mod class {
    /// (a) a secret-shaped value in the text. Reviewable.
    pub const CONTENT: &str = "content";
    /// (b) a credential file by name or folder. Never acceptable.
    pub const CREDENTIAL: &str = "credential";
    /// (c) over the size cap, or inside a pruned generated folder. Reviewable.
    pub const POLICY: &str = "policy";
    /// (d) empty, binary, no text, unreadable, not a regular file.
    pub const UNINDEXABLE: &str = "unindexable";
    /// (e) `.gitignore`, `.semlithignore`, or outside the store's roots.
    pub const EXCLUDED: &str = "excluded";
    /// Indexed: every match was a declared test dummy.
    pub const DUMMY: &str = "dummy";
    /// (f) a parser crashed, ran out of memory or out of time on it. The rule
    /// is the reason. Not reviewable — there is nothing in it to review — but
    /// accepting it tries it once more.
    pub const CRASHED: &str = "crashed";

    /// Whether a person may accept a row of this class.
    pub fn reviewable(class: &str) -> bool {
        matches!(class, CONTENT | POLICY)
    }
}

/// One file or folder that was not indexed, and why.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Refused {
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    pub class: String,
    pub rule: String,
    /// What the scan found, masked. Empty for anything but a content row
    /// and a dummy row.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub matches: Vec<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<u8>,
    /// Files the row stands for: one, or a folder's count.
    pub files: u32,
    pub first_seen: i64,
    pub last_seen: i64,
    /// Whether a person may accept it.
    pub reviewable: bool,
    /// The acceptance on this path, when there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accepted: Option<String>,
}

/// Record that `path` was not indexed. The first time it was seen is kept.
#[allow(clippy::too_many_arguments)]
pub fn refuse(
    db: &Connection,
    path: &str,
    class: &str,
    rule: &str,
    matches: &[crate::keyscan::Match],
    files: u32,
    now: i64,
) -> Result<()> {
    let confidence = matches
        .iter()
        .filter(|m| m.dummy.is_none() || class == class::DUMMY)
        .map(|m| m.confidence)
        .max();
    let json = if matches.is_empty() {
        None
    } else {
        Some(serde_json::to_string(matches)?)
    };
    db.execute(
        "INSERT INTO refusals (path, class, rule, matches, confidence, files, first_seen, last_seen)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)
         ON CONFLICT(path) DO UPDATE SET class = excluded.class, rule = excluded.rule,
           matches = excluded.matches, confidence = excluded.confidence,
           files = excluded.files, last_seen = excluded.last_seen",
        params![path, class, rule, json, confidence, files, now],
    )?;
    Ok(())
}

/// Turn on FTS5's secure delete for `chunks_fts`, if it is not on: a removed
/// row's terms then leave the index's segments at once rather than at their
/// next merge, so a file refused for a secret leaves no searchable term
/// behind. A setting the index keeps; older binaries read it unchanged.
pub fn secure_delete_fts(db: &Connection) -> Result<()> {
    let set = db
        .query_row(
            "SELECT 1 FROM chunks_fts_config WHERE k = 'secure-delete' AND v = 1",
            [],
            |_| Ok(()),
        )
        .optional()?
        .is_some();
    if !set {
        db.execute(
            "INSERT INTO chunks_fts(chunks_fts, rank) VALUES('secure-delete', 1)",
            [],
        )?;
    }
    Ok(())
}

/// Forget that `path` was not indexed: it has been, or it is gone.
pub fn unrefuse(db: &Connection, path: &str) -> Result<()> {
    db.execute("DELETE FROM refusals WHERE path = ?1", params![path])?;
    Ok(())
}

/// Every not-indexed row, reviewable first, then by class and path.
pub fn refusals(db: &Connection) -> Result<Vec<Refused>> {
    let mut stmt = db.prepare(
        "SELECT r.path, r.class, r.rule, r.matches, r.confidence, r.files, r.first_seen,
                r.last_seen, a.mode
         FROM refusals r LEFT JOIN acceptances a ON a.path = r.path
         ORDER BY CASE r.class WHEN 'content' THEN 0 WHEN 'policy' THEN 1 WHEN 'credential' THEN 2
                  WHEN 'crashed' THEN 3 WHEN 'dummy' THEN 4 WHEN 'unindexable' THEN 5 ELSE 6 END, r.path",
    )?;
    let rows = stmt.query_map([], |r| {
        let class: String = r.get(1)?;
        let matches: Option<String> = r.get(3)?;
        Ok(Refused {
            path: r.get(0)?,
            reviewable: class::reviewable(&class),
            class,
            rule: r.get(2)?,
            matches: matches
                .and_then(|m| serde_json::from_str(&m).ok())
                .unwrap_or_default(),
            confidence: r.get(4)?,
            files: r.get(5)?,
            first_seen: r.get(6)?,
            last_seen: r.get(7)?,
            accepted: r.get(8)?,
        })
    })?;
    let mut rows = rows.collect::<Result<Vec<_>, _>>()?;
    // Accepted files are indexed and off the list proper, and still listed:
    // a person who accepted one has to be able to find it again to revoke it.
    for a in acceptances(db)? {
        if rows.iter().any(|r| r.path == a.path) {
            continue;
        }
        rows.push(Refused {
            path: a.path,
            class: a.class.clone(),
            rule: format!("accepted from the {} ({})", a.source, a.mode),
            matches: Vec::new(),
            confidence: a.confidence,
            files: 1,
            first_seen: a.at,
            last_seen: a.at,
            reviewable: class::reviewable(&a.class) || a.class == class::DUMMY,
            accepted: Some(a.mode),
        });
    }
    Ok(rows)
}

/// One not-indexed row, by exact path.
pub fn refusal(db: &Connection, path: &str) -> Result<Option<Refused>> {
    Ok(refusals(db)?.into_iter().find(|r| r.path == path))
}

/// A person's decision about one file.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Acceptance {
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    pub class: String,
    pub mode: String,
    #[serde(skip)]
    pub fingerprints: Vec<String>,
    pub confidence: Option<u8>,
    pub at: i64,
    pub source: String,
}

pub fn acceptance(db: &Connection, path: &str) -> Result<Option<Acceptance>> {
    Ok(db
        .query_row(
            "SELECT path, class, mode, fingerprints, confidence, at, source
             FROM acceptances WHERE path = ?1",
            params![path],
            |r| {
                let prints: String = r.get(3)?;
                Ok(Acceptance {
                    path: r.get(0)?,
                    class: r.get(1)?,
                    mode: r.get(2)?,
                    fingerprints: serde_json::from_str(&prints).unwrap_or_default(),
                    confidence: r.get(4)?,
                    at: r.get(5)?,
                    source: r.get(6)?,
                })
            },
        )
        .optional()?)
}

/// Every acceptance, for counts and for the folders the walk must not prune.
pub fn acceptances(db: &Connection) -> Result<Vec<Acceptance>> {
    let mut stmt = db.prepare("SELECT path FROM acceptances ORDER BY path")?;
    let paths: Vec<String> = stmt
        .query_map([], |r| r.get(0))?
        .collect::<Result<Vec<_>, _>>()?;
    let mut out = Vec::new();
    for path in paths {
        if let Some(a) = acceptance(db, &path)? {
            out.push(a);
        }
    }
    Ok(out)
}

pub fn accept(db: &Connection, a: &Acceptance) -> Result<()> {
    db.execute(
        "INSERT INTO acceptances (path, class, mode, fingerprints, confidence, at, source)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
         ON CONFLICT(path) DO UPDATE SET class = excluded.class, mode = excluded.mode,
           fingerprints = excluded.fingerprints, confidence = excluded.confidence,
           at = excluded.at, source = excluded.source",
        params![
            a.path,
            a.class,
            a.mode,
            serde_json::to_string(&a.fingerprints)?,
            a.confidence,
            a.at,
            a.source
        ],
    )?;
    Ok(())
}

pub fn revoke(db: &Connection, path: &str) -> Result<bool> {
    Ok(db.execute("DELETE FROM acceptances WHERE path = ?1", params![path])? > 0)
}

/// The per-store salt fingerprints are keyed with, made on first need.
///
/// Random, from the operating system, and never leaves the store: a
/// fingerprint without it confirms nothing about a guessed value.
pub fn salt(db: &Connection) -> Result<[u8; 32]> {
    if let Some(hex) = get_meta(db, "secret_salt")?
        && let Some(bytes) = unhex(&hex)
    {
        return Ok(bytes);
    }
    let mut bytes = [0u8; 32];
    getrandom::fill(&mut bytes).map_err(|e| anyhow::anyhow!("no random source: {e}"))?;
    let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
    set_meta(db, "secret_salt", &hex)?;
    Ok(bytes)
}

/// The salt, when a store has one. A read-only caller cannot make one, and
/// a store without one has no acceptances to compare against.
pub fn salt_if_any(db: &Connection) -> Result<Option<[u8; 32]>> {
    Ok(get_meta(db, "secret_salt")?.and_then(|h| unhex(&h)))
}

fn unhex(hex: &str) -> Option<[u8; 32]> {
    if hex.len() != 64 || !hex.is_ascii() {
        return None;
    }
    let bytes: Vec<u8> = (0..32)
        .map(|i| u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok())
        .collect::<Option<Vec<u8>>>()?;
    bytes.try_into().ok()
}

/// A chunk's first line, last line and id.
pub type ChunkSpan = (u32, u32, i64);

/// A file's id and its chunks' line spans, for writing its graph again.
pub fn graph_input(db: &Connection, path: &str) -> Result<Option<(i64, Vec<ChunkSpan>)>> {
    let Some(file_id) = db
        .query_row("SELECT id FROM files WHERE path = ?1", params![path], |r| {
            r.get::<_, i64>(0)
        })
        .optional()?
    else {
        return Ok(None);
    };
    let mut stmt = db.prepare(
        "SELECT start_line, end_line, id FROM chunks WHERE file_id = ?1 ORDER BY start_line",
    )?;
    let spans = stmt
        .query_map(params![file_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
        .collect::<Result<Vec<_>, _>>()?;
    Ok(Some((file_id, spans)))
}

/// Remove one file's symbols, and with them the edges that leave them.
pub fn delete_graph(db: &Connection, file_id: i64) -> Result<()> {
    db.execute(
        "DELETE FROM edges WHERE src IN (SELECT id FROM symbols WHERE file_id = ?1)",
        params![file_id],
    )?;
    db.execute("DELETE FROM symbols WHERE file_id = ?1", params![file_id])?;
    Ok(())
}

/// Bring an unchanged file's `bytes` and `indexed_at` up to what is on disk,
/// when the file's size or mtime has moved past the row.
///
/// Only called once the content hash has matched, so the chunks are exactly
/// as current as the file; it is the stamps that freshness is judged by that
/// were behind. A row already current is not written, so an unchanged tree's
/// pass writes nothing.
pub fn heal_stamps(
    db: &Connection,
    path: &str,
    bytes: i64,
    mtime: i64,
    read_mtime: Option<i64>,
    now: i64,
) -> Result<()> {
    db.execute(
        "UPDATE files SET bytes = ?2, indexed_at = MAX(?3, ?4), read_mtime = ?5
         WHERE path = ?1 AND (bytes != ?2 OR indexed_at < ?3 OR read_mtime IS NOT ?5)",
        params![path, bytes, mtime, now, read_mtime],
    )?;
    Ok(())
}

/// The newest `indexed_at` this store holds, or `None` when it holds nothing.
///
/// The store's own answer to "last write", which is what the Stores page's
/// column says it shows. The daemon used to answer it from a counter that
/// started at zero every time it launched, so a store with 438 files in it read
/// `never` until something wrote to it again — finding 1.7 of the 2026-09-17
/// drive.
pub fn last_write(db: &Connection) -> Result<Option<i64>> {
    let at: Option<i64> = db.query_row("SELECT MAX(indexed_at) FROM files", [], |r| r.get(0))?;
    Ok(at)
}

/// `(symbols, edges)` — the graph's size, for `stats` and the portal.
pub fn graph_stats(db: &Connection) -> Result<(i64, i64)> {
    let symbols: i64 = db.query_row("SELECT COUNT(*) FROM symbols", [], |r| r.get(0))?;
    let edges: i64 = db.query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))?;
    Ok((symbols, edges))
}

/// `(files, chunks, indexed bytes)`
/// Whether this store can still be read, as cheaply as that can be asked.
///
/// One row out of each of the two large tables, by the rowid index. It exists
/// because the obvious probe — `stats()` below — is three full scans, and this
/// runs once per store on every aggregating read, which includes every search.
/// Measured on a 10 390-chunk store: `stats()` 2.65 ms, this 0.24 ms, and the
/// gap widens linearly because one is O(n) and the other is O(log n).
///
/// It is not weaker for being cheaper. What it has to catch is a database that
/// opened and cannot be read now — truncated by a killed index run, on a volume
/// that was unplugged — and a btree descent into a page that is no longer there
/// fails exactly as a scan would. What it deliberately does not do is read
/// `meta` and call that proof: `Semlith::open` already read `meta`, and page one
/// of a truncated file is usually the part that survived.
///
/// An empty table is not a failure: a store with nothing indexed yet is a store
/// that reads fine and holds nothing.
pub fn readable(db: &Connection) -> Result<()> {
    for table in ["files", "chunks"] {
        let sql = format!("SELECT id FROM {table} ORDER BY id DESC LIMIT 1");
        let mut stmt = db.prepare(&sql)?;
        let mut rows = stmt.query([])?;
        // Stepped rather than collected: the error this is looking for arrives
        // on the step, and `Option` is the empty-table case rather than a fault.
        let _: Option<i64> = rows.next()?.map(|r| r.get(0)).transpose()?;
    }
    Ok(())
}

pub fn stats(db: &Connection) -> Result<(i64, i64, i64)> {
    let files: i64 = db.query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))?;
    let chunks: i64 = db.query_row("SELECT COUNT(*) FROM chunks", [], |r| r.get(0))?;
    let bytes: i64 = db.query_row("SELECT COALESCE(SUM(bytes), 0) FROM files", [], |r| {
        r.get(0)
    })?;
    Ok((files, chunks, bytes))
}

/// Everything the `Inside the index` page shows about one store.
///
/// Measured, not estimated — that is the page's own claim about itself and so
/// it is the contract for this function. Where a figure cannot be measured
/// from what the store holds, it is not here; the page says what it does not
/// know rather than printing a plausible number.
///
/// One pass over `chunks` is the expensive part: the text of every chunk is
/// read to count lines, words, characters and blanks. A 130k-chunk store is
/// tens of megabytes, which is a second or so — this runs when the page is
/// opened, not on every write.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Corpus {
    pub files: i64,
    pub chunks: i64,
    pub bytes: i64,
    /// Lines covered by chunks. A file's lines are `MAX(end_line)` over its
    /// chunks, which is the file's length wherever it was chunked whole.
    pub lines: i64,
    pub words: i64,
    pub characters: i64,
    pub blank_lines: i64,
    /// Lines whose first non-space characters open a comment in that file's
    /// language. A heuristic over a short table of openers, named as one on
    /// the page.
    pub comment_lines: i64,
    /// Per language, by line: the mix the page draws as a stacked bar.
    pub languages: Vec<LanguageLines>,
    /// Files by the kind of thing they are, for the prose panel.
    pub kinds: Vec<FileKind>,
    pub longest_file: Option<FileLines>,
    /// The most folders any indexed path descends through.
    pub deepest_path: i64,
    /// Unix seconds of the first and last `indexed_at` in the store.
    pub first_indexed: i64,
    pub last_indexed: i64,
    /// Chunks added per month, oldest first, as `("2026-09", 9610)`.
    pub months: Vec<MonthCount>,
    /// One vector per chunk, of this many numbers each.
    pub vector_dim: i64,
    pub symbols: i64,
    pub edges: i64,
    /// Edges by tier, in the order the graph rail lists them. Decided by
    /// `coverage_by_language`, which is the one rule for this.
    pub tiers: Vec<KindCount>,
    /// Edges naming something no definition in this store satisfies, and the
    /// names most often behind that.
    pub unresolved: i64,
    pub unresolved_names: Vec<KindCount>,
    /// Names defined more than once, and the worst of them.
    pub ambiguous_names: i64,
    pub ambiguous_worst: Vec<KindCount>,
    /// Languages this store holds, and how many of them carry an edge.
    pub languages_with_edges: i64,
    /// The median milliseconds of the retrievals the ledger recorded, or zero
    /// when it has recorded none: a claim about this machine rather than a
    /// benchmark from somewhere else.
    pub median_query_ms: i64,
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct LanguageLines {
    pub language: String,
    pub lines: i64,
    pub files: i64,
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct KindCount {
    pub name: String,
    pub count: i64,
}

/// One kind of file on the prose panel: how many there are and, for a kind
/// with a unit, how many of that unit they hold.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct FileKind {
    pub name: String,
    /// Files of this kind.
    pub count: i64,
    /// `pages`, `slides` or `cells`; `None` for a kind counted in files only.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<&'static str>,
    /// The unit summed over the files that have a count.
    pub units: i64,
    /// Files of a counted kind with no count yet — stored by an older binary,
    /// counted by the next index pass.
    pub uncounted: i64,
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct FileLines {
    pub path: String,
    pub lines: i64,
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct MonthCount {
    /// `YYYY-MM`, in UTC, because that is what SQLite's `strftime` gives and a
    /// month boundary in the reader's zone is not worth a time-zone database.
    pub month: String,
    pub chunks: i64,
}

/// A line's comment openers, by the language the path says it is.
///
/// Short on purpose. It is here to answer "how much of this corpus is prose
/// inside code", and getting `//` and `#` right answers that for nearly every
/// file anybody indexes. A language missing from it contributes no comment
/// lines rather than a wrong count.
fn comment_openers(language: &str) -> &'static [&'static str] {
    // Lowercased, because `filter::Language::name` is already lowercase —
    // `rust`, not `Rust`. Matching the capitalised spellings found nothing and
    // reported a corpus with no comments in it at all.
    match language.to_ascii_lowercase().as_str() {
        "rust" | "c" | "c++" | "c#" | "go" | "java" | "javascript" | "typescript" | "tsx"
        | "jsx" | "swift" | "kotlin" | "scala" | "php" | "dart" | "zig" | "css" => {
            &["//", "/*", "*"]
        }
        "python" | "ruby" | "shell" | "bash" | "perl" | "r" | "yaml" | "toml" | "makefile"
        | "dockerfile" | "elixir" | "nix" => &["#"],
        "sql" | "lua" | "haskell" => &["--"],
        "html" | "xml" | "markdown" => &["<!--"],
        "lisp" | "clojure" => &[";"],
        _ => &[],
    }
}

/// Measure one store, for the `Inside the index` page.
pub fn corpus(db: &Connection, language_of: impl Fn(&str) -> String) -> Result<Corpus> {
    let (files, chunks, bytes) = stats(db)?;
    let mut out = Corpus {
        files,
        chunks,
        bytes,
        vector_dim: 384,
        ..Default::default()
    };

    // One pass over the chunks, joined to the path so the comment rule knows
    // which language it is reading. Everything counted per file first, so
    // "lines" is the file's own length rather than the sum of its chunks'
    // spans — chunks overlap.
    let mut per_file: std::collections::HashMap<i64, (String, i64)> =
        std::collections::HashMap::new();
    {
        let mut q = db.prepare(
            "SELECT c.file_id, f.path, c.end_line, c.text
               FROM chunks c JOIN files f ON f.id = c.file_id",
        )?;
        let mut rows = q.query([])?;
        while let Some(row) = rows.next()? {
            let file_id: i64 = row.get(0)?;
            let path: String = row.get(1)?;
            let end: i64 = row.get(2)?;
            let text: String = row.get(3)?;
            let language = language_of(&path);
            let openers = comment_openers(&language);
            out.characters += text.chars().count() as i64;
            out.words += text.split_whitespace().count() as i64;
            for line in text.lines() {
                let trimmed = line.trim_start();
                if trimmed.is_empty() {
                    out.blank_lines += 1;
                } else if openers.iter().any(|o| trimmed.starts_with(o)) {
                    out.comment_lines += 1;
                }
            }
            let slot = per_file.entry(file_id).or_insert((path, 0));
            slot.1 = slot.1.max(end);
        }
    }

    let mut by_language: std::collections::HashMap<String, (i64, i64)> =
        std::collections::HashMap::new();
    for (path, lines) in per_file.values() {
        out.lines += lines;
        let language = language_of(path);
        let name = if language.is_empty() {
            "other".to_string()
        } else {
            language
        };
        let slot = by_language.entry(name).or_insert((0, 0));
        slot.0 += lines;
        slot.1 += 1;
        if out.longest_file.as_ref().is_none_or(|f| f.lines < *lines) {
            out.longest_file = Some(FileLines {
                path: path.clone(),
                lines: *lines,
            });
        }
        let depth = path.trim_matches('/').matches('/').count() as i64;
        out.deepest_path = out.deepest_path.max(depth);
    }
    out.languages = by_language
        .into_iter()
        .map(|(language, (lines, files))| LanguageLines {
            language,
            lines,
            files,
        })
        .collect();
    out.languages
        .sort_by_key(|row| std::cmp::Reverse(row.lines));

    // The kinds with a unit are exactly the formats `chunk::COUNTED` names,
    // so every file under them either has a count or is waiting for one.
    {
        let mut q = db.prepare(
            "SELECT CASE
                      WHEN lower(path) LIKE '%.pdf' THEN 'PDF'
                      WHEN lower(path) LIKE '%.pptx' OR lower(path) LIKE '%.odp' THEN 'Slide deck'
                      WHEN lower(path) LIKE '%.xlsx' OR lower(path) LIKE '%.ods'
                        OR lower(path) LIKE '%.csv' OR lower(path) LIKE '%.tsv' THEN 'Spreadsheet'
                      WHEN lower(path) LIKE '%.ipynb' THEN 'Notebook'
                      WHEN lower(path) LIKE '%.docx' OR lower(path) LIKE '%.odt' THEN 'Document'
                      WHEN lower(path) LIKE '%.png' OR lower(path) LIKE '%.jpg'
                        OR lower(path) LIKE '%.jpeg' OR lower(path) LIKE '%.webp' THEN 'Image'
                      ELSE 'Text and code'
                    END AS k,
                    COUNT(*), COALESCE(SUM(units), 0), SUM(units IS NULL)
               FROM files GROUP BY k ORDER BY COUNT(*) DESC",
        )?;
        let mut rows = q.query([])?;
        while let Some(row) = rows.next()? {
            let name: String = row.get(0)?;
            let unit = match name.as_str() {
                "PDF" => Some("pages"),
                "Slide deck" => Some("slides"),
                "Spreadsheet" | "Notebook" => Some("cells"),
                _ => None,
            };
            out.kinds.push(FileKind {
                count: row.get(1)?,
                units: row.get(2)?,
                uncounted: if unit.is_some() { row.get(3)? } else { 0 },
                unit,
                name,
            });
        }
    }

    let span: (i64, i64) = db.query_row(
        "SELECT COALESCE(MIN(indexed_at), 0), COALESCE(MAX(indexed_at), 0) FROM files",
        [],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    out.first_indexed = span.0;
    out.last_indexed = span.1;

    {
        let mut q = db.prepare(
            "SELECT strftime('%Y-%m', f.indexed_at, 'unixepoch') AS m, COUNT(c.id)
               FROM files f JOIN chunks c ON c.file_id = f.id
              GROUP BY m ORDER BY m",
        )?;
        let mut rows = q.query([])?;
        while let Some(row) = rows.next()? {
            out.months.push(MonthCount {
                month: row.get(0)?,
                chunks: row.get(1)?,
            });
        }
    }

    out.symbols = db.query_row("SELECT COUNT(*) FROM symbols", [], |r| r.get(0))?;
    out.edges = db.query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))?;

    /* The four tiers, from `coverage_by_language`, which is the one place that
     * decides them.
     *
     * Grouping `edges.confidence` stood here and is a different question: the
     * column holds `extracted` or `inferred`, and whether an inferred edge is
     * resolved, ambiguous or unresolved depends on how many definitions of its
     * target this store holds. So the page read `resolved 0 · ambiguous 0`
     * directly above a coverage table reading 2380 and 2158 -- two answers to
     * one question, on one page, from one store.
     *
     * `languages_with_edges` comes from the same pass for the same reason. */
    let coverage = coverage_by_language(db)?;
    let mut tiers = [0i64; 4];
    for row in &coverage {
        tiers[0] += row.extracted as i64;
        tiers[1] += row.resolved as i64;
        tiers[2] += row.ambiguous as i64;
        tiers[3] += row.unresolved as i64;
        if row.extracted + row.resolved + row.ambiguous > 0 {
            out.languages_with_edges += 1;
        }
    }
    out.tiers = ["extracted", "resolved", "ambiguous", "unresolved"]
        .iter()
        .zip(tiers)
        .map(|(name, count)| KindCount {
            name: (*name).to_string(),
            count,
        })
        .collect();
    out.unresolved = tiers[3];
    let (names, _) = unresolved_targets(db, 7)?;
    out.unresolved_names = names
        .into_iter()
        .map(|(name, count)| KindCount { name, count })
        .collect();
    out.ambiguous_names = db.query_row(
        "SELECT COUNT(*) FROM (SELECT name FROM symbols GROUP BY name HAVING COUNT(*) > 1)",
        [],
        |r| r.get(0),
    )?;
    out.ambiguous_worst = counted(
        db,
        "SELECT name, COUNT(*) c FROM symbols GROUP BY name HAVING c > 1
          ORDER BY c DESC, name LIMIT 5",
    )?;

    // The middle of what this machine actually measured. `ms` is recorded per
    // retrieval, so this is a fact about this store rather than a benchmark.
    out.median_query_ms = db
        .query_row(
            // `micros`, which is what the column is called. Asking for `ms`
            // did not fail loudly — the row read errored and the fallback
            // reported a store that had never been queried.
            "SELECT micros / 1000 FROM retrievals WHERE COALESCE(tool, '') NOT IN ('note', 'refused')
              ORDER BY micros LIMIT 1 OFFSET (SELECT COUNT(*) FROM retrievals
              WHERE COALESCE(tool, '') NOT IN ('note', 'refused')) / 2",
            [],
            |r| r.get(0),
        )
        .unwrap_or(0);

    Ok(out)
}

/// A two-column `name, count` query, as the list the page draws from it.
fn counted(db: &Connection, sql: &str) -> Result<Vec<KindCount>> {
    let mut q = db.prepare(sql)?;
    let mut rows = q.query([])?;
    let mut out = Vec::new();
    while let Some(row) = rows.next()? {
        out.push(KindCount {
            name: row.get(0)?,
            count: row.get(1)?,
        });
    }
    Ok(out)
}

/// One session's whole ledger, as the per-session table reads it.
#[derive(Debug, Clone, Default)]
pub struct SessionRow {
    /// The session id the client sent at handshake. Empty for rows written
    /// before 0.15.0, which is said rather than guessed at.
    pub session: String,
    pub client: String,
    /// When the session's first and last recorded retrieval happened.
    pub first: i64,
    pub last: i64,
    pub retrievals: i64,
    /// Retrievals that found nothing. Recorded and credited nothing — a
    /// ledger that remembers only its successes is a marketing document.
    pub zero_hit: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
    /// Whole-file less excerpt, over the rows that found something.
    pub net: i64,
    /// Rows counted with the store's own tokenizer rather than by the
    /// four-characters fallback. The tier of this row's figures.
    pub measured: i64,
    /// The model the session's calls were made by, as its client's own log
    /// recorded it — the one most of its rows name. `None` while usage is off
    /// or the client keeps no log: a session's saving is priced at the model
    /// it ran on, or not at all.
    pub model: Option<String>,
}

impl SessionRow {
    /// `measured` when every credited row in the session was counted by a
    /// model's own tokenizer, `modelled` otherwise. Never averaged: two rows
    /// counted two ways are not one number.
    pub fn tier(&self) -> &'static str {
        if self.measured == self.retrievals && self.retrievals > 0 {
            "measured"
        } else {
            "modelled"
        }
    }
}

/// Every session this store recorded, newest last-seen first.
///
/// Grouped in SQL rather than in the page, for the reason the totals are:
/// one search over six stores writes a row in each, and a browser adding
/// them up is a second opinion about a number the store can state.
pub fn ledger_sessions(db: &Connection, limit: usize) -> Result<Vec<SessionRow>> {
    let mut stmt = db.prepare(
        "SELECT COALESCE(session, ''), client,
                MIN(at), MAX(at), COUNT(*),
                SUM(CASE WHEN hits = 0 THEN 1 ELSE 0 END),
                SUM(excerpt_tokens), SUM(whole_file_tokens),
                SUM(CASE WHEN hits > 0 THEN whole_file_tokens - excerpt_tokens ELSE 0 END),
                SUM(CASE WHEN tokenizer IS NOT NULL AND tokenizer <> 'chars4' THEN 1 ELSE 0 END),
                (SELECT r2.model FROM retrievals r2
                  WHERE COALESCE(r2.session, '') = COALESCE(retrievals.session, '')
                    AND r2.client = retrievals.client AND r2.model IS NOT NULL
                  GROUP BY r2.model ORDER BY COUNT(*) DESC LIMIT 1)
         FROM retrievals
         WHERE COALESCE(tool, '') NOT IN ('note', 'refused')
         GROUP BY COALESCE(session, ''), client
         ORDER BY MAX(at) DESC
         LIMIT ?1",
    )?;
    let rows = stmt.query_map([limit as i64], |r| {
        Ok(SessionRow {
            session: r.get(0)?,
            client: r.get(1)?,
            first: r.get(2)?,
            last: r.get(3)?,
            retrievals: r.get(4)?,
            zero_hit: r.get(5)?,
            excerpt_tokens: r.get(6)?,
            whole_file_tokens: r.get(7)?,
            net: r.get(8)?,
            measured: r.get(9)?,
            model: r.get(10)?,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// Warm query latency as the ledger recorded it: p50 and p95, in microseconds.
///
/// From the rows themselves rather than from a benchmark, so the figure is
/// what this machine actually served rather than what it can serve.
pub fn ledger_latency(db: &Connection) -> Result<(i64, i64)> {
    // One figure per retrieval and none for a row that measured no work: a
    // median over raw-read rows' zeros and one row per store per search is
    // how a report came to say 724 ms where the rows said ~67.
    let mut stmt = db.prepare(&format!(
        "SELECT MAX(micros) AS m FROM retrievals WHERE micros > 0 AND {AGENT_RETRIEVAL}
          GROUP BY COALESCE(query_id, 'row:' || id) ORDER BY m"
    ))?;
    let rows = stmt.query_map([], |r| r.get::<_, i64>(0))?;
    let all: Vec<i64> = rows.collect::<rusqlite::Result<_>>()?;
    if all.is_empty() {
        return Ok((0, 0));
    }
    let at = |q: f64| all[((all.len() as f64 - 1.0) * q).round() as usize];
    Ok((at(0.50), at(0.95)))
}

/// The hash of the newest ledger row: what `--verify` checks the chain to.
pub fn ledger_head(db: &Connection) -> Result<Option<String>> {
    let hash: Option<String> = db
        .query_row(
            "SELECT hash FROM retrievals ORDER BY id DESC LIMIT 1",
            [],
            |r| r.get(0),
        )
        .optional()?;
    Ok(hash)
}

/// Queries that found nothing, commonest first.
///
/// The gap list: a question an agent asked that this corpus could not answer
/// is either a missing document or a name nobody uses in the words they
/// searched with.
pub fn ledger_zero_hit_queries(db: &Connection, limit: usize) -> Result<Vec<(String, i64)>> {
    ledger_zero_hit_queries_since(db, 0, limit)
}

/// The questions that found nothing, at or after `since`.
pub fn ledger_zero_hit_queries_since(
    db: &Connection,
    since: i64,
    limit: usize,
) -> Result<Vec<(String, i64)>> {
    let mut stmt = db.prepare(&format!(
        "SELECT query, COUNT(*) AS n FROM (
            SELECT MIN(query) AS query FROM retrievals WHERE at >= ?1 AND {AGENT_RETRIEVAL}
             GROUP BY COALESCE(query_id, 'row:' || id) HAVING MAX(hits) = 0)
         GROUP BY query ORDER BY n DESC, query LIMIT ?2"
    ))?;
    let rows = stmt.query_map(rusqlite::params![since, limit as i64], |r| {
        Ok((r.get(0)?, r.get(1)?))
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// One recorded retrieval, as the access report attaches them.
#[derive(Debug, Clone)]
pub struct RetrievalRow {
    pub at: i64,
    pub client: String,
    pub tool: String,
    pub query: String,
    pub hits: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
}

/// Every retrieval since `since`, newest first.
///
/// `ledger_sessions` above aggregates these into one row per session, which is
/// what the access report shows by default. This is the same rows unrolled, for
/// the report's `Attach retrieved excerpts` toggle: a session line says an agent
/// asked forty times, and an auditor's question is which forty.
///
/// `tool` is NULL on every row written before 0.15.0 and is reported as `—`
/// rather than guessed — those rows are real retrievals and dropping them would
/// make the attachment disagree with the session counts above it.
pub fn ledger_retrievals(db: &Connection, since: i64, limit: usize) -> Result<Vec<RetrievalRow>> {
    let mut stmt = db.prepare(
        "SELECT at, client, COALESCE(tool, ''), query, hits, excerpt_tokens, whole_file_tokens
         FROM retrievals WHERE at >= ?1 AND COALESCE(tool, '') NOT IN ('note', 'refused')
         ORDER BY at DESC, id DESC LIMIT ?2",
    )?;
    let rows = stmt.query_map(rusqlite::params![since, limit as i64], |r| {
        Ok(RetrievalRow {
            at: r.get(0)?,
            client: r.get(1)?,
            tool: r.get(2)?,
            query: r.get(3)?,
            hits: r.get(4)?,
            excerpt_tokens: r.get(5)?,
            whole_file_tokens: r.get(6)?,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// Files this store read since `since`, newest first, with when it read them.
pub fn files_indexed_since(
    db: &Connection,
    since: i64,
    limit: usize,
) -> Result<Vec<(String, i64)>> {
    let mut stmt = db.prepare(
        "SELECT path, indexed_at FROM files WHERE indexed_at >= ?1
         ORDER BY indexed_at DESC LIMIT ?2",
    )?;
    let rows = stmt.query_map([since, limit as i64], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// One settled dependency edge, by name, for the community pass.
///
/// Names rather than ids, because `edges.dst` is a name and the whole point
/// of the pass is to group names. Only edges whose target the store actually
/// defines are returned: an edge into a dependency that was never indexed
/// cannot join two communities of this corpus.
pub struct NamedEdge {
    pub from: String,
    pub to: String,
}

/// Every `calls` and `imports` edge whose target this store defines, up to
/// `limit`, with the total so a reader is told when the list was cut.
///
/// This is the one whole-graph read in the crate and it is bounded for that
/// reason. Everything else walks one hop at a time to keep peak memory flat
/// as a corpus grows; communities are a property of the whole graph and
/// cannot be computed a hop at a time, so the bound is the substitute — past
/// it the panel says `Shown N of M` rather than quietly clustering a slice.
pub fn community_edges(db: &Connection, limit: usize) -> Result<(Vec<NamedEdge>, i64)> {
    let target = crate::graph::not_navigational("s.kind");
    // `extracted` and `inferred` are the stored values; `resolved` and
    // `ambiguous` are computed per query and never written, so "settled" here
    // means an extracted edge or a bare-name match onto exactly one
    // definition. A name with several definitions is not evidence that two
    // subsystems are joined.
    let sql = format!(
        "SELECT src.name, s.name
         FROM symbols src
         JOIN edges e ON e.src = src.id
         JOIN symbols s ON s.name = e.dst AND {target}
         WHERE e.kind IN ('calls', 'imports')
           AND src.name <> s.name
           AND (SELECT COUNT(*) FROM symbols d WHERE d.name = e.dst AND {}) = 1
         LIMIT ?1",
        crate::graph::not_navigational("d.kind")
    );
    let mut stmt = db.prepare(&sql)?;
    let rows = stmt.query_map([limit as i64], |r| {
        Ok(NamedEdge {
            from: r.get(0)?,
            to: r.get(1)?,
        })
    })?;
    let edges: Vec<NamedEdge> = rows.collect::<rusqlite::Result<_>>()?;
    let total: i64 = db.query_row(
        "SELECT COUNT(*) FROM edges WHERE kind IN ('calls', 'imports')",
        [],
        |r| r.get(0),
    )?;
    Ok((edges, total))
}

/// Where each of these names is defined, for the hub lines under a community.
pub fn where_defined(db: &Connection, names: &[String]) -> Result<Vec<(String, String, u32)>> {
    if names.is_empty() {
        return Ok(Vec::new());
    }
    let holes = vec!["?"; names.len()].join(", ");
    let sql = format!(
        "SELECT s.name, f.path, s.start_line
         FROM symbols s JOIN files f ON f.id = s.file_id
         WHERE s.name IN ({holes})
         ORDER BY f.path, s.start_line"
    );
    let mut stmt = db.prepare(&sql)?;
    let binds: Vec<Value> = names.iter().map(|n| Value::Text(n.clone())).collect();
    let rows = stmt.query_map(rusqlite::params_from_iter(binds), |r| {
        Ok((r.get(0)?, r.get(1)?, r.get(2)?))
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// Call targets no definition in this store satisfies, commonest first, and
/// how many distinct ones there are.
///
/// The names a reader has to recognise as "outside this corpus" before they
/// read an absent edge as a missing call. Counted rather than listed in full.
/// The language's own builtins and standard library are left out
/// ([`crate::graph::is_builtin`]) — cobra's list was `Errorf` 198 times,
/// `len`, `append` and `os` (2026-10-14 audit) — and [`builtin_targets`]
/// counts what was left out, so a report can say so.
pub fn unresolved_targets(db: &Connection, limit: usize) -> Result<(Vec<(String, i64)>, i64)> {
    let (mut all, _) = outside_targets(db)?;
    let distinct = all.len() as i64;
    all.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    all.truncate(limit);
    Ok((all, distinct))
}

/// How many distinct call and import targets with no definition here are the
/// language's own builtins or standard library, and so are not in
/// [`unresolved_targets`].
pub fn builtin_targets(db: &Connection) -> Result<i64> {
    Ok(outside_targets(db)?.1)
}

/// Targets nothing here defines, as `(name, edges)` outside the builtins, and
/// the count of distinct names that were builtins only.
fn outside_targets(db: &Connection) -> Result<(Vec<(String, i64)>, i64)> {
    // One existence test per distinct target rather than per edge, then the
    // per-file rows of only those targets, because whether a name is a
    // builtin depends on the calling file's language and the edge's hint.
    // Cached per store until its graph changes, as the report is asked for
    // again and again while it is being read.
    cached_by_graph(db, "unresolved", || {
        let target = crate::graph::not_navigational("d.kind");
        let mut stmt = db.prepare(&format!(
            "WITH t AS (SELECT dst FROM edges WHERE kind IN ('calls', 'imports') GROUP BY dst),
                  u AS (SELECT dst FROM t
                        WHERE NOT EXISTS (SELECT 1 FROM symbols d WHERE d.name = t.dst AND {target}))
             SELECT e.dst, e.kind, e.hint, f.path, COUNT(*)
             FROM u JOIN edges e ON e.dst = u.dst
             JOIN symbols s ON s.id = e.src JOIN files f ON f.id = s.file_id
             WHERE e.kind IN ('calls', 'imports')
             GROUP BY e.dst, e.kind, e.hint, s.file_id"
        ))?;
        let rows = stmt.query_map([], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, Option<String>>(2)?,
                r.get::<_, String>(3)?,
                r.get::<_, i64>(4)?,
            ))
        })?;
        let mut language: std::collections::HashMap<String, &'static str> =
            std::collections::HashMap::new();
        let mut kept: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
        let mut builtin: std::collections::HashSet<String> = std::collections::HashSet::new();
        for row in rows {
            let (name, kind, hint, path, n) = row?;
            let lang = *language.entry(path).or_insert_with_key(|p| {
                crate::graph::language_of(std::path::Path::new(p)).unwrap_or("")
            });
            if kind == "imports" && crate::graph::is_relative_import(lang, &name) {
                continue;
            }
            if crate::graph::is_builtin(lang, &name, &kind, hint.as_deref()) {
                builtin.insert(name);
            } else {
                *kept.entry(name).or_insert(0) += n;
            }
        }
        builtin.retain(|name| !kept.contains_key(name));
        Ok((kept.into_iter().collect::<Vec<_>>(), builtin.len() as i64))
    })
}

/// A figure computed over a whole store's graph, kept until the graph's
/// symbol or edge count moves. The health report's aggregates read millions
/// of rows on a large store and give the same answer until something is
/// indexed or forgotten.
fn cached_by_graph<T: Clone + Send + 'static>(
    db: &Connection,
    what: &str,
    compute: impl FnOnce() -> Result<T>,
) -> Result<T> {
    use std::any::Any;
    type Slot = (String, (i64, i64), Box<dyn Any + Send>);
    static CACHE: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new(Vec::new());
    let key = format!("{what}|{}", db.path().unwrap_or(""));
    let stats = graph_stats(db)?;
    if let Some((_, _, value)) = CACHE
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .find(|(k, st, _)| *k == key && *st == stats)
        && let Some(value) = value.downcast_ref::<T>()
    {
        return Ok(value.clone());
    }
    let value = compute()?;
    let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
    cache.retain(|(k, _, _)| *k != key);
    cache.push((key, stats, Box::new(value.clone())));
    Ok(value)
}

/// How many names this store defines more than once.
///
/// The population of every ambiguous edge: a walk refuses to cross one of
/// these, so the count is what a reader needs to know before reading "not
/// connected" as "nothing calls it".
pub fn names_with_several_definitions(db: &Connection) -> Result<i64> {
    let target = crate::graph::not_navigational("s.kind");
    db.query_row(
        &format!(
            "SELECT COUNT(*) FROM (SELECT s.name FROM symbols s WHERE {target}
             GROUP BY s.name HAVING COUNT(*) > 1)"
        ),
        [],
        |r| r.get(0),
    )
    .map_err(Into::into)
}

/// Chunks by the month their file was indexed, oldest first.
///
/// Indexed rather than written: the store records when it read a file, not
/// when somebody wrote it, and labelling this "chunks per month" without
/// saying which would be a claim about a repository's history that the store
/// cannot make.
pub fn chunks_by_month(db: &Connection) -> Result<Vec<(String, i64)>> {
    let mut stmt = db.prepare(
        "SELECT strftime('%Y-%m', f.indexed_at, 'unixepoch') AS month, COUNT(c.id)
         FROM chunks c JOIN files f ON f.id = c.file_id
         GROUP BY month ORDER BY month",
    )?;
    let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// One ledger row as the reports count it (0.42.0).
#[derive(Debug, Clone)]
pub struct ReportRow {
    pub id: i64,
    pub at: i64,
    pub client: String,
    pub client_version: String,
    pub session: String,
    pub tool: String,
    pub query: String,
    /// The retrieval this row is part of: one search over six stores is six
    /// rows and one key. A row written before 0.20.2 has no id and is its own.
    pub key: String,
    pub hits: i64,
    pub micros: i64,
    pub excerpt_tokens: i64,
    pub whole_file_tokens: i64,
    pub tokenizer: String,
}

/// Every ledger row recorded at or after `since`, oldest first.
///
/// The reports take their figures from the rows rather than from the
/// aggregates above, so a window narrows every figure a report prints — the
/// 0.41 savings report narrowed net, credited and total and left whole,
/// excerpt, refunds and latency lifetime (R5). Nothing is filtered here: what
/// counts as a query is the report's rule, and a reader that filtered would be
/// a second copy of it.
pub fn report_rows_since(db: &Connection, store: &str, since: i64) -> Result<Vec<ReportRow>> {
    let mut stmt = db.prepare(
        "SELECT id, at, client, COALESCE(client_version, ''), COALESCE(session, ''),
                COALESCE(tool, ''), query, query_id, hits, micros, excerpt_tokens,
                whole_file_tokens, COALESCE(tokenizer, '')
         FROM retrievals WHERE at >= ?1 ORDER BY id",
    )?;
    let rows = stmt.query_map([since], |r| {
        let id: i64 = r.get(0)?;
        let key: Option<String> = r.get(7)?;
        Ok(ReportRow {
            id,
            at: r.get(1)?,
            client: r.get(2)?,
            client_version: r.get(3)?,
            session: r.get(4)?,
            tool: r.get(5)?,
            query: r.get(6)?,
            key: key
                .filter(|k| !k.is_empty())
                .unwrap_or_else(|| format!("{store}:row:{id}")),
            hits: r.get(8)?,
            micros: r.get(9)?,
            excerpt_tokens: r.get(10)?,
            whole_file_tokens: r.get(11)?,
            tokenizer: r.get(12)?,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<_>>()?)
}

/// A file the store read at or after `since`, and what it held before.
#[derive(Debug, Clone)]
pub struct ReadFile {
    pub path: String,
    pub indexed_at: i64,
    /// The definitions the first re-index inside the window retired — what
    /// the file held when the window opened: `(name, kind, start, end)`.
    /// Empty for a file read for the first time, and for a re-read file that
    /// held no definitions, which the store cannot tell apart from a first read.
    pub before: Vec<(String, String, u32, u32)>,
    /// Its definitions now: `(name, kind, start, end)`.
    pub now: Vec<(String, String, u32, u32)>,
}

/// The first and last indexed path in sort order. Their common directory is
/// the common directory of every path, which is the root a report prints
/// paths against when the registry names none (a store opened by `--store`).
pub fn path_bounds(db: &Connection) -> Result<Option<(String, String)>> {
    Ok(
        db.query_row("SELECT MIN(path), MAX(path) FROM files", [], |r| {
            Ok(
                match (
                    r.get::<_, Option<String>>(0)?,
                    r.get::<_, Option<String>>(1)?,
                ) {
                    (Some(a), Some(b)) => Some((a, b)),
                    _ => None,
                },
            )
        })?,
    )
}

/// Every file read at or after `since`, newest first, with no cap — the
/// change brief's "Files re-read" was 200 per store summed (R3).
pub fn files_read_since(db: &Connection, since: i64) -> Result<Vec<ReadFile>> {
    let mut stmt = db.prepare(
        "SELECT id, path, indexed_at FROM files WHERE indexed_at >= ?1
         ORDER BY indexed_at DESC, path",
    )?;
    let files: Vec<(i64, String, i64)> = stmt
        .query_map([since], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
        .collect::<rusqlite::Result<_>>()?;
    let mut past = db.prepare_cached(
        "SELECT name, kind, start_line, end_line FROM symbols_past
         WHERE path = ?1 AND retired_at = (SELECT MIN(retired_at) FROM symbols_past
                                           WHERE path = ?1 AND retired_at >= ?2)
           AND kind != 'module'",
    )?;
    let mut live = db.prepare_cached(
        "SELECT name, kind, start_line, end_line FROM symbols
         WHERE file_id = ?1 AND kind != 'module' ORDER BY start_line",
    )?;
    let mut out = Vec::with_capacity(files.len());
    for (id, path, indexed_at) in files {
        let span = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?));
        let before = past
            .query_map(params![path, since], span)?
            .collect::<rusqlite::Result<_>>()?;
        let now = live
            .query_map([id], span)?
            .collect::<rusqlite::Result<_>>()?;
        out.push(ReadFile {
            path,
            indexed_at,
            before,
            now,
        });
    }
    Ok(out)
}

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

    /// The change brief's history lookup searches the path index rather than
    /// scanning symbols_past, which never finished on the owner's store.
    #[test]
    fn the_change_briefs_history_lookup_uses_the_path_index() {
        let dir = tempfile::tempdir().unwrap();
        let db = open(&dir.path().join("s.db")).unwrap();
        let plan: Vec<String> = db
            .prepare(
                "EXPLAIN QUERY PLAN
                 SELECT name, kind, start_line, end_line FROM symbols_past
                  WHERE path = ?1 AND retired_at = (SELECT MIN(retired_at) FROM symbols_past
                                                    WHERE path = ?1 AND retired_at >= ?2)
                    AND kind != 'module'",
            )
            .unwrap()
            .query_map(params!["/a.rs", 0], |r| r.get::<_, String>(3))
            .unwrap()
            .collect::<rusqlite::Result<_>>()
            .unwrap();
        assert!(
            plan.iter()
                .all(|step| !step.starts_with("SCAN symbols_past")),
            "{plan:?}"
        );
        assert!(
            plan.iter().any(|step| step.contains("symbols_past_path")),
            "{plan:?}"
        );
    }

    /// Several connections opening one new store at the same moment, as the
    /// daemon's index route, its watcher and a CLI do (#132). Before the open
    /// was made safe to race, most rounds lost one of them to "duplicate
    /// column name" or "database is locked".
    #[test]
    fn a_new_store_opened_by_several_connections_at_once_opens_for_all() {
        let root = tempfile::tempdir().unwrap();
        for round in 0..40 {
            let db = root.path().join(format!("{round}.db"));
            let start = std::sync::Arc::new(std::sync::Barrier::new(6));
            let openers: Vec<_> = (0..6)
                .map(|_| {
                    let db = db.clone();
                    let start = std::sync::Arc::clone(&start);
                    std::thread::spawn(move || {
                        start.wait();
                        open(&db).map(drop).map_err(|e| format!("{e:#}"))
                    })
                })
                .collect();
            for opener in openers {
                if let Err(e) = opener.join().unwrap() {
                    panic!("round {round}: {e}");
                }
            }
        }
    }

    fn sym(name: &str) -> crate::graph::Symbol {
        crate::graph::Symbol {
            kind: "function".to_string(),
            name: name.to_string(),
            qualified: name.to_string(),
            start_line: 1,
            end_line: 2,
        }
    }

    fn at(mut s: crate::graph::Symbol, start: u32, end: u32) -> crate::graph::Symbol {
        s.start_line = start;
        s.end_line = end;
        s
    }

    /// Build a store with one file, one chunk and one symbol, and return the
    /// connection plus the symbol's id.
    fn one_symbol(db: &Connection, path: &str, name: &str) -> i64 {
        db.execute_batch(SCHEMA).unwrap();
        db.pragma_update(None, "foreign_keys", "ON").unwrap();
        let file_id = insert_file(db, path, "h", 1, 0).unwrap();
        let chunk_id = insert_chunk(db, file_id, 0, 1, 2, name).unwrap();
        insert_symbol(db, file_id, Some(chunk_id), &sym(name)).unwrap()
    }

    /// More names than SQLite takes variables in one statement. 0.32.0 bound
    /// them all into one `IN (...)`, and on the 70-repository benchmark corpus
    /// every search failed with "too many SQL variables".
    /// Stopwords leave the keyword list's query unless they are all there is.
    #[test]
    fn stopwords_leave_the_keyword_query_unless_nothing_else_is_there() {
        let db = Connection::open_in_memory().unwrap();
        prepare_for_tests(&db);
        let file = insert_file(&db, "a.md", "h", 1, 0).unwrap();
        for (ord, text) in ["the parser recovers", "of the and the of"]
            .iter()
            .enumerate()
        {
            insert_chunk(&db, file, ord, ord as u32 + 1, ord as u32 + 1, text).unwrap();
        }
        let ids = keyword_search(&db, "how does the parser recover", 10, &[]).unwrap();
        assert_eq!(ids.len(), 1, "a chunk of stopwords matched: {ids:?}");
        let only = keyword_search(&db, "the of", 10, &[]).unwrap();
        assert_eq!(
            only.len(),
            2,
            "a query of stopwords found nothing: {only:?}"
        );
    }

    /// A read that runs past its limit is interrupted and says so; one that
    /// finishes inside it is untouched.
    #[test]
    fn a_bounded_read_is_interrupted_at_its_limit() {
        let db = Connection::open_in_memory().unwrap();
        let started = std::time::Instant::now();
        let slow = bounded(&[&db], std::time::Duration::from_millis(100), || {
            let n: i64 = db.query_row(
                "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c) \
                 SELECT COUNT(*) FROM (SELECT x FROM c LIMIT 10000000000)",
                [],
                |r| r.get(0),
            )?;
            Ok(n)
        });
        let err = slow.expect_err("a ten-billion-row count finished");
        assert!(is_interrupted(&err), "{err:#}");
        assert!(started.elapsed() < std::time::Duration::from_secs(5));

        let quick = bounded(&[&db], std::time::Duration::from_secs(5), || {
            Ok(db.query_row("SELECT 1", [], |r| r.get::<_, i64>(0))?)
        });
        assert_eq!(quick.unwrap(), 1);
    }

    #[test]
    fn symbols_by_names_takes_more_names_than_sqlite_takes_variables() {
        let db = Connection::open_in_memory().unwrap();
        one_symbol(&db, "b.rs", "wanted");
        let a = insert_file(&db, "a.rs", "h", 1, 0).unwrap();
        insert_symbol(&db, a, None, &at(sym("also_wanted"), 5, 6)).unwrap();
        insert_symbol(&db, a, None, &at(sym("wanted"), 1, 2)).unwrap();

        let mut names: Vec<String> = (0..40_000).map(|i| format!("absent_{i}")).collect();
        names.push("wanted".to_string());
        names.insert(0, "also_wanted".to_string());
        let found = symbols_by_names(&db, &names, &[]).unwrap();

        // One order across batches, as the single statement gave: path, then line.
        let got: Vec<(&str, u32)> = found
            .iter()
            .map(|s| (s.path.as_str(), s.start_line))
            .collect();
        assert_eq!(got, [("a.rs", 1), ("a.rs", 5), ("b.rs", 1)]);
    }

    /// The walk's variant drops an edge whose target is a hub, and only that
    /// edge; `edges_out` itself still settles every edge.
    #[test]
    fn edges_out_short_of_hubs_drops_only_edges_into_hubs() {
        let db = Connection::open_in_memory().unwrap();
        let caller = one_symbol(&db, "a.rs", "caller");
        insert_edge(&db, caller, "rare", "calls", "inferred", None, None).unwrap();
        insert_edge(&db, caller, "common", "calls", "inferred", None, None).unwrap();
        let b = insert_file(&db, "b.rs", "h", 1, 0).unwrap();
        insert_symbol(&db, b, None, &sym("rare")).unwrap();
        for line in 1..=3 {
            insert_symbol(&db, b, None, &at(sym("common"), line * 10, line * 10 + 1)).unwrap();
        }

        let targets = |ends: Vec<EdgeEnd>| {
            let mut names: Vec<String> = ends.into_iter().map(|e| e.symbol.name).collect();
            names.sort();
            names.dedup();
            names
        };
        assert_eq!(
            targets(edges_out_short_of_hubs(&db, "caller", &[], 2).unwrap()),
            ["rare"]
        );
        assert_eq!(
            targets(edges_out_short_of_hubs(&db, "caller", &[], 3).unwrap()),
            ["common", "rare"]
        );
        assert_eq!(
            targets(edges_out(&db, "caller", &[]).unwrap()),
            ["common", "rare"]
        );
    }

    /// Forgetting a file takes its symbols and its outgoing edges with it.
    ///
    /// The cascade does this, not the caller — which is why it is worth a test:
    /// a missing `ON DELETE CASCADE` would leave rows pointing at a file id
    /// SQLite is free to reissue.
    #[test]
    fn deleting_a_file_deletes_its_symbols_and_its_outgoing_edges() {
        let db = Connection::open_in_memory().unwrap();
        let caller = one_symbol(&db, "a.rs", "caller");
        insert_edge(&db, caller, "callee", "calls", "inferred", None, None).unwrap();
        assert_eq!(graph_stats(&db).unwrap(), (1, 1));

        delete_file(&db, "a.rs", 0).unwrap();
        assert_eq!(
            graph_stats(&db).unwrap(),
            (0, 0),
            "the file's symbols and the edges leaving them both cascade"
        );
    }

    /// Re-indexing the file an edge points *into* must not delete the edge.
    ///
    /// This is the whole reason `edges.dst` is a name and not an id. With an id
    /// there, re-extracting `b.rs` would reissue its symbol ids and orphan
    /// every edge from `a.rs` into it — the graph would rot on exactly the
    /// operation this release exists to make safe.
    #[test]
    fn re_indexing_the_target_file_leaves_edges_into_it_intact() {
        let db = Connection::open_in_memory().unwrap();
        let caller = one_symbol(&db, "a.rs", "caller");
        insert_edge(&db, caller, "callee", "calls", "inferred", None, None).unwrap();
        let b = insert_file(&db, "b.rs", "h", 1, 0).unwrap();
        insert_symbol(&db, b, None, &sym("callee")).unwrap();
        assert_eq!(edges_out(&db, "caller", &[]).unwrap().len(), 1);

        // b.rs changes: its symbols are dropped and re-extracted with new ids.
        delete_file(&db, "b.rs", 0).unwrap();
        let b = insert_file(&db, "b.rs", "h2", 1, 0).unwrap();
        insert_symbol(&db, b, None, &at(sym("callee"), 9, 10)).unwrap();

        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(
            out.len(),
            1,
            "the edge survived its target being re-indexed"
        );
        assert_eq!(
            out[0].symbol.start_line, 9,
            "and now points at the new rows"
        );
    }

    /// A store with one caller and several definitions of the name it calls.
    ///
    /// Returns the connection; `paths` are the files each definition of
    /// `callee` lives in, and the caller is always `src/caller.rs`.
    fn many_definitions(paths: &[&str]) -> Connection {
        let db = Connection::open_in_memory().unwrap();
        one_symbol(&db, "src/caller.rs", "caller");
        for (i, path) in paths.iter().enumerate() {
            // The caller's own file is already there, and a definition in it
            // is exactly the case the same-file rank is about.
            let file = db
                .query_row("SELECT id FROM files WHERE path = ?1", params![path], |r| {
                    r.get(0)
                })
                .optional()
                .unwrap()
                .unwrap_or_else(|| insert_file(&db, path, &format!("h{i}"), 1, 0).unwrap());
            insert_symbol(&db, file, None, &sym("callee")).unwrap();
        }
        db
    }

    fn call(db: &Connection, hint: Option<&str>) {
        let src: i64 = db
            .query_row("SELECT id FROM symbols WHERE name = 'caller'", [], |r| {
                r.get(0)
            })
            .unwrap();
        insert_edge(db, src, "callee", "calls", "inferred", hint, None).unwrap();
    }

    /// One definition of the name is one answer, whatever the hint says.
    #[test]
    fn a_name_with_one_definition_resolves() {
        let db = many_definitions(&["src/other.rs"]);
        call(&db, None);
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].confidence, crate::graph::RESOLVED);
        assert_eq!(out[0].definitions, 1);
    }

    /// Four definitions and nothing to choose between them. Every candidate
    /// comes back marked `ambiguous` and carrying the count, so a renderer can
    /// say "4 definitions" instead of printing four calls the source never
    /// made.
    #[test]
    fn a_name_nothing_narrows_is_ambiguous_and_keeps_every_candidate() {
        let db = many_definitions(&["src/a.rs", "src/b.rs", "src/c.rs", "src/d.rs"]);
        call(&db, None);
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 4);
        assert!(out.iter().all(|e| e.confidence == crate::graph::AMBIGUOUS));
        assert!(out.iter().all(|e| e.definitions == 4));
    }

    /// The hint picks the definition whose file it names, and the other three
    /// are not returned at all.
    #[test]
    fn a_hint_that_names_a_file_resolves_to_that_definition() {
        let db = many_definitions(&["src/a.rs", "src/store.rs", "src/c.rs"]);
        call(&db, Some("store"));
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(out[0].symbol.path, "src/store.rs");
        assert_eq!(out[0].confidence, crate::graph::RESOLVED);
        assert_eq!(
            out[0].definitions, 3,
            "the count is what the ranking chose between, not what survived"
        );
    }

    /// A hint naming a directory works the same way: a module is a file or a
    /// directory depending on how the author felt that day.
    #[test]
    fn a_hint_names_a_directory_as_readily_as_a_file() {
        let db = many_definitions(&["src/a.rs", "src/store/mod.rs"]);
        call(&db, Some("store"));
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].symbol.path, "src/store/mod.rs");
    }

    /// A module path outranks the calling file's own namesake: `store::callee()`
    /// in caller.rs is store.rs's `callee`, whatever caller.rs defines. Until
    /// 0.42.0 the calling file won, which in flask's test_config.py settled
    /// `flask.Flask(...)` on a test's own subclass (2026-10-14 audit). A
    /// call with no path, or a path naming the calling file, still means its
    /// own.
    #[test]
    fn a_module_path_outranks_the_calling_file() {
        let db = many_definitions(&["src/caller.rs", "src/store.rs"]);
        call(&db, Some("store"));
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].symbol.path, "src/store.rs");

        let db = many_definitions(&["src/caller.rs", "src/store.rs"]);
        call(&db, None);
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].symbol.path, "src/caller.rs");

        let db = many_definitions(&["src/caller.rs", "src/store.rs"]);
        call(&db, Some("caller"));
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].symbol.path, "src/caller.rs");
    }

    /// With no hint, what the calling file imports breaks the tie.
    #[test]
    fn an_import_resolves_what_the_hint_cannot() {
        let db = many_definitions(&["src/a.rs", "src/b.rs"]);
        let src: i64 = db
            .query_row("SELECT id FROM symbols WHERE name = 'caller'", [], |r| {
                r.get(0)
            })
            .unwrap();
        insert_edge(
            &db,
            src,
            "crate::b::callee",
            "imports",
            "extracted",
            None,
            None,
        )
        .unwrap();
        call(&db, None);
        let out = edges_out(&db, "caller", &["calls".to_string()]).unwrap();
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(out[0].symbol.path, "src/b.rs");
        assert_eq!(out[0].confidence, crate::graph::RESOLVED);
    }

    /// The hint outranks the import list: an import is a set of possibilities,
    /// a hint is a statement about this call.
    #[test]
    fn the_hint_outranks_an_import() {
        let db = many_definitions(&["src/a.rs", "src/b.rs"]);
        let src: i64 = db
            .query_row("SELECT id FROM symbols WHERE name = 'caller'", [], |r| {
                r.get(0)
            })
            .unwrap();
        insert_edge(
            &db,
            src,
            "crate::b::callee",
            "imports",
            "extracted",
            None,
            None,
        )
        .unwrap();
        call(&db, Some("a"));
        let out = edges_out(&db, "caller", &["calls".to_string()]).unwrap();
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(out[0].symbol.path, "src/a.rs");
    }

    /// An edge the syntax tree settled is never downgraded by a ranking.
    #[test]
    fn an_extracted_edge_stays_extracted() {
        let db = many_definitions(&["src/store.rs"]);
        let src: i64 = db
            .query_row("SELECT id FROM symbols WHERE name = 'caller'", [], |r| {
                r.get(0)
            })
            .unwrap();
        insert_edge(
            &db,
            src,
            "callee",
            "calls",
            "extracted",
            Some("store"),
            None,
        )
        .unwrap();
        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out[0].confidence, crate::graph::EXTRACTED);
    }

    /// A store written by 0.14.0 has a NULL hint on every row. It must answer
    /// exactly as it did then: one definition is the answer, several are a
    /// question.
    #[test]
    fn a_null_hint_behaves_as_it_did_before_hints_existed() {
        let db = many_definitions(&["src/a.rs"]);
        call(&db, None);
        let one = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(one.len(), 1);
        assert_eq!(one[0].symbol.path, "src/a.rs");

        let db = many_definitions(&["src/a.rs", "src/b.rs"]);
        call(&db, None);
        let two = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(
            two.len(),
            2,
            "both candidates are still reachable, now labelled rather than asserted"
        );
    }

    /// Callers are unchanged: the row came from the edge's own `src` id, so
    /// there is nothing to resolve and the stored confidence stands.
    #[test]
    fn callers_keep_the_stored_confidence() {
        let db = many_definitions(&["src/a.rs", "src/b.rs"]);
        call(&db, None);
        let inbound = edges_in(&db, "callee", &[]).unwrap();
        assert_eq!(inbound.len(), 1);
        assert_eq!(inbound[0].confidence, crate::graph::INFERRED);
        assert_eq!(inbound[0].definitions, 1);
    }

    /// Both directions resolve, and the edge kind filter applies to each.
    #[test]
    fn edges_resolve_in_both_directions_and_filter_by_kind() {
        let db = Connection::open_in_memory().unwrap();
        let caller = one_symbol(&db, "a.rs", "caller");
        let b = insert_file(&db, "b.rs", "h", 1, 0).unwrap();
        insert_symbol(&db, b, None, &sym("callee")).unwrap();
        insert_edge(&db, caller, "callee", "calls", "extracted", None, None).unwrap();
        insert_edge(&db, caller, "callee", "references", "inferred", None, None).unwrap();

        assert_eq!(edges_out(&db, "caller", &[]).unwrap().len(), 2);
        let calls = edges_out(&db, "caller", &["calls".to_string()]).unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].confidence, "extracted");

        let inbound = edges_in(&db, "callee", &["calls".to_string()]).unwrap();
        assert_eq!(inbound.len(), 1);
        assert_eq!(
            inbound[0].symbol.name, "caller",
            "edges_in reports the source"
        );
    }

    /// An edge to something the corpus does not contain is still recorded, and
    /// simply resolves to nothing. A call into the standard library is the
    /// common case, and dropping it would lose the fact that the call is there.
    #[test]
    fn an_edge_to_an_unindexed_target_resolves_to_nothing_without_erroring() {
        let db = Connection::open_in_memory().unwrap();
        let caller = one_symbol(&db, "a.rs", "caller");
        insert_edge(&db, caller, "println", "calls", "inferred", None, None).unwrap();
        assert!(edges_out(&db, "caller", &[]).unwrap().is_empty());
        assert_eq!(graph_stats(&db).unwrap().1, 1, "but the edge row is there");
    }

    /// Every store written before 0.6.0 lacks the key entirely. Reading that as
    /// anything but format 1 would refuse the whole installed base.
    #[test]
    fn a_store_without_the_key_is_the_format_we_understand() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        assert!(get_meta(&db, FORMAT_KEY).unwrap().is_none());
        check_format(&db).expect("a pre-0.6.0 store is readable");
        // And still has no key: opening a store must not rewrite it.
        assert!(get_meta(&db, FORMAT_KEY).unwrap().is_none());
    }

    /// The point of writing the format down: a later semlith's store is refused
    /// with both numbers, instead of read as though its layout were this one.
    #[test]
    fn a_newer_format_is_refused_naming_both_numbers() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        let newer = FORMAT_VERSION + 1;
        set_meta(&db, FORMAT_KEY, &newer.to_string()).unwrap();

        let refused = check_format(&db).expect_err("a newer format must not be read");
        let said = refused.to_string();
        assert!(said.contains(&newer.to_string()), "{said}");
        assert!(
            said.contains(&FORMAT_VERSION.to_string()),
            "the error must name what this binary understands: {said}"
        );

        // The format this binary wrote is of course readable.
        set_meta(&db, FORMAT_KEY, &FORMAT_VERSION.to_string()).unwrap();
        check_format(&db).unwrap();
    }

    #[test]
    fn only_a_format_4_store_moves_to_format_5_before_a_write() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        // No key: format 1, a single index file; stamping would read it as
        // sharded.
        mark_vector_format(&db).unwrap();
        assert!(get_meta(&db, FORMAT_KEY).unwrap().is_none());
        // Format 3 re-chunks on its first full pass, which stamps it.
        set_meta(&db, FORMAT_KEY, "3").unwrap();
        mark_vector_format(&db).unwrap();
        assert_eq!(format(&db).unwrap(), 3);
        set_meta(&db, FORMAT_KEY, &CODE_CONTEXT.to_string()).unwrap();
        mark_vector_format(&db).unwrap();
        assert_eq!(format(&db).unwrap(), TURBOVEC_V8);
        assert_eq!(TURBOVEC_V8, FORMAT_VERSION);
    }

    fn automerge_row(db: &Connection) -> Option<i64> {
        db.query_row(
            "SELECT v FROM chunks_fts_config WHERE k = 'automerge'",
            [],
            |r| r.get(0),
        )
        .optional()
        .unwrap()
    }

    #[test]
    fn a_held_automerge_is_put_back_as_it_was() {
        let db = Connection::open_in_memory().unwrap();
        db.set_db_config(rusqlite::config::DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)
            .unwrap();
        db.execute_batch(SCHEMA).unwrap();

        // No row before: none after, and nothing left in meta.
        assert_eq!(automerge_row(&db), None);
        hold_automerge(&db).unwrap();
        assert_eq!(automerge_row(&db), Some(0));
        // Held twice (a slice after a crash) still remembers the first value.
        hold_automerge(&db).unwrap();
        release_automerge(&db).unwrap();
        assert_eq!(automerge_row(&db), None);
        assert!(get_meta(&db, AUTOMERGE_HELD_KEY).unwrap().is_none());
        // Released with nothing held is nothing.
        release_automerge(&db).unwrap();
        assert_eq!(automerge_row(&db), None);

        // A store's own value comes back.
        db.execute(
            "INSERT INTO chunks_fts(chunks_fts, rank) VALUES('automerge', 8)",
            [],
        )
        .unwrap();
        hold_automerge(&db).unwrap();
        assert_eq!(automerge_row(&db), Some(0));
        release_automerge(&db).unwrap();
        assert_eq!(automerge_row(&db), Some(8));
    }

    #[test]
    fn a_first_import_lasts_until_a_pass_ends_it() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        assert!(!first_import(&db, false).unwrap(), "a store with rows");
        assert!(
            first_import(&db, true).unwrap(),
            "an empty store starts one"
        );
        assert!(first_import(&db, false).unwrap(), "the next slice is in it");
        end_first_import(&db).unwrap();
        assert!(!first_import(&db, false).unwrap());
    }

    fn seeded() -> Connection {
        let db = Connection::open_in_memory().unwrap();
        db.pragma_update(None, "foreign_keys", "ON").unwrap();
        db.execute_batch(SCHEMA).unwrap();
        let f = insert_file(&db, "/a/lib.rs", "h", 10, 0).unwrap();
        insert_chunk(&db, f, 0, 1, 5, "const EMBED_BATCH: usize = 32;").unwrap();
        insert_chunk(
            &db,
            f,
            1,
            6,
            9,
            "a paragraph about retry backoff and jitter",
        )
        .unwrap();
        db
    }

    /// A corpus with the same word in four files: two under `src`, two not,
    /// two Rust, two Markdown. Enough to tell a union from an intersection.
    /// A store holds the paths its own platform produces, and `filter::anchor`
    /// builds patterns to match those — backslashes on Windows, forward
    /// slashes everywhere else. A fixture written with one separator therefore
    /// tests nothing on the other platform, so these are spelled in the
    /// separator the code under test is going to use.
    fn native(path: &str) -> String {
        path.replace('/', std::path::MAIN_SEPARATOR_STR)
    }

    fn mixed() -> Connection {
        let db = Connection::open_in_memory().unwrap();
        db.pragma_update(None, "foreign_keys", "ON").unwrap();
        db.execute_batch(SCHEMA).unwrap();
        db.execute_batch(GLOB_INDEX).unwrap();
        for path in [
            "/proj/src/lib.rs",
            "/proj/src/notes.md",
            "/proj/vendor/other.rs",
            "/proj/README.MD",
        ] {
            let f = insert_file(&db, &native(path), "h", 10, 0).unwrap();
            insert_chunk(&db, f, 0, 1, 5, "retry backoff and jitter").unwrap();
        }
        db
    }

    /// `groups()` output for a filter, so the tests exercise the same patterns
    /// the CLI produces rather than hand-written globs that could drift from it.
    fn filter(paths: &[&str], exts: &[&str], langs: &[&str]) -> Vec<Vec<String>> {
        let own = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        crate::filter::Filter::new(&own(paths), &own(exts), &own(langs))
            .unwrap()
            .groups()
            .to_vec()
    }

    fn paths_of(db: &Connection, ids: &[u64]) -> Vec<String> {
        let mut out: Vec<String> = ids
            .iter()
            .map(|&i| chunk(db, i).unwrap().unwrap().path)
            .collect();
        out.sort();
        out
    }

    #[test]
    fn keyword_search_finds_an_exact_identifier() {
        let db = seeded();
        let hits = keyword_search(&db, "EMBED_BATCH", 10, &[]).unwrap();
        assert_eq!(hits, vec![1], "expected the defining chunk, got {hits:?}");
    }

    #[test]
    fn a_path_glob_selects_only_what_is_under_it() {
        let db = mixed();
        let ids = filtered_chunk_ids(&db, &filter(&["src/**"], &[], &[])).unwrap();
        assert_eq!(
            paths_of(&db, &ids),
            [native("/proj/src/lib.rs"), native("/proj/src/notes.md")]
        );
    }

    /// A scope to one root is a range of the path index, not a GLOB over every
    /// path (#183): the plan searches `files_glob_path` and scans no table.
    #[test]
    fn a_root_scope_is_a_range_of_the_path_index() {
        let db = mixed();
        let groups = filter(&["/proj/src/**"], &[], &[]);
        let (predicate, binds) = glob_predicate(&groups);
        let sql = format!("EXPLAIN QUERY PLAN SELECT f.id FROM files f WHERE {predicate}");
        let plan: Vec<String> = db
            .prepare(&sql)
            .unwrap()
            .query_map(rusqlite::params_from_iter(binds.iter()), |r| r.get(3))
            .unwrap()
            .map(Result::unwrap)
            .collect();
        assert!(
            plan.iter()
                .any(|p| p.contains("INDEX files_glob_path (<expr>>? AND <expr><?)")),
            "the scope did not use the path index: {plan:?}"
        );
        assert!(!plan.iter().any(|p| p.starts_with("SCAN")), "{plan:?}");
        // And the range changes no answer.
        let ids = filtered_chunk_ids(&db, &groups).unwrap();
        assert_eq!(
            paths_of(&db, &ids),
            [native("/proj/src/lib.rs"), native("/proj/src/notes.md")]
        );
    }

    #[test]
    fn only_a_literal_directory_in_front_is_a_range() {
        assert_eq!(
            literal_dir("/proj/src/**"),
            Some(("/proj/src/".into(), "/proj/src0".into()))
        );
        assert_eq!(
            literal_dir("/proj/src/*.rs"),
            Some(("/proj/src/".into(), "/proj/src0".into()))
        );
        assert_eq!(literal_dir("*/src/**"), None, "a leading wildcard");
        assert_eq!(literal_dir("/*"), None, "the whole disk is no range");
        assert_eq!(
            literal_dir("/proj/readme.md"),
            None,
            "no wildcard, no GLOB to narrow"
        );
    }

    /// An absolute pattern means exactly itself: it must not pick up the
    /// `*/` anchoring a relative one gets.
    #[test]
    fn an_absolute_glob_matches_only_what_it_literally_covers() {
        let db = mixed();
        let ids = filtered_chunk_ids(&db, &filter(&["/proj/vendor/*"], &[], &[])).unwrap();
        assert_eq!(paths_of(&db, &ids), [native("/proj/vendor/other.rs")]);
    }

    #[test]
    fn extensions_union_and_a_language_resolves_to_the_same_set() {
        let db = mixed();
        let by_ext = filtered_chunk_ids(&db, &filter(&[], &["rs"], &[])).unwrap();
        let by_lang = filtered_chunk_ids(&db, &filter(&[], &[], &["rust"])).unwrap();
        assert_eq!(paths_of(&db, &by_ext), paths_of(&db, &by_lang));
        assert_eq!(
            paths_of(&db, &by_ext),
            [native("/proj/src/lib.rs"), native("/proj/vendor/other.rs")]
        );

        let both = filtered_chunk_ids(&db, &filter(&[], &["rs", "md"], &[])).unwrap();
        assert_eq!(both.len(), 4, "repeating --ext must union, not intersect");
    }

    /// `README.MD` is Markdown. Extension matching folds case, so a filter
    /// written the way anyone would write it does not miss it.
    #[test]
    fn extension_matching_is_case_insensitive() {
        let db = mixed();
        let ids = filtered_chunk_ids(&db, &filter(&[], &["md"], &[])).unwrap();
        assert_eq!(
            paths_of(&db, &ids),
            [native("/proj/README.MD"), native("/proj/src/notes.md")]
        );
    }

    #[test]
    fn a_path_and_an_extension_intersect() {
        let db = mixed();
        let ids = filtered_chunk_ids(&db, &filter(&["src/**"], &["md"], &[])).unwrap();
        assert_eq!(
            paths_of(&db, &ids),
            [native("/proj/src/notes.md")],
            "the README is Markdown but is not under src"
        );
    }

    /// The whole point of the release: the keyword half must see the same
    /// subset the vector half is given, or fusion ranks a chunk one side was
    /// never allowed to return.
    #[test]
    fn the_keyword_half_honours_the_same_filter() {
        let db = mixed();
        let unfiltered = keyword_search(&db, "retry backoff", 10, &[]).unwrap();
        assert_eq!(unfiltered.len(), 4);

        let scoped =
            keyword_search(&db, "retry backoff", 10, &filter(&["src/**"], &[], &[])).unwrap();
        assert_eq!(
            paths_of(&db, &scoped),
            [native("/proj/src/lib.rs"), native("/proj/src/notes.md")]
        );
    }

    #[test]
    fn a_filter_matching_nothing_selects_nothing() {
        let db = mixed();
        let groups = filter(&["nowhere/**"], &[], &[]);
        assert_eq!(matching_files(&db, &groups).unwrap(), 0);
        assert!(filtered_chunk_ids(&db, &groups).unwrap().is_empty());
        assert!(
            keyword_search(&db, "retry", 10, &groups)
                .unwrap()
                .is_empty()
        );
    }

    /// An unfiltered search must cost exactly what it cost in 0.2.0. The
    /// statement is the whole of that promise: adding the join unconditionally
    /// would tax every query that uses no filter, and would not fail any other
    /// test in this file.
    #[test]
    fn an_unfiltered_search_issues_the_0_2_0_statement_verbatim() {
        assert_eq!(
            UNFILTERED_SQL,
            "SELECT rowid FROM chunks_fts WHERE chunks_fts MATCH ? ORDER BY rank LIMIT ?"
        );
        // And an empty filter must take that branch, not the general one.
        assert_eq!(glob_predicate(&[]), ("1".to_string(), vec![]));
    }

    #[test]
    fn no_filter_counts_every_file() {
        let db = mixed();
        assert_eq!(matching_files(&db, &[]).unwrap(), 4);
    }

    /// An exclusion on its own means everything except, so it needs no
    /// inclusion beside it to be a filter.
    #[test]
    fn an_exclusion_alone_means_everything_except() {
        let db = mixed();
        let f = filter(&["!**/vendor/**"], &[], &[]);
        assert_eq!(matching_files(&db, &f).unwrap(), 3);
    }

    /// The exclusion applies after the inclusions of its own kind, so the two
    /// intersect rather than the later one replacing the earlier.
    #[test]
    fn an_exclusion_narrows_the_inclusions_of_its_kind() {
        let db = mixed();
        let f = filter(&["proj/**", "!**/vendor/**"], &[], &[]);
        assert_eq!(matching_files(&db, &f).unwrap(), 3);

        let f = filter(&["proj/src/**", "!**/notes.md"], &[], &[]);
        assert_eq!(matching_files(&db, &f).unwrap(), 1);
    }

    /// The bind values are positional, so an exclusion written before an
    /// inclusion must still bind to the `?` the clause puts it against.
    #[test]
    fn an_exclusion_written_first_still_binds_to_its_own_placeholder() {
        let db = mixed();
        let written_first = filter(&["!**/vendor/**", "proj/**"], &[], &[]);
        let written_last = filter(&["proj/**", "!**/vendor/**"], &[], &[]);
        assert_eq!(
            matching_files(&db, &written_first).unwrap(),
            matching_files(&db, &written_last).unwrap(),
        );
        assert_eq!(matching_files(&db, &written_first).unwrap(), 3);
    }

    /// Extensions negate the way paths do, and case-insensitively: a store
    /// holding `README.MD` loses it to `--ext '!md'`.
    #[test]
    fn an_excluded_extension_removes_every_spelling_of_it() {
        let db = mixed();
        let f = filter(&[], &["!md"], &[]);
        assert_eq!(matching_files(&db, &f).unwrap(), 2);
    }

    /// A group holding only exclusions still selects from everything, and the
    /// two kinds still intersect across groups.
    #[test]
    fn exclusions_of_different_kinds_intersect() {
        let db = mixed();
        let f = filter(&["!**/vendor/**"], &["!md"], &[]);
        assert_eq!(matching_files(&db, &f).unwrap(), 1);
    }

    #[test]
    fn fts_syntax_in_a_query_is_not_executed_as_syntax() {
        let db = seeded();
        // Each of these is either an FTS5 syntax error or an FTS5 operator if
        // passed through raw. All must come back as ordinary searches.
        for query in [
            "EMBED_BATCH AND retry",
            "unbalanced \" quote",
            "call_me(",
            "prefix*",
            "NEAR(a b)",
            "-negated",
        ] {
            let result = keyword_search(&db, query, 10, &[]);
            assert!(
                result.is_ok(),
                "query {query:?} errored: {:?}",
                result.err()
            );
        }
    }

    #[test]
    fn a_query_with_no_terms_matches_nothing() {
        let db = seeded();
        assert!(keyword_search(&db, "!!! ???", 10, &[]).unwrap().is_empty());
    }

    #[test]
    fn deleting_a_file_removes_its_chunks_from_the_keyword_index() {
        let db = seeded();
        assert!(
            !keyword_search(&db, "EMBED_BATCH", 10, &[])
                .unwrap()
                .is_empty()
        );
        delete_file(&db, "/a/lib.rs", 0).unwrap();
        assert!(
            keyword_search(&db, "EMBED_BATCH", 10, &[])
                .unwrap()
                .is_empty(),
            "cascade delete left the keyword index stale"
        );
    }

    /// A store written by 0.15.0 has no `edges.line`. Opening it must add the
    /// column without touching the rows, and every edge already in it must
    /// report no call site rather than a wrong one.
    #[test]
    fn a_pre_0_16_store_opens_and_its_edges_report_no_call_site() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(
            "CREATE TABLE files (id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE,
                 hash TEXT NOT NULL, bytes INTEGER NOT NULL, indexed_at INTEGER NOT NULL);
             CREATE TABLE symbols (id INTEGER PRIMARY KEY AUTOINCREMENT,
                 file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
                 chunk_id INTEGER, kind TEXT NOT NULL, name TEXT NOT NULL,
                 qualified TEXT NOT NULL, start_line INTEGER NOT NULL, end_line INTEGER NOT NULL);
             CREATE TABLE edges (src INTEGER NOT NULL REFERENCES symbols(id) ON DELETE CASCADE,
                 dst TEXT NOT NULL, kind TEXT NOT NULL, confidence TEXT NOT NULL, hint TEXT);
             INSERT INTO files VALUES (1, '/a/lib.rs', 'h', 10, 0);
             INSERT INTO symbols VALUES (1, 1, NULL, 'function', 'caller', 'm::caller', 1, 9);
             INSERT INTO symbols VALUES (2, 1, NULL, 'function', 'callee', 'm::callee', 20, 24);
             CREATE TABLE retrievals (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL,
                 client TEXT NOT NULL, query TEXT NOT NULL, hits INTEGER NOT NULL,
                 micros INTEGER NOT NULL, excerpt_tokens INTEGER NOT NULL,
                 whole_file_tokens INTEGER NOT NULL);
             INSERT INTO edges VALUES (1, 'callee', 'calls', 'inferred', NULL);",
        )
        .unwrap();

        add_columns(&db).unwrap();

        let out = edges_out(&db, "caller", &[]).unwrap();
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(
            out[0].line, None,
            "a 0.15.0 row must not invent a call site"
        );
        assert_eq!(
            crate::graph::call_site(&out[0], &crate::graph::verbatim),
            "",
            "nothing is rendered for an edge with no line"
        );

        let into = edges_in(&db, "callee", &[]).unwrap();
        assert_eq!(into.len(), 1, "{into:?}");
        assert_eq!(into[0].line, None);
    }

    /// An older binary opening the store puts the insert trigger back; the
    /// writer drops it before inserting, so a chunk is indexed once (#198).
    #[test]
    fn an_insert_trigger_an_older_binary_restored_does_not_index_twice() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        add_columns(&db).unwrap();
        db.execute_batch(
            "CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
                 INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
             END;",
        )
        .unwrap();
        db.execute_batch("BEGIN").unwrap();
        drop_insert_trigger(&db).unwrap();
        let f = insert_file(&db, "/a/lib.rs", "h", 10, 0).unwrap();
        let id = insert_chunk(&db, f, 0, 1, 5, "retry backoff and jitter").unwrap();
        db.execute_batch("COMMIT").unwrap();
        assert_eq!(
            keyword_search(&db, "jitter", 10, &[]).unwrap(),
            vec![id as u64]
        );
        // Indexed once: an integrity check of external content fails on a
        // doubled row.
        db.execute_batch("INSERT INTO chunks_fts(chunks_fts, rank) VALUES('integrity-check', 1);")
            .unwrap();
        // And a delete still takes it out of the index.
        db.execute("DELETE FROM files WHERE id = ?1", [f]).unwrap();
        assert!(keyword_search(&db, "jitter", 10, &[]).unwrap().is_empty());
    }

    #[test]
    fn an_old_store_gets_its_keyword_index_backfilled() {
        // A 0.1.0 store: chunks written with no FTS table in the schema.
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(
            "CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
             CREATE TABLE files (id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE,
                 hash TEXT NOT NULL, bytes INTEGER NOT NULL, indexed_at INTEGER NOT NULL);
             CREATE TABLE chunks (id INTEGER PRIMARY KEY, file_id INTEGER NOT NULL
                 REFERENCES files(id) ON DELETE CASCADE, ord INTEGER NOT NULL,
                 start_line INTEGER NOT NULL, end_line INTEGER NOT NULL, text TEXT NOT NULL);
             INSERT INTO files VALUES (1, '/a/lib.rs', 'h', 10, 0);
             INSERT INTO chunks VALUES (1, 1, 0, 1, 5, 'const EMBED_BATCH: usize = 32;');",
        )
        .unwrap();

        // Opening it with the current schema must index what is already there.
        db.execute_batch(SCHEMA).unwrap();
        backfill_fts(&db).unwrap();
        assert_eq!(
            keyword_search(&db, "EMBED_BATCH", 10, &[]).unwrap(),
            vec![1]
        );
    }

    #[test]
    fn a_key_searched_for_is_recorded_masked_and_the_chain_still_verifies() {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch(SCHEMA).unwrap();
        add_columns(&db).unwrap();
        let key = crate::keyscan::forge(0);
        let query = format!("where is {key} used");
        for q in [query.as_str(), "an ordinary question"] {
            record_retrieval(
                &db,
                &NewRetrieval {
                    client_version: "",
                    client: "cli",
                    session: "s",
                    tool: "search",
                    query: q,
                    hits: 1,
                    micros: 1,
                    excerpt_tokens: 1,
                    whole_file_tokens: 1,
                    stale_hits: 0,
                    tokenizer: "estimate",
                    query_id: "q",
                },
            )
            .unwrap();
        }
        let rows = retrievals(&db, 10).unwrap();
        assert!(
            rows.iter().all(|r| !r.query.contains(&key)),
            "the key was recorded in full"
        );
        assert!(
            rows.iter()
                .any(|r| r.query.starts_with("where is [REDACTED:"))
        );
        assert!(rows.iter().any(|r| r.query == "an ordinary question"));
        assert_eq!(ledger_break(&db).unwrap(), None);
    }

    /// Two connections to one store recording at once leave one chain.
    ///
    /// The daemon and a CLI search are two such writers. Before 0.33.0 each read
    /// the last hash and then inserted, so a writer that read while the other
    /// held an uncommitted row chained to the row before it, and the ledger
    /// reported the second row as edited though nothing had been.
    #[test]
    fn two_connections_recording_at_once_leave_a_chain_that_verifies() {
        fn row(query: &str) -> NewRetrieval<'_> {
            NewRetrieval {
                client_version: "",
                client: "cli",
                session: "s",
                tool: "search",
                query,
                hits: 1,
                micros: 1,
                excerpt_tokens: 1,
                whole_file_tokens: 1,
                stale_hits: 0,
                tokenizer: "chars4",
                query_id: "",
            }
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("store.db");
        let first = open(&path).unwrap();
        let second = open(&path).unwrap();

        // `first` is mid-write: its row is in, not yet committed.
        read_only(&first, false).unwrap();
        first.execute_batch("BEGIN IMMEDIATE").unwrap();
        record_retrieval(&first, &row("first")).unwrap();

        // `second` records meanwhile, and has to end up chained to that row.
        let waiting = std::thread::spawn(move || record_retrieval(&second, &row("second")));
        // Long enough for the unguarded read to have happened; the guarded one
        // is waiting on the lock and is unaffected by how long this is.
        std::thread::sleep(std::time::Duration::from_millis(300));
        read_only(&first, false).unwrap();
        first.execute_batch("COMMIT").unwrap();
        waiting.join().unwrap().unwrap();

        assert_eq!(retrievals(&first, 10).unwrap().len(), 2);
        assert_eq!(
            ledger_break(&first).unwrap(),
            None,
            "two writers forked the chain"
        );
    }
}