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
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
//! Structure half of the store: symbols, and the edges between them.
//!
//! Extraction is tree-sitter over a file's text, and it hangs off the same
//! changed-file path that drives re-embedding (see [`crate::Semlith::index_set`]).
//! That is the whole freshness story: there is no build step, no separate
//! command, and no artifact that can be out of date with the corpus, because
//! the pass that re-embeds a file is the pass that re-extracts it.
//!
//! Every language in [`crate::filter::LANGUAGES`] carries edges — all
//! forty-six, since 0.17.0 replaced the extractor's own six-language list with
//! a question asked of the grammar table. A row with no grammar is named in
//! [`WITHOUT_GRAMMAR`] with the reason; it is searchable exactly as before and
//! simply has no rows here.
//!
//! # Where the queries come from
//!
//! Every grammar ships a `TAGS_QUERY` written for `tree-sitter tags`, and it is
//! a good source of *definitions* — that is what it was built for. Its
//! reference coverage is uneven and none of it covers imports: of the six here,
//! none capture import statements at all, and TypeScript and C capture no calls
//! either. So each language pairs the bundled query with a short supplementary
//! one below, and the two are run together.
//!
//! # Confidence
//!
//! An edge is `extracted` when the syntax tree says where the target came from
//! — a structural edge, or a call whose name the file also imports — and
//! `inferred` when the target was matched by bare name alone. Two functions
//! called `new` in different modules is the normal case in real code, not a
//! corner case, so an inferred edge is marked and stays marked everywhere it
//! surfaces. Nothing may present one as the other.

use anyhow::Result;

/// How long one file's parse may take before it is given up on.
const PARSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
use std::path::Path;
use tree_sitter::{Language, Parser, Query, QueryCursor, StreamingIterator};

/// Edge kinds, as stored in `edges.kind`.
pub const KINDS: [&str; 6] = [
    "defines",
    "calls",
    "imports",
    "references",
    "contains",
    "aliases",
];

/// Stored on the edge: the syntax tree said where the target came from.
pub const EXTRACTED: &str = "extracted";
/// Stored on the edge: the target was matched by bare name alone.
pub const INFERRED: &str = "inferred";

/// What `edges.hint` starts with when the call went through a receiver
/// (`x.run()`, `self.flush()`): the rest is the receiver's type or name, and
/// may be empty. The resolver never settles such an edge on a free function,
/// and settles it at all only on a method of the receiver's stated type.
pub const RECEIVER: &str = ".";
/// Computed at query time: the name had several definitions and the hint,
/// the source file, or its imports picked exactly one of them.
pub const RESOLVED: &str = "resolved";
/// Computed at query time: the name had several definitions and nothing in
/// the source narrowed it to one. An answer that crosses one of these is a
/// guess, and every surface says so.
pub const AMBIGUOUS: &str = "ambiguous";

/// Every confidence value a renderer can be handed, strongest first.
///
/// Two are written to `edges.confidence` and two are decided when the edge is
/// read, because a stored `resolved` would go stale the moment a second
/// definition of the name was indexed somewhere else.
pub const CONFIDENCES: [&str; 4] = [EXTRACTED, RESOLVED, INFERRED, AMBIGUOUS];

/// How much a confidence value is worth when something has to be ordered by
/// it: lower is better. An unknown value sorts last rather than panicking, so
/// a store written by a newer binary still renders.
pub fn confidence_rank(confidence: &str) -> usize {
    CONFIDENCES
        .iter()
        .position(|c| *c == confidence)
        .unwrap_or(CONFIDENCES.len())
}

/// A symbol found in a file, before it has an id.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Symbol {
    pub kind: String,
    pub name: String,
    pub qualified: String,
    pub start_line: u32,
    pub end_line: u32,
}

/// An edge found in a file, before either end has an id.
///
/// `from` is the name of the symbol the reference sits inside — the file's
/// module symbol when it sits at the top level.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Edge {
    pub from: String,
    pub to: String,
    pub kind: String,
    pub confidence: String,
    /// What the source text said about where the target lives, when it said
    /// anything: the module of a scoped call, the receiver of a method call,
    /// the object of a qualified one. `None` for a bare call, for an import,
    /// and for every structural edge.
    ///
    /// It is a lead, not an address — `self.index.search` yields `index`,
    /// which may name a field, a module or neither. The resolver treats it as
    /// one ranking signal among several rather than as truth.
    pub hint: Option<String>,
    /// The line the reference sat on in the source file.
    ///
    /// Where the call, import or reference was written — not where either
    /// symbol is defined. "Where is X invoked" is a question about this line,
    /// and before 0.16.0 the only answer available was the enclosing symbol's
    /// definition, which can be hundreds of lines away.
    ///
    /// `None` on every row an older binary wrote, which is why the format
    /// version does not move for it.
    pub line: Option<u32>,
    /// The edge leaves from the file's module symbol: a `defines` edge, or a
    /// reference at the top level. Without it a file and a definition that
    /// share a name — `main.rs` and `fn main` — are one source, and the
    /// module's `defines` edges were written onto `fn main` (2026-10-14
    /// audit, G3).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub from_module: bool,
}

/// What one file yielded.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Extraction {
    pub symbols: Vec<Symbol>,
    pub edges: Vec<Edge>,
}

/// Languages in [`crate::filter::LANGUAGES`] that ship without a graph, and why.
///
/// A grammar is refused when its licence is copyleft or cannot be identified:
/// the parser is compiled into this binary, so a GPL or LGPL grammar would take
/// the whole Apache-2.0 crate with it, and a licence nobody can name is treated
/// as the worst case rather than the best. A row here is a deliberate, stated
/// gap; a row missing from both here and the grammar table is a bug, and
/// `every_advertised_language_has_a_grammar` fails for it.
pub const WITHOUT_GRAMMAR: &[(&str, &str)] = &[];

/// Whether the graph covers a language.
///
/// There is one list, [`crate::filter::LANGUAGES`], and one answer to "does
/// this language have a grammar" — this function. Nothing keeps a second copy
/// of the set, because the six-language copy that used to live here drifted
/// from the forty-six the product advertised for four releases.
pub fn has_graph(lang: &str) -> bool {
    grammar(lang).is_some()
}

/// Whether a bare `f()` in this language can only mean a function, never a
/// method of the type around the call. True for Rust, Python, Go and
/// JavaScript and TypeScript (Svelte and Vue scripts included): a method there
/// is reached through `self.`, `this.` or a value. Java, Kotlin, Scala,
/// Groovy, C#, C++, Objective-C, Swift, Dart, Ruby and PHP are left out, as is
/// every language not named here, because inside a class body a bare
/// `helper()` can be `this.helper()`.
pub(crate) fn no_implicit_receiver(lang: &str) -> bool {
    matches!(
        lang,
        "rust" | "python" | "go" | "javascript" | "typescript" | "svelte" | "vue"
    )
}

/// Whether a bare `helper()` inside a class body can be `this.helper()`: the
/// languages [`no_implicit_receiver`] leaves out because of it. PHP and
/// Objective-C are not here — a member there is reached only through `$this`
/// or `self` — and neither is any language without classes.
fn implicit_receiver(lang: &str) -> bool {
    matches!(
        lang,
        "java" | "kotlin" | "scala" | "groovy" | "csharp" | "cpp" | "swift" | "dart" | "ruby"
    )
}

/// Every language the graph covers, in the table's own order.
pub fn languages() -> Vec<&'static str> {
    crate::filter::LANGUAGES
        .iter()
        .map(|entry| entry.name)
        .filter(|name| has_graph(name))
        .collect()
}

/// The language label for a path, if this release extracts from it.
///
/// Dispatch is by extension and whole filename, through the same
/// [`crate::filter::language_of_path`] the search filter uses, so a file is in
/// exactly one language no matter which half of the product is asking.
pub fn language_of(path: &Path) -> Option<&'static str> {
    let entry = crate::filter::language_of_path(&path.to_string_lossy())?;
    has_graph(entry.name).then_some(entry.name)
}

/// What each grammar's `TAGS_QUERY` does not give us.
///
/// Kept short on purpose: the bundled query is the source of truth for
/// definitions, and this closes the three gaps it has — imports, which no
/// grammar here captures; calls, which TypeScript and C do not; and constants,
/// which almost none of them do.
///
/// A constant is a definition an agent types by name, and without a symbol row
/// the definition lift in `search_preferring` cannot fire for one. That is why
/// `MAX_NODES`, `RRF_K` and `KEY_GRACE` were the identifier questions 0.22.0
/// could not put in the top three while `edges_out` and `DEPENDENCY_KINDS` — a
/// function and an array the Rust query does tag — sat at rank 1. Rust was the
/// only language 0.22.0 fixed, so the same hole was open in the other
/// forty-five; 0.23.0 closes it wherever the language has a construct for a
/// named constant at all. Where a grammar already makes one a symbol under
/// another name — Dart and Zig call it a variable, Kotlin and Swift a property,
/// Python a constant already — nothing is added here, because a second capture
/// over the same span is how one symbol ends up containing itself.
fn supplement(lang: &str) -> &'static str {
    match lang {
        "rust" => {
            r#"
            (const_item name: (identifier) @name) @definition.constant
            (static_item name: (identifier) @name) @definition.constant
            (use_declaration argument: (_) @reference.import)
            ; `use store::Semlith as Store;` — the alias is a symbol of its own
            ; and the path it stands for is what it reaches. Without the edge a
            ; walk stops at `Store`, which is defined nowhere.
            (use_as_clause
              path: (_) @reference.alias
              alias: (_) @name) @definition.alias
            ; A scoped call names the function and the thing it went through.
            ; Only the function earns an edge: `store::edges_out` is a call to
            ; `edges_out`, and `store` is what says *which* `edges_out`. Until
            ; 0.15.0 the path segment was emitted as a second `calls` edge,
            ; which recorded a call the source does not make and put a module
            ; name into every path the finder walked. It is a hint now.
            (call_expression
              function: (scoped_identifier
                path: (identifier) @hint
                name: (identifier) @name)) @reference.call
            ; A longer path, `crate::store::edges_out`: the hint is the segment
            ; nearest the name, because that is the one that names the module.
            (call_expression
              function: (scoped_identifier
                path: (scoped_identifier name: (identifier) @hint)
                name: (identifier) @name)) @reference.call
            ; `crate::search_parallel(args)`, `self::helper()`, `super::run()`:
            ; a path the grammar spells with a keyword, so `(identifier)` above
            ; never matched it and the call was missed (2026-10-14 audit, G2).
            ; The keyword names no file, so there is no hint.
            (call_expression
              function: (scoped_identifier
                path: [(crate) (self) (super)]
                name: (identifier) @name)) @reference.call
            ; A method call: `self.flush()`, `store.db()`, `self.index.search()`.
            ; The receiver is the hint, reduced to its type or last identifier,
            ; and marked as a receiver: a method call never means a free fn.
            (call_expression
              function: (field_expression
                value: (_) @receiver
                field: (field_identifier) @name)) @reference.call
            ; A call inside a macro's arguments: `json!({ "x": f(1) })`. The
            ; grammar leaves the arguments as a flat token tree, so none of the
            ; patterns above ever saw `f(1)` and the call had no edge — which
            ; is how a caller inside a `json!` slipped past the impact check
            ; (#244). The same three shapes are read off the tokens instead: a
            ; name, `a::name` with the segment as the hint, and `x.name` with
            ; `x` as the receiver, each followed by a parenthesised tree. A
            ; tree whose own child is `(` is one the parentheses delimit; an
            ; anchor on that first child misses `()`. An anchor also skips the
            ; `!` of a nested `vec![..]` or `format!(..)`, and a query cannot
            ; see whether the tree sits in a macro call or an attribute, so
            ; `collect` finishes the check; see `macro_argument_call`.
            (token_tree
              (identifier) @name . (token_tree "(") @reference.call)
            (token_tree
              (identifier) @hint . "::" . (identifier) @name
              . (token_tree "(") @reference.call)
            (token_tree
              (_) @receiver . "." . (identifier) @name
              . (token_tree "(") @reference.call)
        "#
        }
        // TypeScript's bundled query matches nothing on ordinary unexported
        // declarations, so its definitions are spelled out here rather than
        // inherited.
        "typescript" => {
            r#"
            (import_statement source: (string) @reference.import)
            ; `import { search as find }` and `export { search as find }`.
            (import_specifier
              name: (_) @reference.alias
              alias: (identifier) @name) @definition.alias
            (export_specifier
              name: (_) @reference.alias
              alias: (identifier) @name) @definition.alias
            (function_declaration name: (identifier) @name) @definition.function
            (class_declaration name: (type_identifier) @name) @definition.class
            (interface_declaration name: (type_identifier) @name) @definition.interface
            (method_definition name: (property_identifier) @name) @definition.method
            (variable_declarator
              name: (identifier) @name
              value: [(arrow_function) (function_expression)]) @definition.function
            ; `const MAX_HOLDERS = 4`. The value is spelled out rather than
            ; left as `(_)` so that the arrow function on the line above stays
            ; one symbol: a `const` bound to a function is a function, and
            ; tagging it twice would make `semlith symbol` report two
            ; definitions of it.
            (lexical_declaration
              "const"
              (variable_declarator
                name: (identifier) @name
                value: [
                  (number) (string) (template_string) (true) (false) (null)
                  (object) (array) (identifier) (member_expression)
                  (unary_expression) (binary_expression)
                  (call_expression) (new_expression)
                ])) @definition.constant
            (call_expression function: (identifier) @name) @reference.call
            ; `store.search(...)`, `this.index.search(...)`: the object is the
            ; hint, reduced to its last identifier.
            (call_expression
              function: (member_expression
                object: (_) @hint
                property: (property_identifier) @name)) @reference.call
        "#
        }
        "python" => {
            r#"
            (import_statement name: (_) @reference.import)
            (import_from_statement module_name: (_) @reference.import)
            ; `import numpy as np`, `from x import search as find`.
            (aliased_import
              name: (_) @reference.alias
              alias: (identifier) @name) @definition.alias
            ; `json.loads(...)`, `self.store.search(...)`: the object names the
            ; module or the receiver the call went through. A receiver unless
            ; the file imports the name as a module; see `extract`.
            (call
              function: (attribute
                object: (_) @receiver
                attribute: (identifier) @name)) @reference.call
        "#
        }
        "go" => {
            r#"
            ; `const MaxHolders = 4`, and every name in a parenthesised
            ; `const (...)` block, which is one `const_spec` each.
            (const_declaration (const_spec name: (identifier) @name) @definition.constant)
            (import_spec path: (interpreted_string_literal) @reference.import)
            ; `import fp "path/filepath"` — the alias is what the file then
            ; writes, and the path is what it stands for.
            (import_spec
              name: (package_identifier) @name
              path: (interpreted_string_literal) @reference.alias) @definition.alias
            ; `fmt.Errorf(...)`, `c.validate()`: the operand is the hint, which
            ; is what tells `fmt.Errorf` from a call into this corpus.
            (call_expression
              function: (selector_expression
                operand: (identifier) @hint
                field: (field_identifier) @name)) @reference.call
        "#
        }
        "java" => {
            r#"
            (import_declaration (scoped_identifier) @reference.import)
            ; `static final int MAX_HOLDERS = 4;`. Java has no `const`, so a
            ; constant is a field that says `final`, and the modifiers are the
            ; only place that is written.
            ((field_declaration
               (modifiers) @_modifiers
               declarator: (variable_declarator name: (identifier) @name)) @definition.constant
             (#match? @_modifiers "\\bfinal\\b"))
        "#
        }
        // C++ has C's problem and C's fix: the bundled query tags the declarator,
        // so a function's span stopped at its signature, and it captures no
        // calls at all.
        "cpp" => {
            r#"
            (preproc_include path: (_) @reference.import)
            (call_expression function: (identifier) @reference.call)
            (function_definition
              declarator: (function_declarator
                declarator: (identifier) @name)) @definition.function
            ; `#define MAX_HOLDERS 4` and `constexpr int MAX_WAITERS = 8;`.
            ; C++ has both of C's macro and a real constant declaration, and
            ; the qualifier is what tells the second from a plain variable —
            ; `volatile` sits in the same node and is not one.
            (preproc_def name: (identifier) @name) @definition.constant
            ((declaration
               (type_qualifier) @_qualifier
               declarator: (init_declarator declarator: (identifier) @name)) @definition.constant
             (#any-of? @_qualifier "const" "constexpr" "consteval" "constinit"))
        "#
        }
        "csharp" => {
            r#"
            (using_directive (identifier) @reference.import)
            ; `const int MaxHolders = 4;`. A field is a constant only when it
            ; says so, and `static`, `readonly` and the access modifiers all
            ; arrive in the same node.
            ((field_declaration
               (modifier) @_const
               (variable_declaration
                 (variable_declarator name: (identifier) @name))) @definition.constant
             (#eq? @_const "const"))
            (invocation_expression function: (identifier) @name) @reference.call
            ; `store.Search(...)`: the object is the hint.
            (invocation_expression
              function: (member_access_expression
                expression: (_) @hint
                name: (identifier) @name)) @reference.call
        "#
        }
        // Elm's bundled query captures the name in a type annotation as a
        // reference and the body of a declaration not at all, so `acquire =
        // helper` recorded nothing about `acquire` depending on `helper`.
        "elm" => {
            r#"
            (value_declaration
              functionDeclarationLeft: (function_declaration_left
                (lower_case_identifier) @name)) @definition.function
            (value_expr name: (value_qid (lower_case_identifier) @name)) @reference.call
            (import_clause moduleName: (upper_case_qid) @reference.import)
        "#
        }
        "javascript" => {
            r#"
            (import_statement source: (string) @reference.import)
            (import_specifier
              name: (_) @reference.alias
              alias: (identifier) @name) @definition.alias
            (export_specifier
              name: (_) @reference.alias
              alias: (identifier) @name) @definition.alias
            ; `const MAX_HOLDERS = 4`. The bundled query tags only the
            ; `export module.exports = ...` form, so an ordinary top-level
            ; constant reached the graph as nothing at all. The value is
            ; spelled out so that `const f = () => {}` stays a function.
            (lexical_declaration
              "const"
              (variable_declarator
                name: (identifier) @name
                value: [
                  (number) (string) (template_string) (true) (false) (null)
                  (object) (array) (identifier) (member_expression)
                  (unary_expression) (binary_expression)
                  (call_expression) (new_expression)
                ])) @definition.constant
            ; `store.search(...)`, `view.sel.clear()`: the object is the hint,
            ; as in TypeScript. Without it every member call read as a bare
            ; one.
            (call_expression
              function: (member_expression
                object: (_) @hint
                property: (property_identifier) @name)) @reference.call
        "#
        }
        "php" => {
            r#"
            (require_expression (string (string_content) @reference.import))
            (include_expression (string (string_content) @reference.import))
            (function_call_expression function: (name) @name) @reference.call
            (member_call_expression
              object: (_) @hint
              name: (name) @name) @reference.call
            ; `const MAX_HOLDERS = 4;`, whether it stands alone or inside a
            ; class. `define('MAX_HOLDERS', 4)` is a function call and stays
            ; one: the name it binds is a string, not an identifier the
            ; grammar can hand back.
            (const_declaration (const_element (name) @name)) @definition.constant
        "#
        }
        "swift" => {
            r#"
            (import_declaration (identifier) @reference.import)
            (call_expression (simple_identifier) @name) @reference.call
            (call_expression
              (navigation_expression
                target: (_) @hint
                suffix: (navigation_suffix (simple_identifier) @name))) @reference.call
        "#
        }
        "c" => {
            r#"
            (preproc_include path: (_) @reference.import)
            (call_expression function: (identifier) @reference.call)
            ; C's bundled query tags the declarator, so a function's span stops
            ; at its signature and every call inside its body was attributed to
            ; the file instead of to the function that makes it. This spans the
            ; whole definition; the narrower duplicate is dropped by the
            ; contained-definition rule below.
            (function_definition
              declarator: (function_declarator
                declarator: (identifier) @name)) @definition.function
            ; `#define MAX_HOLDERS 4`. This is C's named constant, and not a
            ; stylistic alternative to one: a `const int` is a read-only
            ; object rather than a constant expression, and cannot size an
            ; array or label a case.
            (preproc_def name: (identifier) @name) @definition.constant
        "#
        }
        "ruby" => {
            r#"
            ; Ruby has no `const` keyword. A name that begins with a capital
            ; is a constant, and the grammar says so by parsing it as
            ; `constant` rather than `identifier` — which is why this needs no
            ; predicate and no naming convention of our own.
            (assignment left: (constant) @name) @definition.constant
        "#
        }
        "elixir" => {
            r#"
            ; `@max_holders 4`. A module attribute is the nearest thing
            ; Elixir has to a constant, and the grammar has no node for one:
            ; it is `@` applied to a call with no parentheses. The attributes
            ; the language reserves for documentation and typespecs go
            ; through the same syntax and are not constants.
            ((unary_operator
               "@"
               operand: (call target: (identifier) @name (arguments))) @definition.constant
             (#not-any-of? @name
               "moduledoc" "doc" "typedoc" "spec" "type" "typep" "opaque"
               "callback" "macrocallback" "behaviour" "impl" "deprecated"
               "derive" "enforce_keys" "compile" "dialyzer" "on_definition"
               "before_compile" "after_compile" "external_resource"))
        "#
        }
        "lua" => {
            r#"
            ; `local MAX_HOLDERS <const> = 4`. Lua 5.4's attribute is the only
            ; thing in the language that makes a binding a constant; a local
            ; without one is reassignable and is not.
            ((variable_declaration
               (assignment_statement
                 (variable_list
                   name: (identifier) @name
                   attribute: (attribute (identifier) @_attribute)))) @definition.constant
             (#eq? @_attribute "const"))
        "#
        }
        _ => "",
    }
}

/// The grammar for a language, for a caller outside the extractor.
///
/// `semlith pattern` compiles its own query against the same grammar the
/// extractor uses, read from the same table, so the two halves cannot disagree
/// about what "rust" is.
pub fn language_grammar(lang: &str) -> Option<Language> {
    grammar(lang).map(|(language, _)| language)
}

fn grammar(lang: &str) -> Option<(Language, &'static str)> {
    match lang {
        "rust" => Some((
            tree_sitter_rust::LANGUAGE.into(),
            tree_sitter_rust::TAGS_QUERY,
        )),
        "typescript" => Some((
            tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
            tree_sitter_typescript::TAGS_QUERY,
        )),
        "python" => Some((
            tree_sitter_python::LANGUAGE.into(),
            tree_sitter_python::TAGS_QUERY,
        )),
        "go" => Some((tree_sitter_go::LANGUAGE.into(), tree_sitter_go::TAGS_QUERY)),
        "java" => Some((
            tree_sitter_java::LANGUAGE.into(),
            tree_sitter_java::TAGS_QUERY,
        )),
        "c" => Some((tree_sitter_c::LANGUAGE.into(), tree_sitter_c::TAGS_QUERY)),

        // The forty languages 0.17.0 added. Twenty-three of their crates ship a
        // tags query written for `tree-sitter tags`, which is the same
        // arrangement the six above have. The other seventeen ship none, so
        // the query is written here under `queries/<language>/tags.scm` in the
        // same capture vocabulary, and the extractor cannot tell the two apart.
        "clojure" => Some((
            tree_sitter_clojure_orchard::LANGUAGE.into(),
            include_str!("../queries/clojure/tags.scm"),
        )),
        "cpp" => Some((
            tree_sitter_cpp::LANGUAGE.into(),
            tree_sitter_cpp::TAGS_QUERY,
        )),
        "csharp" => Some((
            tree_sitter_c_sharp::LANGUAGE.into(),
            tree_sitter_c_sharp::TAGS_QUERY,
        )),
        "dart" => Some((
            tree_sitter_dart::LANGUAGE.into(),
            tree_sitter_dart::TAGS_QUERY,
        )),
        "dockerfile" => Some((
            tree_sitter_containerfile::LANGUAGE.into(),
            include_str!("../queries/dockerfile/tags.scm"),
        )),
        "elixir" => Some((
            tree_sitter_elixir::LANGUAGE.into(),
            tree_sitter_elixir::TAGS_QUERY,
        )),
        "elm" => Some((
            tree_sitter_elm::LANGUAGE.into(),
            tree_sitter_elm::TAGS_QUERY,
        )),
        "erlang" => Some((
            tree_sitter_erlang::LANGUAGE.into(),
            include_str!("../queries/erlang/tags.scm"),
        )),
        "fortran" => Some((
            tree_sitter_fortran::LANGUAGE.into(),
            include_str!("../queries/fortran/tags.scm"),
        )),
        "graphql" => Some((
            tree_sitter_graphql::LANGUAGE.into(),
            include_str!("../queries/graphql/tags.scm"),
        )),
        "groovy" => Some((
            tree_sitter_groovy::LANGUAGE.into(),
            include_str!("../queries/groovy/tags.scm"),
        )),
        "javascript" => Some((
            tree_sitter_javascript::LANGUAGE.into(),
            tree_sitter_javascript::TAGS_QUERY,
        )),
        "lua" => Some((
            tree_sitter_lua::LANGUAGE.into(),
            tree_sitter_lua::TAGS_QUERY,
        )),
        "nix" => Some((
            tree_sitter_nix::LANGUAGE.into(),
            include_str!("../queries/nix/tags.scm"),
        )),
        "ocaml" => Some((
            tree_sitter_ocaml::LANGUAGE_OCAML.into(),
            tree_sitter_ocaml::TAGS_QUERY,
        )),
        "php" => Some((
            tree_sitter_php::LANGUAGE_PHP.into(),
            tree_sitter_php::TAGS_QUERY,
        )),
        "powershell" => Some((
            tree_sitter_powershell::LANGUAGE.into(),
            include_str!("../queries/powershell/tags.scm"),
        )),
        "proto" => Some((
            tree_sitter_proto::LANGUAGE.into(),
            include_str!("../queries/proto/tags.scm"),
        )),
        "r" => Some((tree_sitter_r::LANGUAGE.into(), tree_sitter_r::TAGS_QUERY)),
        "ruby" => Some((
            tree_sitter_ruby::LANGUAGE.into(),
            tree_sitter_ruby::TAGS_QUERY,
        )),
        "sql" => Some((
            tree_sitter_sequel::LANGUAGE.into(),
            include_str!("../queries/sql/tags.scm"),
        )),
        "swift" => Some((
            tree_sitter_swift::LANGUAGE.into(),
            tree_sitter_swift::TAGS_QUERY,
        )),
        "vue" => Some((
            tree_sitter_vue_next::LANGUAGE.into(),
            include_str!("../queries/vue/tags.scm"),
        )),
        "css" => Some((
            tree_sitter_css::LANGUAGE.into(),
            include_str!("../queries/css/tags.scm"),
        )),
        "haskell" => Some((
            tree_sitter_haskell::LANGUAGE.into(),
            include_str!("../queries/haskell/tags.scm"),
        )),
        "html" => Some((
            tree_sitter_html::LANGUAGE.into(),
            include_str!("../queries/html/tags.scm"),
        )),
        "json" => Some((
            tree_sitter_json::LANGUAGE.into(),
            include_str!("../queries/json/tags.scm"),
        )),
        "julia" => Some((
            tree_sitter_julia::LANGUAGE.into(),
            include_str!("../queries/julia/tags.scm"),
        )),
        "kotlin" => Some((
            tree_sitter_kotlin_ng::LANGUAGE.into(),
            include_str!("../queries/kotlin/tags.scm"),
        )),
        "makefile" => Some((
            tree_sitter_make::LANGUAGE.into(),
            include_str!("../queries/makefile/tags.scm"),
        )),
        "markdown" => Some((
            tree_sitter_md::LANGUAGE.into(),
            include_str!("../queries/markdown/tags.scm"),
        )),
        "objective-c" => Some((
            tree_sitter_objc::LANGUAGE.into(),
            include_str!("../queries/objective-c/tags.scm"),
        )),
        "perl" => Some((
            ts_parser_perl::LANGUAGE.into(),
            include_str!("../queries/perl/tags.scm"),
        )),
        "scala" => Some((
            tree_sitter_scala::LANGUAGE.into(),
            include_str!("../queries/scala/tags.scm"),
        )),
        "shell" => Some((
            tree_sitter_bash::LANGUAGE.into(),
            include_str!("../queries/shell/tags.scm"),
        )),
        "svelte" => Some((
            tree_sitter_svelte_ng::LANGUAGE.into(),
            include_str!("../queries/svelte/tags.scm"),
        )),
        "terraform" => Some((
            tree_sitter_hcl::LANGUAGE.into(),
            include_str!("../queries/terraform/tags.scm"),
        )),
        "toml" => Some((
            tree_sitter_toml_ng::LANGUAGE.into(),
            include_str!("../queries/toml/tags.scm"),
        )),
        "yaml" => Some((
            tree_sitter_yaml::LANGUAGE.into(),
            include_str!("../queries/yaml/tags.scm"),
        )),
        "zig" => Some((
            tree_sitter_zig::LANGUAGE.into(),
            include_str!("../queries/zig/tags.scm"),
        )),

        _ => None,
    }
}

/// The compiled queries for a language, built once per process.
///
/// Compiling a query is orders of magnitude dearer than running one, and
/// indexing a repository runs these over every file it walks. A grammar whose
/// bundled query does not compile against the grammar version linked here is a
/// packaging problem rather than a user's file, so that half is dropped and the
/// other still runs.
fn queries(lang: &'static str, language: &Language, tags: &str) -> &'static [Query] {
    static CACHE: std::sync::LazyLock<
        std::sync::Mutex<std::collections::HashMap<&'static str, &'static [Query]>>,
    > = std::sync::LazyLock::new(Default::default);

    let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
    cache.entry(lang).or_insert_with(|| {
        let compiled: Vec<Query> = [tags, supplement(lang)]
            .iter()
            .filter(|source| !source.is_empty())
            .filter_map(|source| Query::new(language, source).ok())
            .collect();
        Box::leak(compiled.into_boxed_slice())
    })
}

/// A definition found in the tree, with the byte range that makes nesting
/// decidable.
struct Def {
    kind: String,
    name: String,
    /// The type a method belongs to where the tree says so outside any class
    /// body: a Rust `impl` or `trait` block, a Go receiver, a C++ out-of-line
    /// `Foo::bar` — which the enclosing-definition rule cannot see, because
    /// none of them is a definition of its own.
    owner: Option<String>,
    /// What a Go method calls its receiver (`t` in `func (t *T) F()`), the
    /// name that plays `self` inside it.
    receiver: Option<String>,
    start: usize,
    end: usize,
    start_line: u32,
    end_line: u32,
}

/// The definition kinds a method can be declared inside.
const CLASS_KINDS: &[&str] = &["class", "interface", "object"];

/// A reference found in the tree, with the byte offset that places it inside a
/// definition.
struct Ref {
    name: String,
    kind: &'static str,
    at: usize,
    /// Where the referenced name itself starts. Two captures of one call
    /// agree on it even when they captured different nodes around it.
    name_at: usize,
    line: u32,
    hint: Option<String>,
    /// The call went through a receiver (`x.f()`), so it means a method.
    method: bool,
    /// That receiver is `self`, `this` or `cls`: the enclosing class.
    on_self: bool,
    /// That receiver is `super`: a method, of a class the call does not name.
    on_super: bool,
}

/// The deepest nesting a block grammar is given. tree-sitter-md and
/// tree-sitter-yaml keep a stack of open blocks that their external scanner
/// serialises into tree-sitter's 1024-byte buffer, and past about 260 levels
/// the C `assert` in `ts_parser__external_scanner_serialize` aborts the
/// process — measured 2026-10-14 for nested blockquotes, nested lists, nested
/// block sequences and `- - -` sequences alike. Half that is deeper than any
/// real document nests; a file past it keeps its text and loses only its graph.
pub const MAX_BLOCK_NESTING: usize = 128;

/// Whether a file in a block grammar nests past [`MAX_BLOCK_NESTING`], counted
/// line by line: each `>` and list marker opens a level, and so does every two
/// columns of indentation in front of them.
/// The text a grammar's C scanner is handed, for the grammars whose scanner
/// calls a narrow `<ctype.h>` function on a full Unicode code point.
///
/// tree-sitter-md's block scanner runs `isdigit` on the character after a
/// digit at a list-marker position (`scanner.c:740`), and tree-sitter-bash's on
/// the character after `{` or `..` in a brace expansion (`scanner.c:1158,
/// 1172`). glibc's `isdigit` indexes a table valid for -128..255 with no
/// check, so a code point past U+00FF reads out of bounds and can fault: a
/// 7-byte Markdown file did under the 0.41.0 fuzzers. Such a character, right
/// after a character those scanners test, is replaced with as many `a` bytes as
/// it has, so every byte offset and line stays the original's and names are
/// still read from the original text. Borrowed when nothing needs replacing.
pub fn ctype_safe<'a>(lang: &str, text: &'a str) -> std::borrow::Cow<'a, str> {
    let triggers: fn(char) -> bool = match lang {
        "markdown" => |c| c.is_ascii_digit(),
        "bash" => |c| c.is_ascii_digit() || c == '{' || c == '.',
        _ => return std::borrow::Cow::Borrowed(text),
    };
    let needs = |prev: Option<char>, c: char| (c as u32) > 0xFF && prev.is_some_and(triggers);
    let mut prev = None;
    if !text.chars().any(|c| {
        let hit = needs(prev, c);
        prev = Some(c);
        hit
    }) {
        return std::borrow::Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len());
    let mut prev = None;
    for c in text.chars() {
        if needs(prev, c) {
            out.extend(std::iter::repeat_n('a', c.len_utf8()));
            prev = Some('a');
        } else {
            out.push(c);
            prev = Some(c);
        }
    }
    std::borrow::Cow::Owned(out)
}

pub fn too_nested(lang: &str, text: &str) -> bool {
    if !matches!(lang, "markdown" | "yaml") {
        return false;
    }
    // Debug builds only: lets a test hand the real crashing shapes to the
    // parse worker and watch it, not this cap, keep the process up.
    #[cfg(debug_assertions)]
    if std::env::var_os("SEMLITH_NO_NESTING_CAP").is_some() {
        return false;
    }
    text.lines().any(|line| {
        let (mut depth, mut columns) = (0usize, 0usize);
        let mut chars = line.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                ' ' => columns += 1,
                '\t' => columns += 2,
                '>' => depth += 1,
                '-' | '*' | '+' if chars.peek().is_none_or(|n| *n == ' ' || *n == '\t') => {
                    depth += 1
                }
                // Not the end of the prefix: tree-sitter-md goes on nesting
                // past a NUL or another control character, so a line of 100
                // `>`, NULs, then 128 more aborted the parser while this
                // counted 100 (cargo-fuzz chunk_markdown, 0.41.0).
                c if c.is_control() => {}
                _ => break,
            }
            if depth + columns / 2 > MAX_BLOCK_NESTING {
                return true;
            }
        }
        false
    })
}

/// Symbols and edges for one file.
///
/// `None` when the extension carries no grammar. A file that fails to parse is
/// not an error either: tree-sitter always returns a tree, and a partial parse
/// of a file mid-edit yields the symbols it could read rather than nothing.
pub fn extract(path: &Path, text: &str) -> Result<Option<Extraction>> {
    let Some(lang) = language_of(path) else {
        return Ok(None);
    };
    if too_nested(lang, text) {
        return Ok(None);
    }
    let Some((language, tags)) = grammar(lang) else {
        return Ok(None);
    };

    let mut parser = Parser::new();
    parser.set_language(&language)?;
    // Bounded. A tree-sitter grammar can take superlinear time on input that
    // is valid and pathological — a deeply nested expression, a file of
    // brackets — and this runs inside the store's write lock, so a parser that
    // does not come back is a store nothing else can write to. Two seconds is
    // far more than any real file takes, and expiry means "no graph for this
    // file", which is what an unsupported language already means.
    let deadline = std::time::Instant::now() + PARSE_TIMEOUT;
    let mut expired = |_: &tree_sitter::ParseState| {
        if std::time::Instant::now() >= deadline {
            std::ops::ControlFlow::Break(())
        } else {
            std::ops::ControlFlow::Continue(())
        }
    };
    let options = tree_sitter::ParseOptions::default().progress_callback(&mut expired);
    let parse = ctype_safe(lang, text);
    let parsed =
        parser.parse_with_options(&mut |at, _| &parse.as_bytes()[at..], None, Some(options));
    let Some(tree) = parsed else {
        return Ok(None);
    };

    let mut defs: Vec<Def> = Vec::new();
    let mut refs: Vec<Ref> = Vec::new();

    // Rust's field types, read once per file, so a receiver such as
    // `self.members[i].store` can name the type its method belongs to.
    let rust = (lang == "rust").then(|| RustFields::of(tree.root_node(), text));
    for query in queries(lang, &language, tags) {
        collect(query, &tree, text, rust.as_ref(), &mut defs, &mut refs);
    }
    // Markdown's sections come from the one heading scanner the chunker cuts
    // with, which reads setext headings as well as ATX ones.
    if lang == "markdown" {
        defs.retain(|d| d.kind != "heading");
        defs.extend(markdown_sections(text));
    }

    // The bundled query and the supplement can capture one item twice — and
    // within the bundled query a method is often both `definition.method` and
    // `definition.function`. Two Defs over one range make each the other's
    // innermost enclosing definition, which is how a symbol ends up containing
    // itself.
    defs.sort_by(|a, b| {
        (a.start, std::cmp::Reverse(a.end), &a.name).cmp(&(
            b.start,
            std::cmp::Reverse(b.end),
            &b.name,
        ))
    });
    defs.dedup_by(|a, b| a.start == b.start && a.end == b.end && a.name == b.name);

    // Two queries can tag the same definition at two widths: a bundled query
    // that tags the declarator and a supplement that tags the whole definition
    // are both right about where the symbol is and disagree about where it
    // ends. The wider one is the useful one, because a reference inside the
    // body is only attributed to the symbol whose range covers it — C attributed
    // every call in a function body to the file until this rule existed.
    //
    // Same name *and* same kind is the condition, so a `mod x` containing an
    // `fn x`, or a Java class containing its own constructor, keeps both.
    let contained = contained(&defs);
    let mut keep = contained.iter();
    defs.retain(|_| !keep.next().copied().unwrap_or(false));

    let module = module_name(path);
    let mut symbols = vec![Symbol {
        kind: "module".to_string(),
        name: module.clone(),
        qualified: path.to_string_lossy().to_string(),
        start_line: 1,
        end_line: text.lines().count().max(1) as u32,
    }];
    // Each edge with the definition it leaves from, so two definitions of
    // one name in a file (`A::new` and `B::new`) each keep their calls.
    let mut edges: Vec<(Option<usize>, Edge)> = Vec::new();

    let parents = enclosing_each(&defs);
    // A function declared in a class body is a method of it. Kotlin, Python
    // and C++ grammars tag both as functions, and a member then read the same
    // as a top-level function the file's module name happens to qualify
    // (`A::helper` in A.kt), so the resolver could not tell them apart.
    for i in 0..defs.len() {
        let in_class = parents[i].is_some_and(|p| CLASS_KINDS.contains(&defs[p].kind.as_str()));
        if defs[i].kind == "function" && in_class {
            defs[i].kind = "method".to_string();
        }
    }
    for (i, def) in defs.iter().enumerate() {
        let parent = parents[i].map(|p| defs[p].name.clone());
        // The owner outranks the enclosing definition: `Fleet::search_preferring`
        // is what the code calls it and what a qualified question asks for,
        // and `fleet::search_preferring` could be either of two methods.
        let qualified = match (&def.owner, &parent) {
            (Some(owner), _) => format!("{owner}::{}", def.name),
            (None, Some(p)) => format!("{p}::{}", def.name),
            (None, None) => format!("{module}::{}", def.name),
        };
        symbols.push(Symbol {
            kind: def.kind.clone(),
            name: def.name.clone(),
            qualified,
            start_line: def.start_line,
            end_line: def.end_line,
        });
        // Structural edges are read straight off the tree, so both are
        // extracted: a definition is either nested in another or it is not.
        // A self-edge is possible and meaningless: `A.java` takes `A` as its
        // module name and then declares `class A`.
        if parent.as_deref().unwrap_or(&module) == def.name {
            continue;
        }
        match parent {
            Some(p) => edges.push((
                parents[i],
                Edge {
                    from: p,
                    to: def.name.clone(),
                    kind: "contains".to_string(),
                    confidence: EXTRACTED.to_string(),
                    hint: None,
                    // A structural edge has no call site, so it carries the line
                    // the definition itself starts on rather than nothing: that is
                    // where the source says the containment happens.
                    line: Some(def.start_line),
                    from_module: false,
                },
            )),
            None => edges.push((
                None,
                Edge {
                    from: module.clone(),
                    to: def.name.clone(),
                    kind: "defines".to_string(),
                    confidence: EXTRACTED.to_string(),
                    hint: None,
                    line: Some(def.start_line),
                    from_module: true,
                },
            )),
        }
    }

    // The names this file imports. A call to one of them was resolved by the
    // file itself rather than guessed at, which is the line between extracted
    // and inferred for a reference.
    let imported: Vec<String> = refs
        .iter()
        .filter(|r| r.kind == "imports")
        .flat_map(|r| import_names(&r.name))
        .collect();

    // The class a definition sits in: the Rust `impl` the extractor read, or
    // the nearest enclosing definition of a class kind for everything else.
    // What `self`, `this` and `cls` are, and what makes a call recursion.
    let class_of = |at: Option<usize>| -> Option<String> {
        let mut at = at;
        if let Some(owner) = at.and_then(|i| defs[i].owner.clone()) {
            return Some(owner);
        }
        // Bounded: two definitions over one range are each other's parent,
        // and a cycle there hung the whole file (cobra completions.go).
        for _ in 0..defs.len() {
            let i = at?;
            if CLASS_KINDS.contains(&defs[i].kind.as_str()) {
                return Some(defs[i].name.clone());
            }
            at = parents[i];
        }
        None
    };

    // The class definition a reference sits in, by index: the nearest
    // enclosing definition of a class kind.
    let class_at = |at: Option<usize>| -> Option<usize> {
        let mut at = at;
        for _ in 0..defs.len() {
            let i = at?;
            if CLASS_KINDS.contains(&defs[i].kind.as_str()) {
                return Some(i);
            }
            at = parents[i];
        }
        None
    };
    // A bare call to a name the enclosing class itself defines means that
    // member: inside a class body where a bare `helper()` is `this.helper()`
    // (Java, Kotlin, C#, C++, Swift and the rest of `implicit_receiver`), and
    // in a Python class body itself, where `x = deco(1)` reads the class's
    // own namespace — though never from inside a Python method, where it
    // reads the module's.
    let member = |holder: Option<usize>, name: &str| -> Option<String> {
        let class = if implicit_receiver(lang) {
            class_at(holder)?
        } else if lang == "python" {
            holder.filter(|h| CLASS_KINDS.contains(&defs[*h].kind.as_str()))?
        } else {
            return None;
        };
        (0..defs.len())
            .any(|j| parents[j] == Some(class) && defs[j].name == name && j != class)
            .then(|| defs[class].name.clone())
    };

    // Where each call through a receiver names its target. The bundled query
    // captures `self.go()` a second time with no receiver, and that copy must
    // not read as a bare call; `go(x.go())` still has one.
    let through: std::collections::HashSet<usize> = refs
        .iter()
        .filter(|r| r.method || r.on_self)
        .map(|r| r.name_at)
        .collect();
    let holders = innermost_at(&defs, refs.iter().map(|r| r.at), None);
    for (reference, holder) in refs.iter().zip(holders) {
        let enclosing = holder.map(|h| &defs[h]);
        let from = match enclosing {
            Some(def) => def.name.clone(),
            None => module.clone(),
        };
        let owner = class_of(holder);
        // Go names its receiver instead of calling it `self`: `t.F()` inside
        // `func (t *T) G()` goes through the method's own receiver.
        let go_self = lang == "go"
            && reference
                .hint
                .as_ref()
                .is_some_and(|h| enclosing.and_then(|d| d.receiver.as_ref()) == Some(h));
        let on_self = reference.on_self || go_self;
        let member = match (&reference.hint, on_self, reference.kind) {
            (None, false, "calls") => member(holder, &reference.name),
            _ => None,
        };
        // A receiver is what the call went through: its type where the
        // source states it, `self`'s class, or the receiver's own name. A
        // Python object the file imported as a module (`import json` then
        // `json.loads()`) is a module path, not a receiver.
        let lead = match (&reference.hint, on_self) {
            (_, true) if go_self => owner.clone(),
            (Some(h), _) => Some(h.clone()),
            (None, true) => owner.clone(),
            (None, false) => member.clone(),
        };
        // `this.close()` goes through a receiver; JavaScript and TypeScript
        // capture it as a hint, which drops `this`, and it read as bare.
        let this_call = (on_self || reference.on_super)
            && matches!(lang, "javascript" | "typescript" | "svelte" | "vue");
        let method = (reference.method || go_self || this_call)
            && !(lang == "python"
                && !reference.on_self
                && lead.as_ref().is_some_and(|l| {
                    imported.contains(l) || defs.iter().any(|d| d.kind == "alias" && d.name == *l)
                }));
        // Direct recursion adds a self-edge and no information. A call to the
        // same name through anything but the caller's own class is not
        // recursion: `Fleet::search_preferring` calling
        // `store.search_preferring()`, or helpers.py's `make_response` calling
        // `current_app.make_response(args)` (2026-10-14 audit, G2). Nor is a
        // bare call inside a method where no implicit receiver exists:
        // `fn lane(&self, id) { lane(id) }` in an `impl` calls the free fn.
        let in_method = owner.is_some() || enclosing.is_some_and(|d| d.kind == "method");
        let recursion = from == reference.name
            && match &lead {
                None => {
                    method
                        || through.contains(&reference.name_at)
                        || !(in_method && no_implicit_receiver(lang))
                }
                Some(l) => owner.as_ref() == Some(l) || (!method && l == "Self"),
            };
        if recursion {
            continue;
        }
        // The file said where this came from, one way or the other: it
        // imported the name itself (`use ...::edges_out;` then `edges_out()`),
        // or it imported the thing the call went through (`use ...::store;`
        // then `store::edges_out()`, or `use ...::HiArgs;` then a method on an
        // `&HiArgs`). The second is exactly as determined as the first — the
        // module the call names is in the file's own imports — and reading it
        // as inferred is what left Rust at 2% extracted while the source was
        // perfectly explicit.
        let named_by_file = reference.kind == "imports"
            || imported.contains(&reference.name)
            || lead.as_ref().is_some_and(|h| imported.contains(h));
        let confidence = if named_by_file { EXTRACTED } else { INFERRED };
        // A method call's hint carries a leading `.`, so the resolver knows the
        // call went through a receiver and can never mean a free function.
        let hint = if method {
            Some(format!("{RECEIVER}{}", lead.unwrap_or_default()))
        } else {
            reference.hint.clone().or(member)
        };
        edges.push((
            holder,
            Edge {
                from,
                to: reference.name.clone(),
                kind: reference.kind.to_string(),
                confidence: confidence.to_string(),
                hint,
                line: Some(reference.line),
                from_module: enclosing.is_none(),
            },
        ));
    }

    // One call can be captured by both the bundled query and the supplement,
    // and only the supplement carries a hint. Deduplicating on the triple
    // alone would keep whichever landed first; ordering by confidence and then
    // by whether a hint is present makes the best-informed copy of each edge
    // the one that survives.
    edges.sort_by(|(x, a), (y, b)| {
        (
            &a.from,
            x,
            &a.to,
            &a.kind,
            a.from_module,
            confidence_rank(&a.confidence),
            a.hint.is_none(),
            &a.hint,
            a.line.is_none(),
            a.line,
        )
            .cmp(&(
                &b.from,
                y,
                &b.to,
                &b.kind,
                b.from_module,
                confidence_rank(&b.confidence),
                b.hint.is_none(),
                &b.hint,
                b.line.is_none(),
                b.line,
            ))
    });
    edges.dedup_by(|(x, a), (y, b)| {
        (&a.from, x, &a.to, &a.kind, a.from_module) == (&b.from, y, &b.to, &b.kind, b.from_module)
    });
    let edges = edges.into_iter().map(|(_, e)| e).collect();

    Ok(Some(Extraction { symbols, edges }))
}

fn collect(
    query: &Query,
    tree: &tree_sitter::Tree,
    text: &str,
    rust: Option<&RustFields>,
    defs: &mut Vec<Def>,
    refs: &mut Vec<Ref>,
) {
    let names = query.capture_names();
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), text.as_bytes());
    while let Some(m) = matches.next() {
        // A tags query names its tag with `@name` and spans it with
        // `@definition.X` or `@reference.X`, and the two are separate captures
        // of the same match. Java is the clearest case: `@reference.call` lands
        // on the argument list `()` and the method's identifier arrives beside
        // it as `@name`. So the match is read as a whole, not capture by
        // capture.
        let mut span: Option<(&str, tree_sitter::Node)> = None;
        let mut name: Option<tree_sitter::Node> = None;
        let mut hint: Option<tree_sitter::Node> = None;
        let mut method = false;
        let mut references: Vec<(&str, tree_sitter::Node)> = Vec::new();
        for capture in m.captures() {
            let capture_name = names[capture.index as usize];
            if let Some(kind) = capture_name.strip_prefix("definition.") {
                span = Some((kind, capture.node));
            } else if capture_name == "name" {
                name = Some(capture.node);
            } else if capture_name == "hint" {
                hint = Some(capture.node);
            } else if capture_name == "receiver" {
                hint = Some(capture.node);
                method = true;
            } else if let Some(kind) = capture_name.strip_prefix("reference.") {
                references.push((kind, capture.node));
            }
        }

        for (kind, node) in references {
            let kind = match kind {
                "call" => "calls",
                "import" => "imports",
                "alias" => "aliases",
                _ => "references",
            };
            // An import is a literal path and is kept whole. Anything else
            // takes the match's `@name` when it has one, and otherwise
            // descends into whatever node the grammar chose to capture —
            // Rust's query hands back `helper()` for a call and an entire
            // `impl` block for an implementation.
            let target = if kind == "imports" {
                Some(trim_literal(&text[node.byte_range()]).to_string())
            } else if kind == "aliases" {
                // The captured node is the path the alias stands for, and
                // `edges.dst` is a bare name, so `store::Semlith` has to become
                // `Semlith` before it can resolve against anything. `@name`
                // here is the alias, not the target, which is why this does not
                // fall through to the branch below.
                last_segment(&text[node.byte_range()])
            } else {
                match name {
                    Some(n) => Some(text[n.byte_range()].to_string()),
                    None => reference_name(node, text),
                }
            };
            let Some(target) = target.filter(|t| !t.is_empty()) else {
                continue;
            };
            if node.kind() == "token_tree" && !macro_argument_call(node, name) {
                continue;
            }
            // A macro invocation is recorded under the name the source writes.
            //
            // `format!(...)` is a reference to the macro `format!`, not a call
            // to a function called `format`, and the two are different names.
            // Conflating them made every function that formats a string look
            // like a caller of `store::format`: 229 of them on semlith's own
            // store, against three real ones. The grammar's tags query cannot
            // tell them apart because it captures the identifier without its
            // `!`, so the distinction is restored here.
            let target = if in_macro(node) {
                format!("{target}!")
            } else {
                target
            };
            refs.push(Ref {
                name: target,
                kind,
                at: node.start_byte(),
                name_at: name.map_or(node.start_byte(), |n| n.start_byte()),
                line: node.start_position().row as u32 + 1,
                // A receiver whose type the source states is a better lead
                // than its variable name: `store.search_preferring()` names a
                // file that defines no such method, and `Semlith` names the
                // one that does.
                hint: hint.and_then(|h| {
                    rust.and_then(|fields| receiver_type(h, text, fields))
                        .or_else(|| rust.and_then(|_| token_variant_owner(h, text)))
                        .or_else(|| hint_text(h, text))
                }),
                method,
                on_self: hint
                    .is_some_and(|h| matches!(&text[h.byte_range()], "self" | "this" | "cls")),
                on_super: hint.is_some_and(|h| &text[h.byte_range()] == "super"),
            });
        }

        if let (Some((kind, node)), Some(name)) = (span, name) {
            // An alias is the clause that names it, and its name sits at the
            // clause's very end: climbing from there reached Python's whole
            // `module`, so `BaseResponse` spanned app.py and owned every class
            // in it (2026-10-14 audit, G4 and G5).
            let span = if kind == "alias" {
                node
            } else {
                definition_span(node, name)
            };
            let raw = &text[name.byte_range()];
            let scope = scope_owner(name, text);
            let go = go_receiver(span, text);
            let owner = match rust {
                Some(_) => rust_owner(span, text),
                None => go.as_ref().map(|(ty, _)| ty.clone()).or(scope.clone()),
            };
            // `void ns::helper() {}` is a namespace's function, which the
            // grammar tags as a method because of its qualified name; so is a
            // Rust `fn` in a `mod tests { }` body, which the grammar shapes
            // like an `impl`'s.
            // ponytail: case decides type vs namespace (`Foo::` vs `ns::`), the
            // convention nearly every C++ codebase keeps; a lower-case class
            // defined out of line reads as a namespace function.
            let namespace = match &scope {
                Some(s) => !s.starts_with(char::is_uppercase),
                None => rust.is_some() && owner.is_none(),
            };
            let kind = if kind == "method" && namespace {
                "function"
            } else {
                kind
            };
            defs.push(Def {
                kind: kind.to_string(),
                name: if kind == "heading" {
                    crate::chunk::heading_title(raw)
                } else {
                    raw.to_string()
                },
                owner,
                receiver: go.and_then(|(_, name)| name),
                start: span.start_byte(),
                end: span.end_byte(),
                start_line: span.start_position().row as u32 + 1,
                end_line: span.end_position().row as u32 + 1,
            });
        }
    }
}

/// Each Markdown heading as a definition spanning its section: from its own
/// line to the line before the next heading at its depth or above, or the
/// file's last line.
fn markdown_sections(text: &str) -> Vec<Def> {
    let mut starts = vec![0usize];
    starts.extend(text.match_indices('\n').map(|(i, _)| i + 1));
    let lines = text.lines().count();
    let byte = |line: usize| starts.get(line).copied().unwrap_or(text.len());
    let found = crate::chunk::headings(text);
    found
        .iter()
        .enumerate()
        .map(|(i, h)| {
            let next = found[i + 1..]
                .iter()
                .find(|n| n.level <= h.level)
                .map_or(lines + 1, |n| n.line as usize);
            let end_line = (next - 1).max(h.line as usize);
            Def {
                kind: "heading".to_string(),
                name: h.title.clone(),
                owner: None,
                receiver: None,
                start: byte(h.line as usize - 1),
                end: byte(end_line)
                    .saturating_sub(1)
                    .max(byte(h.line as usize - 1) + 1),
                start_line: h.line,
                end_line: end_line as u32,
            }
        })
        .collect()
}

/// A Rust type as far as a method call needs it: its name, and for a
/// container (`Vec<T>`, `Option<T>`, `[T]`) the element a `[i]` or a `for`
/// hands out.
#[derive(Debug, Clone, PartialEq)]
struct Ty {
    name: String,
    elem: Option<String>,
}

/// Standard containers and values: a receiver of one of these is not a
/// type in the corpus, so the variable's name stays the better lead.
const STD_TYPES: [&str; 14] = [
    "Vec", "VecDeque", "Option", "Result", "String", "str", "HashMap", "BTreeMap", "HashSet",
    "BTreeSet", "Path", "PathBuf", "[]", "Self",
];

/// The declared type of every struct field in one Rust file: by owner and
/// field, and by field name alone for a receiver whose owner is unknown.
///
/// A field name declared with two different types in one file maps to
/// nothing by name — `store: Semlith` beside `store: String` — and is then
/// answered only through its owner: `self.members[i].store` is `Member`'s.
struct RustFields {
    by_owner: std::collections::HashMap<(String, String), Ty>,
    by_name: std::collections::HashMap<String, Option<Ty>>,
}

impl RustFields {
    fn of(root: tree_sitter::Node, text: &str) -> RustFields {
        let mut out = RustFields {
            by_owner: Default::default(),
            by_name: Default::default(),
        };
        let mut cursor = root.walk();
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            if node.kind() == "field_declaration" {
                let owner = node
                    .parent()
                    .and_then(|list| list.parent())
                    .filter(|item| item.kind() == "struct_item")
                    .and_then(|item| item.child_by_field_name("name"))
                    .map(|n| text[n.byte_range()].to_string());
                let name = node.child_by_field_name("name");
                let ty = node
                    .child_by_field_name("type")
                    .and_then(|t| rust_ty(t, text));
                if let (Some(name), Some(ty)) = (name, ty) {
                    let field = text[name.byte_range()].to_string();
                    if let Some(owner) = owner {
                        out.by_owner.insert((owner, field.clone()), ty.clone());
                    }
                    let entry = out.by_name.entry(field).or_insert_with(|| Some(ty.clone()));
                    if entry.as_ref() != Some(&ty) {
                        *entry = None;
                    }
                }
                continue;
            }
            stack.extend(node.named_children(&mut cursor));
        }
        out
    }
}

/// The type a Go method's receiver names, and the receiver's own name: `T`
/// and `t` for `func (t *T) F()` and for `func (t T[K]) F()`. Without it a method was qualified by its package
/// (`a::F`), and no type the source states could ever select it.
fn go_receiver(node: tree_sitter::Node, text: &str) -> Option<(String, Option<String>)> {
    let receiver = node.child_by_field_name("receiver")?;
    let mut cursor = receiver.walk();
    let parameter = receiver
        .named_children(&mut cursor)
        .find(|c| c.kind() == "parameter_declaration")?;
    let ty = &text[parameter.child_by_field_name("type")?.byte_range()];
    let ty = ty.trim_start_matches('*');
    let ty = ty.split('[').next().unwrap_or(ty).trim();
    let name = parameter
        .child_by_field_name("name")
        .map(|n| text[n.byte_range()].to_string());
    (!ty.is_empty()).then(|| (ty.to_string(), name))
}

/// The class or namespace a C++ out-of-line definition names before its own
/// name: `Foo` for `void Foo::bar()`, `ns` for `void a::ns::helper()`.
fn scope_owner(name: tree_sitter::Node, text: &str) -> Option<String> {
    let parent = name
        .parent()
        .filter(|p| p.kind() == "qualified_identifier")?;
    let scope = &text[parent.child_by_field_name("scope")?.byte_range()];
    let last = scope.rsplit("::").next().unwrap_or(scope);
    let last = last.split('<').next().unwrap_or(last).trim();
    (!last.is_empty()).then(|| last.to_string())
}

/// The type a Rust definition is a member of: the nearest `impl` or `trait`
/// block around it. A function nested inside another function, or a module in
/// between, belongs to neither. An `impl Trait for Box<dyn Error>`, whose type
/// names nothing, is the trait's.
fn rust_owner(node: tree_sitter::Node, text: &str) -> Option<String> {
    let mut at = node.parent();
    while let Some(n) = at {
        match n.kind() {
            "impl_item" => {
                return n
                    .child_by_field_name("type")
                    .and_then(|t| rust_type_name(t, text))
                    .or_else(|| rust_type_name(n.child_by_field_name("trait")?, text));
            }
            "trait_item" => {
                return n
                    .child_by_field_name("name")
                    .map(|t| text[t.byte_range()].to_string());
            }
            "function_item" | "mod_item" | "closure_expression" => return None,
            _ => {}
        }
        at = n.parent();
    }
    None
}

/// The type a type node names, through references and the smart pointers a
/// method call sees through: `&mut Fleet`, `Arc<Mutex<Fleet>>` and
/// `crate::fleet::Fleet` all name `Fleet`.
fn rust_type_name(node: tree_sitter::Node, text: &str) -> Option<String> {
    rust_ty(node, text).map(|t| t.name)
}

/// [`rust_type_name`], keeping a container's element.
fn rust_ty(node: tree_sitter::Node, text: &str) -> Option<Ty> {
    const THROUGH: [&str; 7] = ["Box", "Rc", "Arc", "RefCell", "Mutex", "RwLock", "Cell"];
    let plain = |name: String| Some(Ty { name, elem: None });
    match node.kind() {
        "type_identifier" | "primitive_type" => plain(text[node.byte_range()].to_string()),
        "reference_type" | "pointer_type" => rust_ty(node.child_by_field_name("type")?, text),
        "scoped_type_identifier" => rust_ty(node.child_by_field_name("name")?, text),
        "array_type" => Some(Ty {
            name: "[]".to_string(),
            elem: node
                .child_by_field_name("element")
                .and_then(|e| rust_type_name(e, text)),
        }),
        "generic_type" => {
            let base = rust_type_name(node.child_by_field_name("type")?, text)?;
            let first = node.child_by_field_name("type_arguments").and_then(|args| {
                let mut cursor = args.walk();
                args.named_children(&mut cursor).next()
            });
            if THROUGH.contains(&base.as_str()) {
                return rust_ty(first?, text);
            }
            Some(Ty {
                name: base,
                elem: first.and_then(|f| rust_type_name(f, text)),
            })
        }
        _ => None,
    }
}

/// The type of a Rust method call's receiver, where the source states it.
///
/// `self` inside an `impl T` block; a parameter, `let` or `for` binding whose
/// type is declared or constructed (`x: T`, `T::new()`, `T::open(…)?`,
/// `T { … }`, `for x in &self.items`); and a field, through its owner's
/// declared type when the chain says whose field it is (`self.members[i].store`
/// is `Member.store`), or by its name when only one type in the file declares
/// it. A standard container is not a lead, so `None` and the receiver's own
/// name stays the hint, as it was before 0.30.0.
fn receiver_type(receiver: tree_sitter::Node, text: &str, fields: &RustFields) -> Option<String> {
    expr_ty(receiver, text, fields, 0)
        .map(|t| t.name)
        .filter(|name| !STD_TYPES.contains(&name.as_str()))
}

/// [`expr_ty`]'s enum variant rule for a receiver inside a macro's arguments,
/// where the tree holds tokens rather than a path: `Kind :: Catchup` before
/// `.lane()` in `assert_eq!(Kind::Catchup.lane(), 1)` names `Kind`.
fn token_variant_owner(variant: tree_sitter::Node, text: &str) -> Option<String> {
    let upper = |s: &str| s.starts_with(char::is_uppercase);
    if !upper(&text[variant.byte_range()]) {
        return None;
    }
    let separator = variant
        .prev_sibling()
        .filter(|s| &text[s.byte_range()] == "::")?;
    let owner = &text[separator.prev_sibling()?.byte_range()];
    if !upper(owner) {
        return None;
    }
    if owner != "Self" {
        return Some(owner.to_string());
    }
    let mut at = variant.parent();
    while let Some(n) = at {
        if n.kind() == "function_item" {
            return rust_owner(n, text);
        }
        at = n.parent();
    }
    None
}

/// The type an expression evaluates to, where the source states it.
fn expr_ty(node: tree_sitter::Node, text: &str, fields: &RustFields, depth: u8) -> Option<Ty> {
    if depth > 8 {
        return None;
    }
    match node.kind() {
        "self" => {
            let mut at = node.parent();
            while let Some(n) = at {
                if n.kind() == "function_item" {
                    return rust_owner(n, text).map(|name| Ty { name, elem: None });
                }
                at = n.parent();
            }
            None
        }
        "identifier" => binding_ty(node, text, fields, depth),
        "field_expression" => {
            let field = text[node.child_by_field_name("field")?.byte_range()].to_string();
            let owner = node
                .child_by_field_name("value")
                .and_then(|v| expr_ty(v, text, fields, depth + 1));
            if let Some(owner) = owner
                && let Some(ty) = fields.by_owner.get(&(owner.name, field.clone()))
            {
                return Some(ty.clone());
            }
            fields.by_name.get(&field).cloned().flatten()
        }
        "index_expression" => {
            let container = expr_ty(node.named_child(0)?, text, fields, depth + 1)?;
            container.elem.map(|name| Ty { name, elem: None })
        }
        "reference_expression" | "parenthesized_expression" | "try_expression" => {
            let inner = node
                .child_by_field_name("value")
                .or_else(|| node.named_child(0))?;
            expr_ty(inner, text, fields, depth + 1)
        }
        // An enum variant is a value of its enum: `Kind::Catchup.lane()`
        // calls `Kind::lane`, and `Self::Catchup` is the `impl`'s type.
        "scoped_identifier" => {
            let variant = &text[node.child_by_field_name("name")?.byte_range()];
            let path = &text[node.child_by_field_name("path")?.byte_range()];
            let owner = path.rsplit("::").next().unwrap_or(path);
            if !variant.starts_with(char::is_uppercase) || !owner.starts_with(char::is_uppercase) {
                return None;
            }
            if owner != "Self" {
                return Some(Ty {
                    name: owner.to_string(),
                    elem: None,
                });
            }
            let mut at = node.parent();
            while let Some(n) = at {
                if n.kind() == "function_item" {
                    return rust_owner(n, text).map(|name| Ty { name, elem: None });
                }
                at = n.parent();
            }
            None
        }
        _ => None,
    }
}

/// The declared or constructed type of a local named by `ident`: the last
/// parameter, `let` or `for` binding of that name in the enclosing function
/// that comes before the use.
fn binding_ty(ident: tree_sitter::Node, text: &str, fields: &RustFields, depth: u8) -> Option<Ty> {
    let name = &text[ident.byte_range()];
    let mut function = ident.parent();
    while let Some(f) = function {
        if f.kind() == "function_item" {
            break;
        }
        function = f.parent();
    }
    let function = function?;
    // ponytail: walks the whole enclosing function per method call; a
    // per-function binding table if a pathological file ever shows up in
    // the indexing profile.
    let mut found: Option<(usize, Ty)> = None;
    let mut cursor = function.walk();
    let mut stack = vec![function];
    while let Some(node) = stack.pop() {
        if node.start_byte() >= ident.start_byte() {
            continue;
        }
        let names_it = |field: &str| {
            node.child_by_field_name(field)
                .is_some_and(|p| p.kind() == "identifier" && &text[p.byte_range()] == name)
        };
        let ty = match node.kind() {
            "parameter" | "let_declaration" if names_it("pattern") => node
                .child_by_field_name("type")
                .and_then(|t| rust_ty(t, text))
                .or_else(|| {
                    node.child_by_field_name("value")
                        .and_then(|v| constructed_type(v, text))
                        .map(|name| Ty { name, elem: None })
                }),
            // `for x in &self.items`: the element of what is iterated.
            "for_expression" if names_it("pattern") => node
                .child_by_field_name("value")
                .and_then(|v| expr_ty(v, text, fields, depth + 1))
                .and_then(|t| t.elem)
                .map(|name| Ty { name, elem: None }),
            _ => None,
        };
        if let Some(ty) = ty
            && found.as_ref().is_none_or(|(at, _)| node.start_byte() > *at)
        {
            found = Some((node.start_byte(), ty));
        }
        stack.extend(node.named_children(&mut cursor));
    }
    found.map(|(_, ty)| ty)
}

/// `T::new()`, `T::open(…)?`, `T::load(…).unwrap()` and `T { … }` construct a
/// `T`. The upper-case check keeps `store::open()` — a module's function,
/// whose return type the call does not say — out of it.
fn constructed_type(value: tree_sitter::Node, text: &str) -> Option<String> {
    let upper = |t: &str| t.chars().next().is_some_and(char::is_uppercase);
    match value.kind() {
        "try_expression" => constructed_type(value.named_child(0)?, text),
        "struct_expression" => {
            rust_type_name(value.child_by_field_name("name")?, text).filter(|t| upper(t))
        }
        "call_expression" => {
            let function = value.child_by_field_name("function")?;
            match function.kind() {
                "scoped_identifier" => {
                    let path = function.child_by_field_name("path")?;
                    let ty = match path.kind() {
                        "identifier" | "type_identifier" => text[path.byte_range()].to_string(),
                        "scoped_identifier" => {
                            text[path.child_by_field_name("name")?.byte_range()].to_string()
                        }
                        _ => return None,
                    };
                    upper(&ty).then_some(ty)
                }
                // `T::open(…).unwrap()` and `.expect(…)`: the value is what
                // the call before them produced.
                "field_expression" => {
                    let method = &text[function.child_by_field_name("field")?.byte_range()];
                    if matches!(method, "unwrap" | "expect") {
                        constructed_type(function.child_by_field_name("value")?, text)
                    } else {
                        None
                    }
                }
                _ => None,
            }
        }
        _ => None,
    }
}

/// Whether a captured reference is (or sits directly inside) a macro
/// invocation.
///
/// Only the node itself and its immediate parents are checked, because a
/// grammar captures either the invocation or the identifier naming it, and
/// climbing further would swallow every ordinary call that happens to appear
/// inside a macro's arguments — `format!("{}", helper())` really does call
/// `helper`.
fn in_macro(node: tree_sitter::Node) -> bool {
    const MACRO_KINDS: [&str; 2] = ["macro_invocation", "macro_expression"];
    if MACRO_KINDS.contains(&node.kind()) {
        return true;
    }
    node.parent()
        .is_some_and(|parent| MACRO_KINDS.contains(&parent.kind()))
}

/// Whether a call the Rust supplement read out of a token tree (#244) is a
/// call written in a macro invocation's arguments.
///
/// Two things the query cannot say. The name has to stand directly before the
/// parenthesised tree, with nothing between: a query anchor skips anonymous
/// nodes, so `format!("{}", x)` nested in a `json!` matched as a call to
/// `format`, and a macro name is not a call edge. And the token tree has to
/// belong to a macro invocation: an attribute's arguments are token trees too,
/// and `#[cfg(not(test))]` calls nothing named `not`, nor does a `macro_rules!`
/// body call anything until it is expanded somewhere.
fn macro_argument_call(args: tree_sitter::Node, name: Option<tree_sitter::Node>) -> bool {
    if name.is_none() || args.prev_sibling() != name {
        return false;
    }
    let mut up = args.parent();
    while let Some(node) = up {
        if node.kind() != "token_tree" {
            return node.kind() == "macro_invocation";
        }
        up = node.parent();
    }
    false
}

/// The lead a `@hint` capture carries, or `None` when it carries none worth
/// storing.
///
/// The capture is whatever stood to the left of the call — `store`, `self`,
/// `self.index`, `crate::store`, `this.client` — so it is reduced to its last
/// identifier the same way a reference is. Three of them are dropped rather
/// than stored: `self`, `this` and `super` name the file the call is already
/// in, so they rank nothing, and `crate` names the whole tree.
fn hint_text(node: tree_sitter::Node, text: &str) -> Option<String> {
    const USELESS: [&str; 5] = ["self", "this", "super", "crate", "cls"];
    let name = reference_name(node, text)?;
    if name.is_empty() || USELESS.contains(&name.as_str()) {
        return None;
    }
    Some(name)
}

/// The identifier an edge should point at, out of whatever node the query
/// captured.
///
/// Grammars disagree about this. Some capture the bare identifier, some the
/// whole call expression, some an entire `impl` block. Descending to the name
/// makes all of them agree, and a capture with no identifier in it at all is
/// dropped rather than stored as a wall of source text.
fn reference_name(node: tree_sitter::Node, text: &str) -> Option<String> {
    if let Some(function) = node.child_by_field_name("function") {
        return reference_name(function, text);
    }
    if let Some(property) = node.child_by_field_name("property") {
        return reference_name(property, text);
    }
    let kind = node.kind();
    if kind.ends_with("identifier") || kind == "type_identifier" || kind == "word" {
        return Some(text[node.byte_range()].to_string());
    }
    if let Some(name) = node.child_by_field_name("name") {
        return reference_name(name, text);
    }
    // A path or qualified name: the last identifier in it is the thing named.
    let mut cursor = node.walk();
    let last = node
        .named_children(&mut cursor)
        .filter(|c| c.kind().ends_with("identifier"))
        .last();
    match last {
        Some(child) => Some(text[child.byte_range()].to_string()),
        None if node.child_count() == 0 => Some(text[node.byte_range()].to_string()),
        None => None,
    }
}

/// The byte range a definition owns, which is what decides what is nested
/// inside it.
///
/// A grammar that captures its definition on the declaration node gives this
/// directly. TypeScript's tags query does not — it captures a node that stops
/// short of the body, so every call inside a function would look like it sat
/// at the top level of the file. Climbing from the name to the nearest
/// declaration-shaped ancestor recovers the real extent.
fn definition_span<'a>(
    captured: tree_sitter::Node<'a>,
    name: tree_sitter::Node<'a>,
) -> tree_sitter::Node<'a> {
    if captured.start_byte() <= name.start_byte() && captured.end_byte() > name.end_byte() {
        return captured;
    }
    let mut best = captured;
    let mut node = name;
    // The root is the file, never one definition's extent — Python's is called
    // `module`, which reads as declaration-shaped.
    while let Some(parent) = node.parent().filter(|p| p.parent().is_some()) {
        if declaration_shaped(parent.kind()) && parent.end_byte() > best.end_byte() {
            best = parent;
        }
        node = parent;
    }
    best
}

fn declaration_shaped(kind: &str) -> bool {
    const MARKERS: [&str; 10] = [
        "declaration",
        "definition",
        "_item",
        "specifier",
        "class",
        "function",
        "method",
        "struct",
        "interface",
        "module",
    ];
    MARKERS.iter().any(|m| kind.contains(m))
}

// The three passes below answered by comparing every definition with every
// other one, and every reference with every definition: a planted file of
// 450,000 one-line functions was some 10^11 comparisons (audit S18). They are
// sweeps now, with the same answers — `graph::tests` checks them against the
// pairwise versions.

/// For each definition, whether another one of the same name and kind covers
/// it with a different range.
fn contained(defs: &[Def]) -> Vec<bool> {
    let mut out = vec![false; defs.len()];
    let mut groups: std::collections::HashMap<(&str, &str), Vec<usize>> =
        std::collections::HashMap::new();
    for (i, d) in defs.iter().enumerate() {
        groups.entry((&d.name, &d.kind)).or_default().push(i);
    }
    for mut group in groups.into_values() {
        // By start, widest first: whatever could cover a definition sorts
        // before it.
        group.sort_by_key(|&i| (defs[i].start, std::cmp::Reverse(defs[i].end)));
        let mut widest: Option<usize> = None;
        let mut run = 0;
        while run < group.len() {
            let range = (defs[group[run]].start, defs[group[run]].end);
            let mut next = run;
            while next < group.len() && (defs[group[next]].start, defs[group[next]].end) == range {
                next += 1;
            }
            // Only what sorted before this run: a definition with an equal
            // range is the same definition tagged twice, not a cover.
            let covered = widest.is_some_and(|end| end >= range.1);
            for &i in &group[run..next] {
                out[i] = covered;
            }
            widest = Some(widest.map_or(range.1, |end| end.max(range.1)));
            run = next;
        }
    }
    out
}

/// For each position in `at`, the innermost definition whose range holds it:
/// the narrowest, the earliest of equals, skipping `not` for the position at
/// the same index when given. One sweep over the positions in order, holding
/// the definitions open at each by width.
fn innermost_at(
    defs: &[Def],
    at: impl Iterator<Item = usize>,
    not: Option<&dyn Fn(usize) -> usize>,
) -> Vec<Option<usize>> {
    use std::cmp::Reverse;
    use std::collections::{BTreeSet, BinaryHeap};
    let at: Vec<usize> = at.collect();
    let mut order: Vec<usize> = (0..at.len()).collect();
    order.sort_by_key(|&q| at[q]);
    let mut by_start: Vec<usize> = (0..defs.len()).collect();
    by_start.sort_by_key(|&i| defs[i].start);
    let mut open: BTreeSet<(usize, usize)> = BTreeSet::new();
    let mut ends: BinaryHeap<Reverse<(usize, usize)>> = BinaryHeap::new();
    let mut next = 0;
    let mut out = vec![None; at.len()];
    for q in order {
        let pos = at[q];
        while next < by_start.len() && defs[by_start[next]].start <= pos {
            let d = &defs[by_start[next]];
            open.insert((d.end - d.start, by_start[next]));
            ends.push(Reverse((d.end, by_start[next])));
            next += 1;
        }
        while let Some(Reverse((end, i))) = ends.peek().copied() {
            if end > pos {
                break;
            }
            ends.pop();
            let d = &defs[i];
            open.remove(&(d.end - d.start, i));
        }
        let skip = not.map(|f| f(q));
        out[q] = open.iter().map(|&(_, i)| i).find(|&i| Some(i) != skip);
    }
    out
}

/// For each definition, the innermost other definition enclosing its start.
fn enclosing_each(defs: &[Def]) -> Vec<Option<usize>> {
    innermost_at(defs, defs.iter().map(|d| d.start), Some(&|q| q))
}

/// A file's own symbol: what top-level definitions hang off and where
/// top-level references come from.
fn module_name(path: &Path) -> String {
    path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("module")
        .to_string()
}

/// An import's text as the names it could resolve a later reference to.
///
/// `use std::fs::File` imports `File`; `import java.util.List` imports `List`;
/// `from a.b import c` names the module. Taking the last segment covers all of
/// them, and the whole string is kept too so an edge to a module path still
/// resolves.
fn import_names(raw: &str) -> Vec<String> {
    let cleaned = trim_literal(raw);
    let mut out = vec![cleaned.to_string()];
    if let Some(last) = cleaned
        .rsplit(['/', '.', ':'])
        .find(|s| !s.is_empty())
        .filter(|s| *s != cleaned)
    {
        out.push(last.to_string());
    }
    out
}

/// The bare name at the end of a path an alias stands for.
///
/// `store::Semlith` is `Semlith`, `"path/filepath"` is `filepath`, `x.y.search`
/// is `search`. `edges.dst` is a name rather than a path, so an alias that kept
/// its path would resolve against nothing.
fn last_segment(raw: &str) -> Option<String> {
    let cleaned = trim_literal(raw);
    cleaned
        .rsplit(['/', '.', ':'])
        .find(|s| !s.is_empty())
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
}

/// Strip the quoting a literal import path arrives wrapped in.
fn trim_literal(raw: &str) -> &str {
    raw.trim()
        .trim_matches(|c| c == '"' || c == '\'' || c == '<' || c == '>')
        .trim()
}

// --------------------------------------------------------------- traversal

/// How many symbols a single traversal will visit before it stops and says so.
///
/// Reverse reachability over a monorepo is unbounded in principle — a utility
/// everything calls reaches everything — and the answer stops being useful long
/// before it stops growing. The budget is what keeps peak memory flat as the
/// corpus grows, which is the property `tests/measure.rs` asserts, and a
/// truncated answer says it was truncated rather than pretending to be whole.
pub const MAX_NODES: usize = 2000;

/// The edge kinds that mean "depends on", which are the only ones a path is
/// about.
///
/// `defines` and `contains` are structural: they say a symbol sits inside a
/// file or another symbol. True, and useless here — every symbol is reached in
/// one hop from the file it lives in, so including them would make a path
/// between two unrelated functions in one file look like a two-hop
/// dependency. Neighbours still show them, because "what is in this" is a
/// question someone asks.
/// `aliases` is here from 0.16.0 for the opposite reason to `defines`: a
/// re-export or an aliased import is the only thing standing between the name
/// a caller wrote and the definition it meant, so a walk that refuses to cross
/// one reports "not connected" about code that is connected. It is a
/// dependency in the sense that matters — following it lands on real code.
pub const DEPENDENCY_KINDS: [&str; 4] = ["calls", "imports", "references", "aliases"];

pub fn dependency_kinds() -> Vec<String> {
    DEPENDENCY_KINDS.iter().map(|k| k.to_string()).collect()
}

/// Symbol kinds nothing can point *at*.
///
/// A Markdown heading, a YAML or TOML or JSON key, a CSS selector and an HTML
/// element are navigational: they are what a document is searched by, and they
/// are worth being symbols for exactly that. Nothing references them. No
/// `calls` edge has ever meant a heading.
///
/// That distinction has to be enforced where an edge's target is resolved,
/// because `edges.dst` is a *name* and resolution is a join on it. Without it,
/// 0.17.0's forty new languages put 1 427 navigational symbols into this
/// repository's own store — 933 configuration keys, 264 CSS selectors, 230
/// headings — and 44 of them collided with the name of a real function:
/// `path`, `query`, `symbol`, `graph`, `shape`, `forget`, `error`, `version`.
/// Every one of those names became *ambiguous*, the walk refuses to cross an
/// ambiguous name, and the harness measured the result: hit@1 13 to 10, hit@8
/// 27 to 23 on an unchanged question set.
///
/// They stay symbols. `semlith symbol` finds them, a locate answer names the
/// heading a hit sits under, and `semlith stats` counts them. They simply
/// cannot be what an edge meant.
pub const NAVIGATIONAL_KINDS: [&str; 4] = ["heading", "key", "selector", "element"];

/// Whether an edge target is the language's own: a builtin (`len`, `print`,
/// `Ok`, `println!`), a call through a standard-library namespace
/// (`fmt.Errorf`, `os.path.join`, `std::mem::take`), or an import of one
/// (`"os"`, `std::io::Write`, `import json`).
///
/// For "Called and not found", which is a list of code the corpus does not
/// hold: cobra's was `Errorf` 198 times, `len`, `append` and `os` (2026-10-14
/// audit, item 30 of 0.42.0). A name this answers yes for is only ever asked
/// about when nothing in the store defines it, so a user function of the same
/// name is never hidden.
///
/// `hint` is the edge's stored hint, receiver mark and all. Covers the
/// languages a corpus is mostly made of — Go, Rust, Python, JavaScript and
/// TypeScript; any other answers no.
// ponytail: curated names, not the full standard libraries; widen a list when
// a gaps report shows a standard name.
pub fn is_builtin(language: &str, name: &str, kind: &str, hint: Option<&str>) -> bool {
    let hint = hint.map(|h| h.trim_start_matches(RECEIVER));
    let list = |names: &[&str], n: &str| names.contains(&n);
    match language {
        "go" => {
            const BUILTINS: &[&str] = &[
                "append",
                "cap",
                "clear",
                "close",
                "complex",
                "copy",
                "delete",
                "imag",
                "len",
                "make",
                "max",
                "min",
                "new",
                "panic",
                "print",
                "println",
                "real",
                "recover",
                "bool",
                "byte",
                "error",
                "float32",
                "float64",
                "int",
                "int8",
                "int16",
                "int32",
                "int64",
                "rune",
                "string",
                "uint",
                "uint8",
                "uint16",
                "uint32",
                "uint64",
                "uintptr",
                "any",
                // The standard types' methods every Go file calls through a
                // variable: `t.Errorf` on a `*testing.T` was 171 of cobra's.
                "Errorf",
                "Error",
                "Fatal",
                "Fatalf",
                "Log",
                "Logf",
                "Helper",
                "Run",
                "Skip",
                "Skipf",
                "Cleanup",
                "TempDir",
                "Setenv",
                "Parallel",
                "Name",
                "String",
                "Close",
                "Write",
                "WriteString",
                "Read",
                "Len",
                "Lock",
                "Unlock",
                "RLock",
                "RUnlock",
                "Add",
                "Done",
                "Wait",
                "Unwrap",
                "Is",
                "As",
                "Bytes",
                "Reset",
                "Sum",
                "Contains",
                "HasPrefix",
                "Sprintf",
            ];
            const PACKAGES: &[&str] = &[
                "fmt",
                "os",
                "io",
                "strings",
                "strconv",
                "errors",
                "bytes",
                "sort",
                "sync",
                "time",
                "context",
                "filepath",
                "path",
                "bufio",
                "regexp",
                "reflect",
                "unicode",
                "utf8",
                "math",
                "rand",
                "json",
                "http",
                "url",
                "log",
                "flag",
                "exec",
                "runtime",
                "atomic",
                "template",
                "testing",
                "hex",
                "base64",
                "ioutil",
                "signal",
                "syscall",
                "user",
                "unsafe",
                "slices",
                "maps",
                "cmp",
                "iter",
                "tabwriter",
                "heap",
                "list",
            ];
            if kind == "imports" {
                // A standard package's path has no dot in its first element.
                let path = name.trim_matches('"');
                return !path.split('/').next().unwrap_or(path).contains('.');
            }
            list(BUILTINS, name) || hint.is_some_and(|h| list(PACKAGES, h))
        }
        "rust" => {
            const BUILTINS: &[&str] = &[
                "Ok",
                "Err",
                "Some",
                "Box",
                "drop",
                "panic!",
                "println!",
                "print!",
                "eprintln!",
                "eprint!",
                "format!",
                "vec!",
                "write!",
                "writeln!",
                "assert!",
                "assert_eq!",
                "assert_ne!",
                "debug_assert!",
                "debug_assert_eq!",
                "unreachable!",
                "todo!",
                "unimplemented!",
                "matches!",
                "concat!",
                "env!",
                "include_str!",
                "include_bytes!",
                "stringify!",
                "line!",
                "file!",
                "format_args!",
                "dbg!",
                "cfg!",
                "thread_local!",
                "compile_error!",
                // The standard traits' and types' methods every Rust file calls.
                "clone",
                "unwrap",
                "expect",
                "into",
                "iter",
                "into_iter",
                "iter_mut",
                "collect",
                "map",
                "to_string",
                "to_owned",
                "as_str",
                "as_ref",
                "as_deref",
                "len",
                "is_empty",
                "push",
                "push_str",
                "pop",
                "get",
                "get_mut",
                "insert",
                "remove",
                "contains",
                "contains_key",
                "unwrap_or",
                "unwrap_or_default",
                "unwrap_or_else",
                "ok",
                "err",
                "ok_or",
                "ok_or_else",
                "and_then",
                "filter",
                "filter_map",
                "next",
                "join",
                "split",
                "trim",
                "starts_with",
                "ends_with",
                "lock",
                "borrow",
                "borrow_mut",
                "take",
                "extend",
                "enumerate",
                "zip",
                "chain",
                "rev",
                "sort",
                "sort_by",
                "sort_by_key",
                "dedup",
                "retain",
                "entry",
                "or_insert",
                "or_default",
                "chars",
                "bytes",
                "lines",
                "find",
                "position",
                "any",
                "all",
                "count",
                "sum",
                "first",
                "last",
                "is_some",
                "is_none",
                "is_ok",
                "is_err",
                "from",
                "default",
                "fmt",
                "eq",
                "cmp",
                "hash",
                "with_capacity",
                "map_err",
                "flatten",
                "flat_map",
                "skip",
                "copied",
                "cloned",
                "truncate",
                "clear",
                "to_vec",
                "keys",
                "values",
                "display",
                "load",
                "store",
                "send",
                "recv",
                "spawn",
                "now",
                "elapsed",
            ];
            const NAMESPACES: &[&str] = &[
                "std",
                "core",
                "alloc",
                "String",
                "Vec",
                "Option",
                "Result",
                "Box",
                "Rc",
                "Arc",
                "HashMap",
                "HashSet",
                "BTreeMap",
                "BTreeSet",
                "VecDeque",
                "Path",
                "PathBuf",
                "File",
                "fs",
                "io",
                "env",
                "thread",
                "mem",
                "ptr",
                "fmt",
                "process",
                "Duration",
                "Instant",
                "Mutex",
                "RwLock",
                "AtomicBool",
                "AtomicUsize",
                "AtomicU64",
                "Ordering",
                "Cow",
                "Cell",
                "RefCell",
                "iter",
                "str",
                "char",
                "u8",
                "u32",
                "u64",
                "usize",
                "i32",
                "i64",
                "f64",
                "Self",
            ];
            if kind == "imports" {
                return ["std", "core", "alloc"]
                    .iter()
                    .any(|root| name == *root || name.starts_with(&format!("{root}::")));
            }
            list(BUILTINS, name) || hint.is_some_and(|h| list(NAMESPACES, h))
        }
        "python" => {
            const BUILTINS: &[&str] = &[
                "abs",
                "all",
                "any",
                "ascii",
                "bin",
                "bool",
                "breakpoint",
                "bytearray",
                "bytes",
                "callable",
                "chr",
                "classmethod",
                "compile",
                "complex",
                "delattr",
                "dict",
                "dir",
                "divmod",
                "enumerate",
                "eval",
                "exec",
                "filter",
                "float",
                "format",
                "frozenset",
                "getattr",
                "globals",
                "hasattr",
                "hash",
                "help",
                "hex",
                "id",
                "input",
                "int",
                "isinstance",
                "issubclass",
                "iter",
                "len",
                "list",
                "locals",
                "map",
                "max",
                "memoryview",
                "min",
                "next",
                "object",
                "oct",
                "open",
                "ord",
                "pow",
                "print",
                "property",
                "range",
                "repr",
                "reversed",
                "round",
                "set",
                "setattr",
                "slice",
                "sorted",
                "staticmethod",
                "str",
                "sum",
                "super",
                "tuple",
                "type",
                "vars",
                "zip",
                "__import__",
                "Exception",
                "ValueError",
                "TypeError",
                "KeyError",
                "IndexError",
                "RuntimeError",
                "NotImplementedError",
                "AttributeError",
                "OSError",
                "ImportError",
                "StopIteration",
                "AssertionError",
                "LookupError",
                "FileNotFoundError",
                "PermissionError",
                "UnicodeDecodeError",
                "Warning",
                "DeprecationWarning",
                "UserWarning",
                // The built-in types' methods.
                "append",
                "extend",
                "get",
                "items",
                "keys",
                "values",
                "join",
                "split",
                "strip",
                "rstrip",
                "lstrip",
                "startswith",
                "endswith",
                "replace",
                "lower",
                "upper",
                "pop",
                "update",
                "setdefault",
                "encode",
                "decode",
                "add",
                "remove",
                "insert",
                "sort",
                "copy",
                "count",
                "index",
                "discard",
                "partition",
                "rpartition",
                "splitlines",
                "isdigit",
                "isidentifier",
            ];
            const MODULES: &[&str] = &[
                "os",
                "sys",
                "re",
                "json",
                "typing",
                "t",
                "collections",
                "cabc",
                "functools",
                "itertools",
                "pathlib",
                "io",
                "time",
                "datetime",
                "logging",
                "subprocess",
                "shutil",
                "tempfile",
                "threading",
                "asyncio",
                "inspect",
                "contextlib",
                "dataclasses",
                "enum",
                "abc",
                "copy",
                "math",
                "random",
                "string",
                "textwrap",
                "traceback",
                "warnings",
                "weakref",
                "types",
                "uuid",
                "hashlib",
                "base64",
                "struct",
                "socket",
                "urllib",
                "http",
                "email",
                "unittest",
                "argparse",
                "pickle",
                "csv",
                "glob",
                "fnmatch",
                "operator",
                "queue",
                "signal",
                "platform",
                "importlib",
                "gzip",
                "zipfile",
                "decimal",
                "statistics",
                "secrets",
                "hmac",
                "ssl",
                "errno",
                "codecs",
                "locale",
                "pprint",
                "heapq",
                "bisect",
                "ast",
                "gc",
                "atexit",
                "mimetypes",
                "numbers",
                "__future__",
                "path",
            ];
            if kind == "imports" {
                // `import typing as t` is recorded with its alias.
                let module = name.split_whitespace().next().unwrap_or(name);
                let top = module.split('.').next().unwrap_or(module);
                return !module.starts_with('.') && list(MODULES, top);
            }
            list(BUILTINS, name) || hint.is_some_and(|h| list(MODULES, h))
        }
        "javascript" | "typescript" | "tsx" => {
            const BUILTINS: &[&str] = &[
                "require",
                "parseInt",
                "parseFloat",
                "isNaN",
                "isFinite",
                "setTimeout",
                "setInterval",
                "clearTimeout",
                "clearInterval",
                "setImmediate",
                "Promise",
                "Object",
                "Array",
                "JSON",
                "Math",
                "Number",
                "String",
                "Boolean",
                "Date",
                "Error",
                "TypeError",
                "RangeError",
                "Symbol",
                "Map",
                "Set",
                "WeakMap",
                "RegExp",
                "encodeURIComponent",
                "decodeURIComponent",
                "encodeURI",
                "decodeURI",
                "fetch",
                "structuredClone",
                "queueMicrotask",
                "push",
                "pop",
                "shift",
                "unshift",
                "map",
                "filter",
                "forEach",
                "reduce",
                "join",
                "split",
                "slice",
                "splice",
                "indexOf",
                "includes",
                "keys",
                "values",
                "entries",
                "then",
                "catch",
                "finally",
                "log",
                "error",
                "warn",
                "info",
                "debug",
                "toString",
                "hasOwnProperty",
                "call",
                "apply",
                "bind",
                "replace",
                "trim",
                "concat",
                "find",
                "some",
                "every",
                "sort",
                "test",
                "exec",
                "match",
                "startsWith",
                "endsWith",
                "toLowerCase",
                "toUpperCase",
                "stringify",
                "parse",
                "assign",
                "freeze",
                "isArray",
                "resolve",
                "reject",
                "all",
                "get",
                "set",
                "has",
                "delete",
                "emit",
                "on",
            ];
            const MODULES: &[&str] = &[
                "fs",
                "path",
                "http",
                "https",
                "url",
                "util",
                "events",
                "stream",
                "os",
                "crypto",
                "child_process",
                "assert",
                "buffer",
                "querystring",
                "zlib",
                "net",
                "readline",
                "process",
                "console",
                "Object",
                "Array",
                "JSON",
                "Math",
                "Promise",
                "Number",
                "String",
                "Date",
                "Reflect",
            ];
            if kind == "imports" {
                let module = name.trim_matches(|c| c == '"' || c == '\'');
                return module.starts_with("node:") || list(MODULES, module);
            }
            list(BUILTINS, name) || hint.is_some_and(|h| list(MODULES, h))
        }
        _ => false,
    }
}

/// Whether an import names the importing project itself — `crate::`,
/// `super::`, Python's `from . import`, `./x` — and so is never code the
/// corpus does not hold, whatever its text resolves to by name.
pub fn is_relative_import(language: &str, name: &str) -> bool {
    match language {
        "rust" => {
            ["crate::", "super::", "self::"]
                .iter()
                .any(|p| name.starts_with(p))
                || matches!(name, "crate" | "super" | "self")
        }
        "python" => name.starts_with('.'),
        "javascript" | "typescript" | "tsx" => {
            let n = name.trim_matches(|c| c == '"' || c == '\'');
            n.starts_with("./") || n.starts_with("../")
        }
        _ => false,
    }
}

/// The same list as a SQL `NOT IN` list, for the two joins that resolve a name.
pub fn not_navigational(column: &str) -> String {
    let holes = NAVIGATIONAL_KINDS
        .iter()
        .map(|k| format!("'{k}'"))
        .collect::<Vec<_>>()
        .join(", ");
    format!("{column} NOT IN ({holes})")
}

/// One edge of a path, as the path finder renders it.
///
/// Both ends carry a file and a line, and that is not decoration. A hop
/// between two names says almost nothing when either name has several
/// definitions: `index -> first_store` is true of some `index`, and until the
/// row says which one, a reader cannot tell whether the chain holds together
/// or quietly changed subject halfway through.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Step {
    pub from: String,
    pub from_path: String,
    pub from_line: u32,
    pub to: String,
    pub to_path: String,
    pub to_line: u32,
    pub kind: String,
    pub confidence: String,
    /// How many definitions of `to` the store holds.
    pub definitions: usize,
    /// The line the call was written on, in `from_path`.
    ///
    /// `None` for an edge written before 0.16.0 and for one whose source file
    /// has not been re-indexed since — the same absence `EdgeEnd::line` has,
    /// carried through rather than guessed at, because the enclosing
    /// definition's line is a different line and often far away.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_line: Option<u32>,
}

/// A chain, with what it is worth.
///
/// Named `Chain` rather than `Path` because this module already works with
/// `std::path::Path` on every line that reads a file.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Chain {
    pub steps: Vec<Step>,
    pub summary: Summary,
}

/// What the chain is made of, counted rather than described.
///
/// Every renderer prints this and none of them computes it, so the CLI, the
/// MCP reply and the portal cannot drift into saying different things about
/// one answer.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Summary {
    pub hops: usize,
    pub extracted: usize,
    pub resolved: usize,
    pub inferred: usize,
    pub ambiguous: usize,
    /// Joins where the chain left one definition of a name and picked up at
    /// another. A seam is not a hop — it is the place two hops were welded
    /// together, and the weld is the part that may not hold.
    pub seams: usize,
    /// The names welded at those seams, with how many definitions each has.
    pub ambiguous_names: Vec<(String, usize)>,
    /// Whether the honest word for this chain is "hypothesis".
    ///
    /// True when the chain has a seam, or when nothing on it was better than
    /// a bare-name match. Either way the renderers say so in one line rather
    /// than leaving a reader to work it out from the badges.
    pub hypothesis: bool,
}

impl Summary {
    /// Read the chain and count it.
    fn of(steps: &[Step]) -> Self {
        let mut summary = Summary {
            hops: steps.len(),
            ..Default::default()
        };
        for step in steps {
            match step.confidence.as_str() {
                EXTRACTED => summary.extracted += 1,
                RESOLVED => summary.resolved += 1,
                AMBIGUOUS => summary.ambiguous += 1,
                _ => summary.inferred += 1,
            }
        }
        // A seam sits between two hops: the first arrives at one definition of
        // a name and the second leaves from another.
        for pair in steps.windows(2) {
            let (before, after) = (&pair[0], &pair[1]);
            if (&before.to_path, before.to_line) == (&after.from_path, after.from_line) {
                continue;
            }
            summary.seams += 1;
            let name = before.to.clone();
            if !summary.ambiguous_names.iter().any(|(n, _)| *n == name) {
                summary
                    .ambiguous_names
                    .push((name, before.definitions.max(2)));
            }
        }
        summary.hypothesis = summary.seams > 0
            || (!steps.is_empty()
                && steps
                    .iter()
                    .all(|s| s.confidence == INFERRED || s.confidence == AMBIGUOUS));
        summary
    }
}

/// What points at a symbol, and what it points at.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Neighbours {
    pub callers: Vec<crate::store::EdgeEnd>,
    pub callees: Vec<crate::store::EdgeEnd>,
    /// Targets the store holds no definition for, listed only when asked.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub unresolved: Vec<crate::store::Unresolved>,
    /// How many of those were left out. Non-zero only when they were, so a
    /// reader is told the list is short rather than left to assume it is
    /// complete.
    #[serde(skip_serializing_if = "is_zero")]
    pub hidden: usize,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

/// One row per name an edge points at, rather than one row per definition that
/// name could mean.
///
/// Only ambiguous rows are folded. A resolved edge already names one
/// definition, and two resolved edges to the same name from two different
/// definitions of the source are two real calls.
pub fn collapse(callees: Vec<crate::store::EdgeEnd>) -> Vec<crate::store::EdgeEnd> {
    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    callees
        .into_iter()
        .filter(|end| {
            if end.confidence != AMBIGUOUS {
                return true;
            }
            seen.insert((end.symbol.name.clone(), end.kind.clone()))
        })
        .collect()
}

impl Chain {
    /// The chain as every surface prints it.
    ///
    /// One renderer, called by the CLI and by the MCP reply, so the two cannot
    /// drift into describing one answer differently. The portal draws the same
    /// four parts from the same JSON.
    ///
    /// `bold` and `reset` are the terminal's escapes, or empty strings for a
    /// surface that has none.
    pub fn render(&self, bold: &str, reset: &str, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = String::new();
        let width = self
            .steps
            .iter()
            .map(|s| {
                endpoint(&s.from, &shorten(&s.from_path), s.from_line)
                    .chars()
                    .count()
            })
            .max()
            .unwrap_or(0);

        for (i, step) in self.steps.iter().enumerate() {
            let left = endpoint(&step.from, &shorten(&step.from_path), step.from_line);
            let right = endpoint(&step.to, &shorten(&step.to_path), step.to_line);
            let pad = " ".repeat(width.saturating_sub(left.chars().count()));
            out.push_str(&format!(
                "{bold}{}{reset}  {left}{pad}  → {right}  {} · {}\n",
                i + 1,
                step.kind,
                step.confidence,
            ));
            // The seam sits between two hops, because that is where it is: the
            // chain arrived at one definition of a name and leaves from
            // another. Drawing it as a hop of its own, as the first sketch of
            // this did, inflates the hop count and hides the join.
            if let Some(next) = self.steps.get(i + 1)
                && (&step.to_path, step.to_line) != (&next.from_path, next.from_line)
            {
                out.push_str(&format!(
                    "   ── seam · {}: {} definitions · continues from {}\n",
                    step.to,
                    step.definitions.max(2),
                    endpoint(&next.from, &shorten(&next.from_path), next.from_line),
                ));
            }
        }

        out.push_str(&self.trailer());
        out.push('\n');
        if self.summary.hypothesis {
            out.push_str("A hypothesis, not a finding.\n");
        }
        out
    }

    /// The counted line under the chain.
    ///
    /// Every number on it is read off the steps, so it cannot disagree with
    /// what was printed above it.
    pub fn trailer(&self) -> String {
        let s = &self.summary;
        // The four counts sum to the hop count, always. A trailer whose parts
        // do not add up sends the reader looking for the hop it left out.
        let mut line = format!(
            "{} hop{} · {} extracted · {} resolved · {} inferred · {} ambiguous",
            s.hops,
            if s.hops == 1 { "" } else { "s" },
            s.extracted,
            s.resolved,
            s.inferred,
            s.ambiguous,
        );
        if s.seams > 0 {
            let names = s
                .ambiguous_names
                .iter()
                .map(|(name, count)| format!("{name}: {count} definitions"))
                .collect::<Vec<_>>()
                .join(", ");
            line.push_str(&format!(" · {} through ambiguous names ({names})", s.seams));
        }
        line
    }
}

/// Leave a path exactly as the store recorded it.
///
/// What a surface with nothing better to do passes to [`Chain::render`]. The
/// CLI passes something that strips the working directory, because a chain of
/// six absolute paths is six copies of one prefix and one useful suffix.
pub fn verbatim(path: &str) -> String {
    path.to_string()
}

/// Where the call, import or reference this edge records was actually written.
///
/// Empty when the edge carries no line — every row written before 0.16.0, and
/// every row whose source file has not been re-indexed since. A renderer says
/// nothing rather than pointing at the enclosing definition and calling it a
/// call site, because those are different lines and often far apart.
///
/// The two shapes are not cosmetic. From [`crate::store::edges_out`] the row's
/// own `symbol` is the *target*, so the call sits in a different file and has
/// to be named. From [`crate::store::edges_in`] the row's `symbol` is the
/// caller itself and its path is already on the line, so only the line number
/// is new.
pub fn call_site(end: &crate::store::EdgeEnd, shorten: &dyn Fn(&str) -> String) -> String {
    // Which of several definitions a caller resolved to: the difference
    // between `Fleet::search_preferring` and `Semlith::search_preferring`
    // is the whole answer to "what calls this one".
    let means = match &end.means {
        Some(m) => format!(" → {m}"),
        None => String::new(),
    };
    let Some(line) = end.line else {
        return means;
    };
    // A structural edge's line is where the definition starts, not a call:
    // printing "call at line 78" for `fn run`'s own line read as a call that
    // does not exist (2026-10-14 audit, G3).
    let what = if matches!(end.kind.as_str(), "defines" | "contains") {
        ("defined at", "defined on line")
    } else {
        ("called at", "call at line")
    };
    match &end.from_path {
        Some(path) => format!("  · {} {}:{line}{means}", what.0, shorten(path)),
        None => format!("  · {} {line}{means}", what.1),
    }
}

/// `1 definition`, `4 definitions`.
pub fn definitions_word(n: usize) -> String {
    format!("{n} definition{}", if n == 1 { "" } else { "s" })
}

/// One edge end as every surface prints it — `semlith neighbors`, `semlith
/// symbol` and their MCP replies — so the CLI and an agent read one line.
pub fn render_end(end: &crate::store::EdgeEnd, shorten: &dyn Fn(&str) -> String) -> String {
    let name = if end.symbol.kind == "module" {
        format!("{} (module)", end.symbol.name)
    } else {
        end.symbol.name.clone()
    };
    let site = call_site(end, shorten);
    // A collapsed row stands for several definitions and must not name one
    // of them: a reader of `get  src/a.rs:12` quotes that file, and it is one
    // of four the call could have meant. A caller (no `from_path`) is one
    // definite place whatever it called, so it keeps its path.
    if end.confidence == AMBIGUOUS && end.from_path.is_some() {
        return format!(
            "  {name} via {} ({}) · {}{site}",
            end.kind,
            end.confidence,
            definitions_word(end.definitions),
        );
    }
    let store = match &end.symbol.store {
        Some(label) => format!("[{label}] "),
        None => String::new(),
    };
    format!(
        "  {name} via {} ({})  {store}{}:{}{site}",
        end.kind,
        end.confidence,
        shorten(&end.symbol.path),
        end.symbol.start_line,
    )
}

/// `name @ path:line`, or the bare name when the store could not say where.
fn endpoint(name: &str, path: &str, line: u32) -> String {
    if path.is_empty() {
        return name.to_string();
    }
    format!("{name} @ {path}:{line}")
}

/// What to say when there is no chain.
///
/// The two sentences are different answers and must not be confused. Without
/// `all_edges` the search refused to cross names it could not pin down, so the
/// honest report is that nothing *it was willing to walk* connects the two —
/// and it names the flag that widens the question. With `all_edges` it walked
/// everything and still found nothing, which is as close to "no" as this tool
/// gets.
pub fn not_connected(from: &str, to: &str, depth: u32, all_edges: bool) -> String {
    if all_edges {
        format!("{from} and {to} are not connected within {depth} hops by any edge in the store.")
    } else {
        format!(
            "{from} and {to} are not connected within {depth} hops by resolved edges. \
             Ambiguous names were not crossed; --all-edges walks them and labels what it finds."
        )
    }
}

/// Which files a graph answer may name: all of them, or the ones a path,
/// extension or language filter selects.
///
/// A store that holds many repositories holds many `run`s and `get`s, and on
/// the 727-question benchmark of 2026-10-01 caller precision was lost to
/// exactly that: definitions and callers from the other repositories. A scope
/// narrows the definitions in SQL (`symbols_by_names` takes the filter's own
/// predicate, so a name defined five hundred times outside the scope is not
/// read at all) and keeps out every caller, callee and reached row whose file
/// the filter does not select. `impact` checks it per hop, so a scoped walk
/// never expands from outside the scope.
#[derive(Debug, Default, Clone)]
pub struct Scope {
    groups: Vec<Vec<String>>,
    paths: Option<std::collections::HashSet<String>>,
}

impl Scope {
    /// Every file in the store.
    pub fn all() -> Self {
        Self::default()
    }

    /// The files `filter` selects in this store; [`Scope::all`] for an empty
    /// filter, with no query.
    pub fn of(db: &rusqlite::Connection, filter: &crate::filter::Filter) -> Result<Self> {
        if filter.is_empty() {
            return Ok(Self::all());
        }
        let paths = crate::store::filtered_paths(db, filter.groups())?;
        Ok(Self {
            groups: filter.groups().to_vec(),
            paths: Some(paths.into_iter().collect()),
        })
    }

    /// Whether a row in `path` belongs in the answer.
    pub fn holds(&self, path: &str) -> bool {
        self.paths.as_ref().is_none_or(|p| p.contains(path))
    }

    /// The definitions of `name` inside the scope, at most `limit`, code
    /// before headings, keys and selectors: ripgrep's twenty YAML `run:` keys
    /// filled `symbol run` ahead of its six Rust `run`s (2026-10-14 audit, G10).
    fn definitions(
        &self,
        db: &rusqlite::Connection,
        name: &str,
        limit: usize,
    ) -> Result<Vec<crate::store::SymbolRow>> {
        Ok(self.definitions_counted(db, name, limit)?.0)
    }

    /// [`Scope::definitions`], and how many there are in all.
    fn definitions_counted(
        &self,
        db: &rusqlite::Connection,
        name: &str,
        limit: usize,
    ) -> Result<(Vec<crate::store::SymbolRow>, usize)> {
        if self.paths.is_none() {
            return crate::store::symbols_named_counted(db, name, limit);
        }
        let mut rows = crate::store::symbols_by_names(
            db,
            std::slice::from_ref(&name.to_string()),
            &self.groups,
        )?;
        rows.sort_by_key(|r| NAVIGATIONAL_KINDS.contains(&r.kind.as_str()));
        let total = rows.len();
        rows.truncate(limit);
        Ok((rows, total))
    }
}

/// One hop in each direction around `name`.
///
/// `all` widens the answer in the two ways it is narrow. Without it, callees
/// to a name with several definitions collapse to one row carrying the count:
/// four rows saying `get` are four different functions, and printing them as
/// four callees says this symbol calls `get` four times, which it does not.
/// And without it, edges pointing outside the corpus are left out, as they
/// always have been — with a count now, so a reader knows the list is short.
///
/// Callers are untouched in both states: an inbound edge came from a symbol
/// id, so it is one definite place in one definite file.
pub fn neighbours(
    db: &rusqlite::Connection,
    name: &str,
    kinds: &[String],
    all: bool,
    scope: &Scope,
) -> Result<Neighbours> {
    let (qualifier, bare) = split_qualified(name);
    let definitions = scope.definitions(db, bare, 64)?;
    let scoped = scope.paths.is_some();
    let defined: Vec<i64> = definitions.iter().map(|d| d.id).collect();
    // A qualifier that owns nothing is ignored rather than answered with
    // nothing: the bare name is the nearest true answer.
    let owned: Vec<&crate::store::SymbolRow> = match qualifier {
        Some(q) => definitions.iter().filter(|d| owned_by(d, q)).collect(),
        None => Vec::new(),
    };
    let owned_ids: Vec<i64> = owned.iter().map(|d| d.id).collect();

    let mut callers = Vec::new();
    for incoming in crate::store::edges_in_resolved(db, bare, kinds)? {
        if !owned_ids.is_empty() && !incoming.means.iter().any(|m| owned_ids.contains(m)) {
            continue;
        }
        // In scope means the caller's file is selected and what it called is
        // one of the definitions the scope holds, not a namesake elsewhere.
        if scoped
            && (!scope.holds(&incoming.end.symbol.path)
                || !incoming.means.iter().any(|m| defined.contains(m)))
        {
            continue;
        }
        let mut end = incoming.end;
        // An unsettled caller stays `ambiguous`, the word `impact` uses for
        // the same edge: rewording it `inferred` here gave one edge two
        // confidences (2026-10-14 audit, G8). The caller is still one
        // definition, so the row keeps its path.
        if end.definitions > 1 && incoming.means.len() == 1 {
            end.means = definitions
                .iter()
                .find(|d| d.id == incoming.means[0])
                .map(|d| d.qualified.clone());
        }
        callers.push(end);
    }

    let mut callees = crate::store::edges_out(db, bare, kinds)?;
    if scoped {
        callees.retain(|e| {
            e.from_path.as_deref().is_some_and(|p| scope.holds(p)) && scope.holds(&e.symbol.path)
        });
    }
    if !owned.is_empty() {
        callees.retain(|e| {
            owned.iter().any(|d| {
                e.from_path.as_deref() == Some(d.path.as_str()) && e.from_line == Some(d.start_line)
            })
        });
    }
    let unresolved = crate::store::unresolved_out(db, bare, kinds)?;
    Ok(Neighbours {
        callers,
        callees: if all { callees } else { collapse(callees) },
        hidden: if all { 0 } else { unresolved.len() },
        unresolved: if all { unresolved } else { Vec::new() },
    })
}

/// The most names one definitions table answers.
pub const NAMES_LIMIT: usize = 20;

/// One row of a definitions table: where a definition is, and its first line.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Signature {
    /// The name as it was asked, so a row answers a question.
    pub asked: String,
    #[serde(flatten)]
    pub symbol: crate::store::SymbolRow,
    /// The definition's first line, from the store's own chunks, trimmed. Empty
    /// when the store holds no chunk over that line.
    pub signature: String,
}

/// Every definition of several names, one compact row each, and no rings.
///
/// The question it answers is "where are these defined and what do they look
/// like" — three `semlith_symbol` calls before 0.30.0, each carrying callers,
/// callees and a second ring the question did not ask for. The rows are the
/// ones `semlith symbol` gives for each name alone, code first: leaving the
/// headings out made `symbol a b` drop a README heading `symbol a` shows
/// (2026-10-14 audit, G11).
pub fn signatures(
    db: &rusqlite::Connection,
    names: &[String],
    scope: &Scope,
) -> Result<Vec<Signature>> {
    let mut out = Vec::new();
    for asked in names.iter().take(NAMES_LIMIT) {
        let (qualifier, bare) = split_qualified(asked);
        let mut rows = scope.definitions(db, bare, 64)?;
        if let Some(q) = qualifier
            && rows.iter().any(|r| owned_by(r, q))
        {
            rows.retain(|r| owned_by(r, q));
        }
        for symbol in rows {
            let signature = crate::store::chunks_overlapping(
                db,
                &symbol.path,
                symbol.start_line,
                symbol.start_line,
            )?
            .iter()
            .find_map(|c| {
                let offset = symbol.start_line.checked_sub(c.start_line)? as usize;
                c.text.lines().nth(offset).map(|l| l.trim().to_string())
            })
            .unwrap_or_default();
            out.push(Signature {
                asked: asked.clone(),
                symbol,
                signature,
            });
        }
    }
    Ok(out)
}

/// A definitions table as text, one row per definition, and a last line
/// naming every asked name that has none.
pub fn render_signatures(
    rows: &[Signature],
    asked: &[String],
    shorten: &dyn Fn(&str) -> String,
) -> String {
    const WIDTH: usize = 110;
    let mut out = String::new();
    for row in rows {
        let mut signature = row.signature.clone();
        if signature.chars().count() > WIDTH {
            signature = signature.chars().take(WIDTH).collect::<String>() + "\u{2026}";
        }
        let store = match &row.symbol.store {
            Some(s) => format!("{s} "),
            None => String::new(),
        };
        out.push_str(&format!(
            "{} {} {store}{}:{}-{}  {}\n",
            row.symbol.qualified,
            row.symbol.kind,
            shorten(&row.symbol.path),
            row.symbol.start_line,
            row.symbol.end_line,
            signature
        ));
    }
    let missing: Vec<&str> = asked
        .iter()
        .filter(|n| !rows.iter().any(|r| r.asked == **n))
        .map(String::as_str)
        .collect();
    if !missing.is_empty() {
        out.push_str(&format!("no definition: {}\n", missing.join(", ")));
    }
    out.trim_end().to_string()
}

/// A graph answer's text fitted under [`ANSWER_CHARS`].
///
/// Lines are kept in order while they fit; the rest are counted per file, read
/// off each line's first `path:line`, and a `more:` line says what narrows
/// them. An answer already under the cap comes back untouched.
pub fn fit(text: String, narrow: &str) -> String {
    if text.len() <= ANSWER_CHARS {
        return text;
    }
    let lines: Vec<&str> = text.lines().collect();
    let mut out = String::new();
    let mut kept = 0;
    for line in &lines {
        if out.len() + line.len() + 1 + 2_000 > ANSWER_CHARS {
            break;
        }
        out.push_str(line);
        out.push('\n');
        kept += 1;
    }
    let rest = &lines[kept..];
    let mut by_file: Vec<(String, usize)> = Vec::new();
    for line in rest {
        let file = line
            .split_whitespace()
            .find_map(|word| {
                let (path, number) = word.rsplit_once(':')?;
                let number = number.split('-').next()?;
                (!path.is_empty() && number.parse::<u32>().is_ok()).then(|| path.to_string())
            })
            .unwrap_or_else(|| "(no path)".to_string());
        match by_file.iter_mut().find(|(f, _)| *f == file) {
            Some((_, n)) => *n += 1,
            None => by_file.push((file, 1)),
        }
    }
    out.push_str(&format!("\n{} more lines, by file\n", rest.len()));
    let mut left = by_file.len();
    for (file, n) in &by_file {
        let line = format!("  {file} · {n}\n");
        if out.len() + line.len() + 300 > ANSWER_CHARS {
            out.push_str(&format!("  … {left} more files\n"));
            break;
        }
        out.push_str(&line);
        left -= 1;
    }
    out.push_str(&format!(
        "more: {} lines past the {ANSWER_CHARS}-character cap; {narrow}",
        rest.len()
    ));
    out
}

/// How many second-ring names an evidence block will name.
///
/// The ego graph is context, not an answer: past a dozen it stops telling a
/// reader where they are and starts costing them the tokens they came to save.
const EGO_LIMIT: usize = 12;

/// One name two hops from the centre, and the first-ring name it came through.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hop {
    /// The first-ring name this was reached through.
    pub via: String,
    pub name: String,
    pub kind: String,
    pub confidence: String,
    /// `caller` or `callee`, relative to `via`.
    pub direction: &'static str,
}

/// Everything the store knows about one symbol, in one reply.
///
/// An agent asking "what is `record_retrieval`" wanted the definition, who
/// calls it, what it calls, and roughly where it sits — and before 0.16.0 that
/// was three tool calls and three replies, two of which it had to make before
/// it knew whether the first was the right symbol.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Evidence {
    pub name: String,
    /// The first `k`, code before headings, keys and selectors.
    pub definitions: Vec<crate::store::SymbolRow>,
    /// How many definitions the name has in all, of which `definitions` is
    /// the first `k`. `symbol run -k 3` said "3 definitions of this name" of
    /// 52 (2026-10-14 audit, G9).
    pub total: usize,
    pub callers: Vec<crate::store::EdgeEnd>,
    pub callees: Vec<crate::store::EdgeEnd>,
    /// The second ring, reached only through names the first ring settled.
    pub ego: Vec<Hop>,
}

/// The definition, the first ring and the second ring, in one pass.
///
/// The second ring is walked only through first-ring names that are
/// `extracted` or `resolved`. An ambiguous name is several unrelated
/// definitions wearing one label, and expanding through one would put
/// somebody else's callers into this symbol's context — the same wrong answer
/// the path finder used to give, in a different shape.
pub fn evidence(
    db: &rusqlite::Connection,
    name: &str,
    kinds: &[String],
    limit: usize,
    all: bool,
    scope: &Scope,
) -> Result<Evidence> {
    let (qualifier, bare) = split_qualified(name);
    let (mut definitions, mut total) = scope.definitions_counted(db, bare, limit)?;
    if let Some(q) = qualifier
        && definitions.iter().any(|d| owned_by(d, q))
    {
        // Every owned one, counted as the bare name is: the qualifier narrows
        // the question, and the count says what it narrowed to.
        let (every, _) = scope.definitions_counted(db, bare, usize::MAX)?;
        let owned: Vec<_> = every.into_iter().filter(|d| owned_by(d, q)).collect();
        total = owned.len();
        definitions = owned.into_iter().take(limit).collect();
    }
    let ring = neighbours(db, name, kinds, all, scope)?;

    let mut ego: Vec<Hop> = Vec::new();
    let settled: Vec<(&str, &crate::store::EdgeEnd)> = ring
        .callers
        .iter()
        .map(|e| ("caller", e))
        .chain(ring.callees.iter().map(|e| ("callee", e)))
        .filter(|(_, e)| e.confidence == EXTRACTED || e.confidence == RESOLVED)
        .collect();

    for (_, first) in &settled {
        if ego.len() >= EGO_LIMIT {
            break;
        }
        let out = crate::store::edges_out(db, &first.symbol.name, kinds)?;
        let into = crate::store::edges_in(db, &first.symbol.name, kinds)?;
        for (direction, end) in out
            .into_iter()
            .map(|e| ("callee", e))
            .chain(into.into_iter().map(|e| ("caller", e)))
        {
            if ego.len() >= EGO_LIMIT {
                break;
            }
            if !scope.holds(&end.symbol.path) {
                continue;
            }
            // The centre is not two hops from itself, and a name already in
            // the first ring is context the reader has.
            if end.symbol.name == bare
                || ring
                    .callers
                    .iter()
                    .chain(ring.callees.iter())
                    .any(|e| e.symbol.name == end.symbol.name)
                || ego.iter().any(|h| h.name == end.symbol.name)
            {
                continue;
            }
            ego.push(Hop {
                via: first.symbol.name.clone(),
                name: end.symbol.name,
                kind: end.kind,
                confidence: end.confidence,
                direction,
            });
        }
    }

    Ok(Evidence {
        name: name.to_string(),
        definitions,
        total,
        callers: ring.callers,
        callees: ring.callees,
        ego,
    })
}

impl Evidence {
    /// The block as every surface prints it.
    ///
    /// One renderer for the CLI and the MCP reply, for the reason the path
    /// finder has one: two hand-written copies is how the same answer ends up
    /// described two different ways.
    pub fn render(&self, bold: &str, reset: &str, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = String::new();
        for symbol in &self.definitions {
            out.push_str(&format!(
                "{bold}{}{reset} {}  {}:{}-{}\n",
                symbol.name,
                symbol.kind,
                shorten(&symbol.path),
                symbol.start_line,
                symbol.end_line,
            ));
        }
        let total = self.total.max(self.definitions.len());
        if total > self.definitions.len() {
            out.push_str(&format!(
                "{total} definitions of this name, {} shown; k {total} lists every one\n",
                self.definitions.len()
            ));
        } else if total > 1 {
            out.push_str(&format!("{total} definitions of this name\n"));
        }
        for (heading, ends) in [("callers", &self.callers), ("callees", &self.callees)] {
            out.push_str(&format!("\n{bold}{heading}{reset} ({})\n", ends.len()));
            if ends.is_empty() {
                out.push_str("  none\n");
            }
            for end in ends.iter() {
                out.push_str(&render_end(end, shorten));
                out.push('\n');
            }
        }
        if !self.ego.is_empty() {
            out.push_str(&format!("\n{bold}two hops out{reset}\n"));
            for hop in &self.ego {
                out.push_str(&format!(
                    "  {} · {} of {} ({})\n",
                    hop.name, hop.direction, hop.via, hop.confidence,
                ));
            }
        }
        out.trim_end().to_string()
    }
}

/// The shortest chain of edges from `from` to `to`, if there is one.
///
/// Breadth-first, so the first path found is a shortest one. `None` means the
/// two are not connected within `depth` by the edges this search was allowed
/// to walk — which is an answer, not a failure, and is reported as one.
///
/// # What it will not walk
///
/// `all_edges` is false by default, and a search in that state refuses to
/// cross an `ambiguous` name: one whose several definitions the source gave it
/// no way to choose between. This is the release's central correction. The
/// 0.14.0 finder crossed those names silently, so `call_tool` reached
/// `record_retrieval` through a `record` that is two unrelated functions, and
/// printed the result in exactly the format a real chain prints in. A wrong
/// answer that looks like a right one is worse than no answer, so by default
/// there is no answer.
///
/// With `all_edges` the old behaviour is available and labelled: the chain
/// comes back with its seams marked, its confidences counted, and the sentence
/// saying it is a hypothesis.
///
/// Within a depth, better-supported edges are expanded first, so a name
/// reachable both ways is reached by the edge worth more. Without that the
/// answer would depend on the order SQLite returned rows in.
pub fn shortest_path(
    db: &rusqlite::Connection,
    from: &str,
    to: &str,
    depth: u32,
    all_edges: bool,
) -> Result<Option<Chain>> {
    if from == to {
        return Ok(Some(Chain {
            steps: Vec::new(),
            summary: Summary::default(),
        }));
    }
    // A node is a definition, not a name. Two functions called `search` are
    // two nodes, and a chain that arrives at one of them may only leave from
    // that one.
    //
    // This is the whole correction. Refusing `ambiguous` edges is not enough
    // on its own: on the semlith store every hop of `call_tool ->
    // record_retrieval` resolves to exactly one definition, and the chain is
    // still false, because hop 3 arrives at `search` in `lib.rs` and hop 4
    // leaves from `search` in `routes.rs`. Each hop is true. The chain is not.
    let mut came_from: std::collections::HashMap<Node, Step> = std::collections::HashMap::new();
    let mut seen: std::collections::HashSet<Node> = std::collections::HashSet::new();
    // The start is every definition of the name, because "does anything called
    // `call_tool` reach this" is the question that was asked.
    let start = Node::any(from);
    seen.insert(start.clone());
    let mut frontier = vec![start];
    let kinds = dependency_kinds();

    for _ in 0..depth {
        // The whole level's edges, ordered by what they are worth, before any
        // of them is taken. Ordering within one node would still let a weak
        // edge out of the first node beat a strong edge out of the second.
        let mut level: Vec<(Node, crate::store::EdgeEnd)> = Vec::new();
        for current in &frontier {
            for edge in crate::store::edges_out(db, &current.name, &kinds)? {
                if !all_edges {
                    if edge.confidence == AMBIGUOUS {
                        continue;
                    }
                    // The edge has to leave from the definition the chain
                    // actually reached. `edges_out` is asked about a name and
                    // answers for every definition of it, which is right for
                    // "what does this name call" and wrong for "what does
                    // *this* function call".
                    if !current.holds(edge.from_path.as_deref(), edge.from_line) {
                        continue;
                    }
                }
                level.push((current.clone(), edge));
            }
        }
        level.sort_by_key(|(_, edge)| confidence_rank(&edge.confidence));

        let mut next = Vec::new();
        for (current, edge) in level {
            // Strict walks definitions; `all_edges` walks names, which is what
            // makes a seam possible and therefore visible. Keying the two the
            // same way would quietly repair the chains this flag exists to
            // show you.
            let reached = if all_edges {
                Node::any(&edge.symbol.name)
            } else {
                Node {
                    name: edge.symbol.name.clone(),
                    path: edge.symbol.path.clone(),
                    line: edge.symbol.start_line,
                }
            };
            if !seen.insert(reached.clone()) {
                continue;
            }
            came_from.insert(
                reached.clone(),
                Step {
                    from: current.name.clone(),
                    // An edge always knows which definition it leaves from.
                    // The fallback is for a row an older store cannot supply,
                    // and it says so rather than inventing a line.
                    from_path: edge.from_path.unwrap_or_default(),
                    from_line: edge.from_line.unwrap_or(0),
                    to: reached.name.clone(),
                    to_path: edge.symbol.path,
                    to_line: edge.symbol.start_line,
                    kind: edge.kind,
                    confidence: edge.confidence,
                    definitions: edge.definitions,
                    call_line: edge.line,
                },
            );
            if reached.name == to {
                let steps = unwind(&came_from, from, &reached);
                let summary = Summary::of(&steps);
                return Ok(Some(Chain { steps, summary }));
            }
            next.push(reached);
            if seen.len() >= MAX_NODES {
                return Ok(None);
            }
        }
        if next.is_empty() {
            break;
        }
        frontier = next;
    }
    Ok(None)
}

/// One definition, as the traversal addresses it.
///
/// `path` empty means "any definition of this name", which is what the start
/// of a search is and nothing else ever is.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Node {
    name: String,
    path: String,
    line: u32,
}

impl Node {
    fn any(name: &str) -> Self {
        Node {
            name: name.to_string(),
            path: String::new(),
            line: 0,
        }
    }

    /// Whether an edge leaving `(path, line)` leaves from this definition.
    ///
    /// A node with no path is the start of the search and holds every
    /// definition. An edge with no recorded source is one an older store
    /// wrote, and is allowed rather than silently dropped: the store predates
    /// the column, so refusing it would turn every pre-0.15.0 store's path
    /// finder off.
    fn holds(&self, path: Option<&str>, line: Option<u32>) -> bool {
        if self.path.is_empty() {
            return true;
        }
        match (path, line) {
            (Some(path), Some(line)) => path == self.path && line == self.line,
            _ => true,
        }
    }
}

/// The graph a page draws, scoped so it is drawable.
///
/// The payload shape is the contract between the store and any renderer, and
/// is deliberately boring: `nodes` with an id, name, kind, path, lines and
/// store; `edges` with `from`/`to` as indexes into `nodes`, a kind and a
/// confidence; and `total`/`shown` so a truncated drawing can say so rather
/// than quietly looking complete.
///
/// Scope is one of: a symbol and its one-hop neighbourhood, a path prefix, or
/// a whole store — in that order of preference. There is no "everything"
/// scope, because a force layout over a monorepo is neither drawable nor
/// readable, and pretending otherwise just produces a hairball.
/// The most connected symbol across these stores, for a view nobody has scoped.
///
/// One candidate per store — `symbols_scoped` already orders by degree — and
/// then the one with the most edges of the few that came back. Cheap: a
/// handful of candidates, one edge lookup each.
/// How many candidates the opening view considers before it picks one.
///
/// The first by raw degree is almost always a name like `new`, `get` or `run`:
/// defined in forty places, called from everywhere, and connected to none of it
/// in a way a reader can follow. Looking at a handful of candidates is what
/// makes it possible to prefer a symbol whose edges mean something.
const SEED_CANDIDATES: usize = 40;

/// How many definitions a target may have before the graph page stops
/// settling edges to it: the same cut search's walk makes.
const DRAW_HUB: usize = 32;

/// The symbol the graph opens on when nobody has asked for one.
///
/// Not the busiest. A corpus's busiest name is its most *reused* name, and a
/// name defined in forty files earns its degree from forty unrelated callers
/// that the extractor could only match by spelling — so the first thing a user
/// saw on a freshly indexed project was a star of dashed `inferred` lines
/// between functions that have nothing to do with each other. That is a true
/// picture of a name collision and a useless picture of a codebase.
///
/// So the seed is the symbol with the most *resolved* edges — the ones where
/// the extractor knew which definition was meant — and a name with several
/// definitions is preferred only when nothing unambiguous has any edges at all.
/// The busiest name is still one search away; it is just not what the page
/// opens on.
fn busiest(stores: &[(&str, &rusqlite::Connection)]) -> Result<Option<String>> {
    // Chosen once per store and graph: the choice reads the busiest symbols of
    // the whole store, seconds on a large one, and gives the same answer until
    // the symbol or edge count moves.
    type Chosen = (String, (i64, i64), Option<String>);
    static CHOSEN: std::sync::Mutex<Vec<Chosen>> = std::sync::Mutex::new(Vec::new());
    let mut key = String::new();
    let mut stats = (0i64, 0i64);
    for (_, db) in stores {
        key.push_str(db.path().unwrap_or(""));
        key.push('|');
        let (a, b) = crate::store::graph_stats(db)?;
        stats = (stats.0 + a, stats.1 + b);
    }
    if let Some((_, _, name)) = CHOSEN
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .find(|(k, st, _)| *k == key && *st == stats)
    {
        return Ok(name.clone());
    }
    let name = busiest_uncached(stores)?;
    let mut chosen = CHOSEN.lock().unwrap_or_else(|e| e.into_inner());
    chosen.retain(|(k, _, _)| *k != key);
    chosen.push((key, stats, name.clone()));
    Ok(name)
}

fn busiest_uncached(stores: &[(&str, &rusqlite::Connection)]) -> Result<Option<String>> {
    let mut best: Option<((usize, usize, usize), String)> = None;
    for (_, db) in stores {
        let db: &rusqlite::Connection = db;
        for name in crate::store::busiest_names(db, SEED_CANDIDATES * 4)? {
            // A target nothing in the store defines (a macro, a standard
            // library call) is busy and cannot be opened on.
            let definitions = crate::store::symbols_named(db, &name, 2)?.len();
            if definitions == 0 {
                continue;
            }
            // Counted, not settled: settling every edge of forty candidates
            // joined millions of candidate rows on the 879k-chunk corpus and
            // held the page, and every route behind it, for minutes.
            let (resolved, degree) = crate::store::edge_counts(db, &name)?;
            if degree == 0 {
                continue;
            }
            // Three keys, in this order. A name defined once in the store
            // cannot be a collision, whatever its degree; among those, the one
            // whose edges the extractor actually resolved; and only then raw
            // degree. The last key is what keeps a store with nothing but
            // inferred edges -- a dynamic language with no import graph --
            // drawing the same thing it drew before rather than nothing at all.
            //
            // The ambiguity that matters is the focus symbol's own. `len` and
            // `new` are defined in dozens of files, so every edge into them is
            // a spelling match between functions that have nothing to do with
            // each other -- which is exactly the star of dashed lines a user
            // met on opening the page.
            let unambiguous = usize::from(definitions <= 1);
            let score = (unambiguous, resolved, degree);
            if best.as_ref().is_none_or(|(seen, _)| score > *seen) {
                best = Some((score, name.clone()));
            }
        }
    }
    Ok(best.map(|(_, name)| name))
}

/// Takes connections rather than open stores, so the daemon can draw on a
/// read-only connection of its own instead of holding every store's lock for
/// the length of the drawing.
pub fn scoped(
    stores: &[(&str, &rusqlite::Connection)],
    focus: Option<&str>,
    prefix: Option<&str>,
    limit: usize,
    label_stores: bool,
) -> Result<serde_json::Value> {
    let mut nodes: Vec<crate::store::SymbolRow> = Vec::new();
    let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    let mut edges: Vec<serde_json::Value> = Vec::new();
    let mut total = 0usize;

    // With nothing asked for, the busiest symbol's neighbourhood rather than
    // the busiest `limit` symbols.
    //
    // Only edges with both ends drawn are drawn, and the most connected
    // symbols in a corpus are hubs that each point at many different leaves
    // and almost never at one another — so "the top two hundred by degree"
    // came back as two hundred boxes and nought edges. A field of dots is
    // technically the graph and of no use to anyone looking at it.
    let chosen_focus = match (focus, prefix) {
        (None, None) => busiest(stores)?,
        (focus, _) => focus.map(str::to_string),
    };
    let focus = chosen_focus.as_deref();

    for (label, db) in stores {
        let db: &rusqlite::Connection = db;
        let picked = match focus {
            Some(name) => {
                // The symbol itself, then what touches it. Deduplicated by the
                // caller, and cut at the budget: a name like `new` is called
                // from everywhere, and drawing all of it is a knot rather than
                // a neighbourhood. The rail lists every caller and callee
                // either way, so nothing is hidden by this — only undrawn.
                let mut around = crate::store::symbols_named(db, name, 4)?;
                let mut ends: Vec<crate::store::EdgeEnd> =
                    crate::store::edges_in_first(db, name, limit * 2)?
                        .into_iter()
                        .chain(crate::store::edges_out_short_of_hubs(
                            db,
                            name,
                            &[],
                            DRAW_HUB,
                        )?)
                        .collect();
                // The certain edges first. When the budget cuts a hub's
                // neighbourhood -- and it always does -- what is drawn should be
                // the calls the extractor resolved rather than whichever
                // spelling matches happened to sort first. A canvas of dashed
                // `inferred` lines is a picture of a name, not of a program.
                ends.sort_by_key(|end| match end.confidence.as_str() {
                    EXTRACTED | RESOLVED => 0,
                    AMBIGUOUS => 1,
                    _ => 2,
                });
                for end in ends {
                    if around.len() >= limit {
                        break;
                    }
                    around.push(end.symbol);
                }
                around
            }
            None => crate::store::symbols_scoped(db, prefix, limit)?,
        };
        total += crate::store::graph_stats(db)?.0 as usize;

        for mut symbol in picked {
            if nodes.len() >= limit {
                break;
            }
            if index.contains_key(&symbol.name) {
                continue;
            }
            if label_stores {
                symbol.store = Some((*label).to_string());
            }
            index.insert(symbol.name.clone(), nodes.len());
            nodes.push(symbol);
        }
    }

    // Only edges whose both ends are drawn. An edge to something off-canvas is
    // not a line anyone can follow.
    //
    // Deduplicated across stores. Every store open is asked about every drawn
    // name, so a symbol two stores both know produced the same edge twice —
    // and a 20-node subgraph reported 836 edges where the whole 43-node graph
    // reported 623, which cannot both be true and is not a number anyone can
    // read.
    let mut seen: std::collections::HashSet<(usize, usize, String)> = Default::default();
    let drawn: Vec<String> = index.keys().cloned().collect();
    for (from_name, from_index) in &index {
        for (_, db) in stores {
            for end in crate::store::edges_out_to(db, from_name, &drawn)? {
                let Some(to_index) = index.get(&end.symbol.name) else {
                    continue;
                };
                if from_index == to_index {
                    continue;
                }
                if !seen.insert((*from_index, *to_index, end.kind.clone())) {
                    continue;
                }
                edges.push(serde_json::json!({
                    "from": from_index,
                    "to": to_index,
                    "kind": end.kind,
                    "confidence": end.confidence,
                }));
            }
        }
    }

    Ok(serde_json::json!({
        "nodes": nodes,
        "edges": edges,
        "total": total,
        "shown": nodes.len(),
    }))
}

fn unwind(came_from: &std::collections::HashMap<Node, Step>, start: &str, end: &Node) -> Vec<Step> {
    let mut chain = Vec::new();
    let mut cursor = end.clone();
    while cursor.name != start {
        // The precise definition first, then the name: a strict walk keys its
        // nodes by definition and an `all_edges` walk keys them by name.
        let Some(step) = came_from
            .get(&cursor)
            .or_else(|| came_from.get(&Node::any(&cursor.name)))
        else {
            break;
        };
        chain.push(step.clone());
        cursor = Node {
            name: step.from.clone(),
            path: step.from_path.clone(),
            line: step.from_line,
        };
        // The first hop leaves from the search's own start, which holds every
        // definition of its name and is keyed that way.
        if cursor.name == start {
            break;
        }
    }
    chain.reverse();
    chain
}

/// How many reached definitions one impact answer will carry.
///
/// Reverse reachability fans out faster than a path does: a utility three
/// hops below `main` reaches most of the tree, and a list that long is a
/// scroll rather than an answer. Past this the answer says how many it left
/// out instead of printing them.
pub const IMPACT_LIMIT: usize = 400;

/// The most characters a graph answer's text may take, at any depth.
///
/// Claude Code refuses an MCP reply past its output limit and hands the agent
/// nothing at all, which is what `search_preferring` at the default depth did
/// on 2026-09-25 with 75 012 characters. Past this, rows collapse into
/// per-file counts and a `more:` line says what narrows them.
pub const ANSWER_CHARS: usize = 16_000;

/// One definition that reaches the symbol asked about.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Reached {
    pub name: String,
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    /// Where the reaching definition starts.
    pub line: u32,
    /// Where the call, import or reference was written, from `edges.line`.
    /// `None` on an edge an older binary wrote; a renderer then says a
    /// re-index adds it rather than printing the definition's line as though
    /// it were the call.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub at: Option<u32>,
    /// Hops from the symbol asked about. One is a direct caller.
    pub hop: u32,
    /// The edge that reached it, and how much that edge is worth.
    pub kind: String,
    pub confidence: String,
    /// The name this one reaches, one hop nearer the centre.
    pub via: String,
}

/// One file that reaches the symbol, and how closely.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReachedFile {
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    /// Definitions in this file that reach the symbol.
    pub symbols: usize,
    /// The fewest hops any of them takes.
    pub nearest: u32,
}

/// Everything that reaches one symbol, to a bounded number of hops.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Impact {
    pub name: String,
    pub depth: u32,
    /// Whether ambiguous edges were walked.
    pub all_edges: bool,
    /// The definitions of the name itself, so a reader knows which symbol
    /// this is about when there is more than one.
    pub definitions: Vec<crate::store::SymbolRow>,
    pub reached: Vec<Reached>,
    pub files: Vec<ReachedFile>,
    /// How many reached definitions were left out at [`IMPACT_LIMIT`].
    #[serde(skip_serializing_if = "is_zero")]
    pub hidden: usize,
    /// The qualifier asked for matched no definition's owner, so the answer
    /// is about the bare name, and says so.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub unqualified: bool,
    /// Counted the same way a chain's summary is counted, so the page and the
    /// terminal cannot disagree about what the answer is made of.
    pub extracted: usize,
    pub resolved: usize,
    pub inferred: usize,
    pub ambiguous: usize,
}

/// `Type::method`, `module::function` or `Type.method`, split into the
/// qualifier and the bare name. A name that is not qualified, or whose parts
/// are not identifiers — a Markdown heading with a version in it — comes back
/// whole.
pub fn split_qualified(name: &str) -> (Option<&str>, &str) {
    let ident = |t: &str| !t.is_empty() && t.chars().all(|c| c.is_alphanumeric() || c == '_');
    let split = name.rsplit_once("::").or_else(|| name.rsplit_once('.'));
    match split {
        Some((owner, bare)) => {
            let last = owner.rsplit("::").next().unwrap_or(owner);
            if ident(last) && ident(bare) {
                (Some(last), bare)
            } else {
                (None, name)
            }
        }
        None => (None, name),
    }
}

/// Whether a definition belongs to `qualifier`: its owning type, its module
/// (the file's stem) or a directory it sits in.
pub fn owned_by(row: &crate::store::SymbolRow, qualifier: &str) -> bool {
    crate::store::owner_of(&row.qualified) == Some(qualifier)
        || module_name(Path::new(&row.path)) == qualifier
        || Path::new(&row.path)
            .parent()
            .is_some_and(|p| p.components().any(|c| c.as_os_str() == qualifier))
}

/// Everything that reaches `name`, breadth first, up to `depth` hops.
///
/// The mirror of [`shortest_path`] and it walks the same graph under the same
/// rule: a node is a definition, not a name, and an ambiguous edge is not
/// crossed unless `all_edges` says to. Breadth first, so the hop recorded
/// against a definition is the fewest hops it takes — a caller that reaches
/// the symbol both directly and through three others is a direct caller.
///
/// From 0.30.0 each hop asks what calls *this definition*: an edge into a
/// name is kept only where the resolver says it means the definition being
/// walked from. Before, a caller of any `run` counted as reaching the `run`
/// in `main.rs`, which is most of why one answer was 75 012 characters.
pub fn impact(
    db: &rusqlite::Connection,
    name: &str,
    kinds: &[String],
    depth: u32,
    all_edges: bool,
    scope: &Scope,
) -> Result<Impact> {
    // Dependency edges by default, for the reason `shortest_path` walks only
    // those: every symbol is one hop from the file that defines it, so a
    // `defines` edge is true and says nothing about who would notice a
    // change. A caller that names kinds explicitly gets exactly those.
    let dependencies = dependency_kinds();
    let kinds = if kinds.is_empty() {
        dependencies.as_slice()
    } else {
        kinds
    };
    let (qualifier, bare) = split_qualified(name);
    let mut definitions = scope.definitions(db, bare, 64)?;
    let mut unqualified = false;
    if let Some(q) = qualifier {
        let owned: Vec<_> = definitions
            .iter()
            .filter(|d| owned_by(d, q))
            .cloned()
            .collect();
        if owned.is_empty() {
            unqualified = !definitions.is_empty();
        } else {
            definitions = owned;
        }
    }
    let mut answer = Impact {
        name: name.to_string(),
        depth,
        all_edges,
        definitions,
        reached: Vec::new(),
        files: Vec::new(),
        hidden: 0,
        unqualified,
        extracted: 0,
        resolved: 0,
        inferred: 0,
        ambiguous: 0,
    };

    // Seen by definition, so two functions sharing a name are two nodes, and
    // the centre itself is never reported as reaching itself.
    let mut seen: std::collections::HashSet<Node> = std::collections::HashSet::new();
    for row in &answer.definitions {
        seen.insert(Node {
            name: row.name.clone(),
            path: row.path.clone(),
            line: row.start_line,
        });
    }
    let asked: std::collections::HashSet<i64> = answer.definitions.iter().map(|d| d.id).collect();

    let mut incoming: std::collections::HashMap<String, Vec<crate::store::Incoming>> =
        std::collections::HashMap::new();
    let mut frontier: Vec<crate::store::SymbolRow> = answer.definitions.clone();
    for hop in 1..=depth {
        let mut next: Vec<crate::store::SymbolRow> = Vec::new();
        for target in &frontier {
            if !incoming.contains_key(&target.name) {
                let found = crate::store::edges_in_resolved(db, &target.name, kinds)?;
                incoming.insert(target.name.clone(), found);
            }
            for edge in &incoming[&target.name] {
                if !edge.means.contains(&target.id) {
                    continue;
                }
                // An edge that could mean several definitions still reaches
                // the question when every one of them is a definition that was
                // asked about: `search_preferring` asked bare means both.
                let within = hop == 1 && edge.means.iter().all(|id| asked.contains(id));
                if !all_edges && edge.end.confidence == AMBIGUOUS && !within {
                    continue;
                }
                let caller = &edge.end.symbol;
                if !scope.holds(&caller.path) {
                    continue;
                }
                let node = Node {
                    name: caller.name.clone(),
                    path: caller.path.clone(),
                    line: caller.start_line,
                };
                if !seen.insert(node) {
                    continue;
                }
                if answer.reached.len() >= IMPACT_LIMIT {
                    answer.hidden += 1;
                    continue;
                }
                match edge.end.confidence.as_str() {
                    EXTRACTED => answer.extracted += 1,
                    RESOLVED => answer.resolved += 1,
                    INFERRED => answer.inferred += 1,
                    _ => answer.ambiguous += 1,
                }
                next.push(caller.clone());
                answer.reached.push(Reached {
                    name: caller.name.clone(),
                    path: caller.path.clone(),
                    line: caller.start_line,
                    at: edge.end.line,
                    hop,
                    kind: edge.end.kind.clone(),
                    confidence: edge.end.confidence.clone(),
                    via: target.name.clone(),
                });
            }
        }
        if next.is_empty() {
            break;
        }
        frontier = next;
    }

    // Files, nearest first, then by how much of the file is involved. A file
    // that reaches the symbol four ways at six hops is further away than one
    // that reaches it once at one hop, and reading it in that order is how
    // somebody decides what to open.
    answer.files = files_of(&answer.reached);
    Ok(answer)
}

/// The reached rows gathered per file, nearest first.
pub fn files_of(reached: &[Reached]) -> Vec<ReachedFile> {
    let mut by_file: std::collections::BTreeMap<String, (usize, u32)> =
        std::collections::BTreeMap::new();
    for row in reached {
        let entry = by_file.entry(row.path.clone()).or_insert((0, row.hop));
        entry.0 += 1;
        entry.1 = entry.1.min(row.hop);
    }
    let mut files: Vec<ReachedFile> = by_file
        .into_iter()
        .map(|(path, (symbols, nearest))| ReachedFile {
            path,
            symbols,
            nearest,
        })
        .collect();
    files.sort_by(|a, b| {
        a.nearest
            .cmp(&b.nearest)
            .then(b.symbols.cmp(&a.symbols))
            .then(a.path.cmp(&b.path))
    });
    files
}

impl Impact {
    /// The whole answer as text, for the terminal and for an agent.
    ///
    /// One renderer, as the chain has one: the CLI and the MCP reply differ
    /// only in whether they are allowed to use bold. It never passes
    /// [`ANSWER_CHARS`]: rows that do not fit are counted per file instead.
    pub fn render(&self, bold: &str, reset: &str, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = self.headline();
        if self.unqualified {
            out.push_str(&format!(
                "\nno definition of {} is owned by {}; this is every {}",
                split_qualified(&self.name).1,
                split_qualified(&self.name).0.unwrap_or_default(),
                split_qualified(&self.name).1
            ));
        }
        if !self.definitions.is_empty() {
            let defs: Vec<String> = self
                .definitions
                .iter()
                .map(|d| format!("{}:{}", shorten(&d.path), d.start_line))
                .collect();
            out.push_str(&format!("\ndefined at {}", defs.join(", ")));
        }
        if self.reached.is_empty() {
            return out;
        }
        // Room kept for the files block and the closing lines, so the rows
        // are what gives way.
        let files_block = self.files_block(bold, reset, shorten);
        let reserve = files_block.len().min(ANSWER_CHARS / 4) + 400;
        let mut hop = 0;
        let mut shown = 0usize;
        let mut undated = 0usize;
        for row in &self.reached {
            let mut chunk = String::new();
            if row.hop != hop {
                chunk.push_str(&format!(
                    "\n\n{bold}{} hop{}{reset}",
                    row.hop,
                    if row.hop == 1 { "" } else { "s" }
                ));
            }
            let at = match row.at {
                Some(at) => format!("{}:{at} in {}", shorten(&row.path), row.name),
                None => {
                    undated += 1;
                    format!(
                        "{}:{} {} (definition)",
                        shorten(&row.path),
                        row.line,
                        row.name
                    )
                }
            };
            chunk.push_str(&format!(
                "\n  {at} · {} {} · reaches {}",
                row.kind, row.confidence, row.via
            ));
            if out.len() + chunk.len() + reserve > ANSWER_CHARS {
                break;
            }
            if row.hop != hop {
                hop = row.hop;
            }
            out.push_str(&chunk);
            shown += 1;
        }
        let collapsed = self.reached.len() - shown;
        if collapsed > 0 {
            let rest = files_of(&self.reached[shown..]);
            out.push_str(&format!("\n\n{bold}{collapsed} more, by file{reset}"));
            let mut left = rest.len();
            for file in &rest {
                let line = format!(
                    "\n  {} · {} · nearest {} hop{}",
                    shorten(&file.path),
                    file.symbols,
                    file.nearest,
                    if file.nearest == 1 { "" } else { "s" }
                );
                if out.len() + line.len() + 300 > ANSWER_CHARS {
                    out.push_str(&format!("\n  … {left} more files"));
                    break;
                }
                out.push_str(&line);
                left -= 1;
            }
            let nearer = self.reached[shown].hop.saturating_sub(1).max(1);
            out.push_str(&format!(
                "\nmore: {collapsed} rows past the {ANSWER_CHARS}-character cap; depth: {nearer} lists them, or ask about one of the callers above"
            ));
        } else if out.len() + files_block.len() < ANSWER_CHARS {
            out.push_str(&files_block);
        }
        if undated > 0 {
            out.push_str(&format!(
                "\n{undated} row{} show{} the caller's definition: this store has no call-site lines for {}; a re-index adds them",
                if undated == 1 { "" } else { "s" },
                if undated == 1 { "s" } else { "" },
                if undated == 1 { "it" } else { "them" }
            ));
        }
        if self.hidden > 0 {
            out.push_str(&format!(
                "\n\n{} more left out at the limit of {IMPACT_LIMIT}",
                self.hidden
            ));
        }
        out
    }

    fn files_block(&self, bold: &str, reset: &str, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = format!("\n\n{bold}files{reset}");
        for file in &self.files {
            out.push_str(&format!(
                "\n  {} · {} definition{} · nearest {} hop{}",
                shorten(&file.path),
                file.symbols,
                if file.symbols == 1 { "" } else { "s" },
                file.nearest,
                if file.nearest == 1 { "" } else { "s" }
            ));
        }
        out
    }

    /// The sentence that says what the answer is, printed by every surface so
    /// none of them writes its own.
    pub fn headline(&self) -> String {
        if self.reached.is_empty() {
            return format!(
                "nothing in this store reaches {} within {} hop{}",
                self.name,
                self.depth,
                if self.depth == 1 { "" } else { "s" }
            );
        }
        let files = self.files.len();
        format!(
            "{} definition{} in {} file{} reach {} within {} hop{}",
            self.reached.len(),
            if self.reached.len() == 1 { "" } else { "s" },
            files,
            if files == 1 { "" } else { "s" },
            self.name,
            self.depth,
            if self.depth == 1 { "" } else { "s" }
        )
    }
}

/// One hop's supporting line, as evidence rather than as a picture.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Support {
    /// `from → to · kind`, the hop this line is evidence for.
    pub hop: String,
    /// Where the line was written: `path:line`, or empty when the store has
    /// no call line for this edge.
    pub at: String,
    /// The line itself, read from the store's own chunks. Empty when the
    /// store cannot supply it, which is said rather than filled in.
    pub code: String,
    /// `supporting fact` or `candidate — corroborate before use`.
    pub mark: &'static str,
}

/// What a chain is worth, in the shape somebody can paste into a review.
///
/// The Trace panel and `semlith trace` are one answer: the sentence, the
/// chain, and one line of source per hop. Nothing here re-walks the graph —
/// it reads a [`Chain`] the finder already produced, so the two can never
/// disagree about what the path was.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Trace {
    pub from: String,
    pub to: String,
    pub depth: u32,
    pub all_edges: bool,
    pub answer: String,
    pub chain: Option<Chain>,
    pub lines: Vec<Support>,
}

/// The mark a hop's supporting line carries.
///
/// An inferred or ambiguous hop was matched by name and nothing more, so the
/// line under it is a candidate for the reader to check. Anything the source
/// or the ranking settled is a fact.
pub fn support_mark(confidence: &str) -> &'static str {
    match confidence {
        EXTRACTED | RESOLVED => "supporting fact",
        _ => "candidate — corroborate before use",
    }
}

/// Turn a chain into evidence.
///
/// `line_text` reads one line of one file out of the store — passed as a
/// closure for the reason [`expand`] takes one: the shape of the answer is
/// testable against a literal map with no store and no model behind it.
pub fn trace(
    from: &str,
    to: &str,
    depth: u32,
    all_edges: bool,
    chain: Option<Chain>,
    mut line_text: impl FnMut(&str, u32) -> Option<String>,
    shorten: &dyn Fn(&str) -> String,
) -> Trace {
    let Some(chain) = chain else {
        return Trace {
            from: from.to_string(),
            to: to.to_string(),
            depth,
            all_edges,
            answer: not_connected(from, to, depth, all_edges),
            chain: None,
            lines: Vec::new(),
        };
    };

    let s = &chain.summary;
    let answer = if chain.steps.is_empty() {
        format!("{from} is {to}.")
    } else if s.hypothesis && s.seams > 0 {
        format!(
            "Not connected by resolved edges. The nearest chain is {} hop{} long and crosses {} ambiguous name{} — treat it as a hypothesis.",
            s.hops,
            if s.hops == 1 { "" } else { "s" },
            s.seams,
            if s.seams == 1 { "" } else { "s" }
        )
    } else if s.hypothesis {
        format!(
            "Not connected by resolved edges. The nearest chain is {} hop{} long and every hop was matched by bare name — treat it as a hypothesis.",
            s.hops,
            if s.hops == 1 { "" } else { "s" }
        )
    } else {
        format!(
            "Connected in {} hop{}: {} extracted, {} resolved. Every hop names its target through something the extractor read or the ranking settled.",
            s.hops,
            if s.hops == 1 { "" } else { "s" },
            s.extracted,
            s.resolved
        )
    };

    let lines = chain
        .steps
        .iter()
        .map(|step| {
            let (at, code) = match step.call_line {
                Some(line) if !step.from_path.is_empty() => (
                    format!("{}:{line}", shorten(&step.from_path)),
                    line_text(&step.from_path, line).unwrap_or_default(),
                ),
                _ => (String::new(), String::new()),
            };
            Support {
                hop: format!("{} → {} · {}", step.from, step.to, step.kind),
                at,
                code,
                mark: support_mark(&step.confidence),
            }
        })
        .collect();

    Trace {
        from: from.to_string(),
        to: to.to_string(),
        depth,
        all_edges,
        answer,
        chain: Some(chain),
        lines,
    }
}

impl Trace {
    /// The whole trace as text, for the terminal and for an agent.
    pub fn render(&self, bold: &str, reset: &str, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = format!("{bold}answer{reset}\n{}\n", self.answer);
        let Some(chain) = &self.chain else {
            return out;
        };
        if chain.steps.is_empty() {
            return out;
        }
        out.push_str(&format!("\n{bold}chain{reset}\n"));
        out.push_str(&chain.render(bold, reset, shorten));
        out.push_str(&format!("\n{bold}supporting lines{reset}\n"));
        for line in &self.lines {
            if line.at.is_empty() {
                out.push_str(&format!(
                    "  {}  ·  no call line recorded  [{}]\n",
                    line.hop, line.mark
                ));
                continue;
            }
            out.push_str(&format!("  {}   {}\n", line.at, line.code));
            out.push_str(&format!("    {}  [{}]\n", line.hop, line.mark));
        }
        out
    }

    /// What "Copy as evidence" copies, and what `--evidence` prints.
    ///
    /// Plain text with no colour and no box drawing, because it is going into
    /// a review comment or a commit message rather than onto a terminal.
    pub fn evidence(&self, shorten: &dyn Fn(&str) -> String) -> String {
        let mut out = format!("{} → {}\nanswer: {}\n", self.from, self.to, self.answer);
        let Some(chain) = &self.chain else {
            return out;
        };
        for (i, step) in chain.steps.iter().enumerate() {
            out.push_str(&format!(
                "{}. {} @ {}:{} -> {} @ {}:{}  [{}]",
                i + 1,
                step.from,
                shorten(&step.from_path),
                step.from_line,
                step.to,
                shorten(&step.to_path),
                step.to_line,
                step.confidence,
            ));
            if let Some(next) = chain.steps.get(i + 1)
                && (&step.to_path, step.to_line) != (&next.from_path, next.from_line)
            {
                out.push_str(&format!(
                    "  seam: {}: {} definitions · continues from {} @ {}:{}",
                    step.to,
                    step.definitions.max(2),
                    next.from,
                    shorten(&next.from_path),
                    next.from_line,
                ));
            }
            out.push('\n');
        }
        if !self.lines.is_empty() {
            out.push_str("\nsupporting lines\n");
            for line in &self.lines {
                let mark = if line.mark.starts_with("candidate") {
                    "candidate"
                } else {
                    "supporting fact"
                };
                if line.at.is_empty() {
                    out.push_str(&format!(
                        "{}   no call line recorded   [{mark}]\n",
                        line.hop
                    ));
                } else {
                    out.push_str(&format!("{}   {}   [{mark}]\n", line.at, line.code));
                }
            }
        }
        out
    }
}

/// Most edges the community pass will read out of one store.
///
/// The bound that stands in for the one-hop-at-a-time rule every other
/// traversal follows. Twenty thousand edges is the whole of this repository's
/// own graph several times over, and a corpus past it gets a panel that says
/// how much it left out.
pub const COMMUNITY_EDGES: usize = 20_000;

/// Rounds of label propagation.
///
/// Label propagation converges in a handful of rounds on graphs this shape,
/// and a fixed cap is what makes the answer the same twice — which the panel
/// needs more than it needs the last percent of modularity.
const LABEL_ROUNDS: usize = 8;

/// How many communities the panel lists before it says `Shown N of M`.
pub const COMMUNITIES_SHOWN: usize = 12;

/// One hub of a community: a name and where it is defined.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hub {
    pub name: String,
    #[serde(serialize_with = "crate::serialize_plain")]
    pub path: String,
    pub line: u32,
}

/// A group of names that call each other more than they call anything else.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Community {
    /// The community's busiest member, which is what it gets called.
    pub label: String,
    pub size: usize,
    /// The three busiest members, by degree inside the community.
    pub hubs: Vec<Hub>,
    /// The strongest edge out of this community: the other community's
    /// label and how many settled edges run to it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cross: Option<(String, usize)>,
}

/// The communities of a graph, by label propagation.
///
/// Deterministic on purpose: nodes are visited in name order and a tie
/// between two labels is broken by name, so the same store gives the same
/// communities twice. That matters more here than modularity does — a panel
/// that regroups a codebase every time it is opened is not a map.
///
/// Takes edges rather than a database for the reason [`expand`] takes a
/// closure: the maths is tested against a literal edge list with no store
/// behind it.
pub fn communities(edges: &[(String, String)]) -> Vec<Community> {
    use std::collections::{BTreeMap, BTreeSet};

    let mut neighbours: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for (from, to) in edges {
        neighbours
            .entry(from.as_str())
            .or_default()
            .insert(to.as_str());
        neighbours
            .entry(to.as_str())
            .or_default()
            .insert(from.as_str());
    }
    if neighbours.is_empty() {
        return Vec::new();
    }

    // Everything starts in a community of its own, and takes the commonest
    // label among its neighbours each round.
    let mut label: BTreeMap<&str, &str> = neighbours.keys().map(|n| (*n, *n)).collect();
    for _ in 0..LABEL_ROUNDS {
        let mut moved = false;
        for (node, around) in &neighbours {
            let mut tally: BTreeMap<&str, usize> = BTreeMap::new();
            for other in around {
                *tally.entry(label[other]).or_default() += 1;
            }
            let Some(&top) = tally.values().max() else {
                continue;
            };
            // A node keeps its own label when that label is among the
            // winners, and only moves when another strictly beats it. Plain
            // label propagation without this collapses: two clusters joined
            // by a single edge become one community, because a tie is
            // resolved by an arbitrary rule rather than by staying put.
            let mine = label[node];
            if tally.get(mine).copied().unwrap_or(0) == top {
                continue;
            }
            // Among strict winners, the name that sorts first, so the result
            // does not depend on iteration order.
            let Some((&best, _)) = tally
                .iter()
                .filter(|(_, n)| **n == top)
                .min_by_key(|(name, _)| **name)
            else {
                continue;
            };
            if mine != best {
                label.insert(node, best);
                moved = true;
            }
        }
        if !moved {
            break;
        }
    }

    let mut members: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for (node, group) in &label {
        members.entry(group).or_default().push(node);
    }

    // How many settled edges run between each pair of communities, for the
    // "strongest cross-community edge" line.
    let mut between: BTreeMap<(&str, &str), usize> = BTreeMap::new();
    for (from, to) in edges {
        let (a, b) = (label[from.as_str()], label[to.as_str()]);
        if a != b {
            *between.entry((a, b)).or_default() += 1;
        }
    }

    let out: Vec<(&str, Community)> = members
        .into_iter()
        .map(|(group, names)| {
            // Degree inside the community decides the hubs and the label: the
            // name everything else in the group talks to is what the group is.
            let inside: BTreeSet<&str> = names.iter().copied().collect();
            let mut ranked: Vec<(usize, &str)> = names
                .iter()
                .map(|name| {
                    let degree = neighbours
                        .get(name)
                        .map(|around| around.iter().filter(|o| inside.contains(*o)).count())
                        .unwrap_or(0);
                    (degree, *name)
                })
                .collect();
            ranked.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
            let cross = between
                .iter()
                .filter(|((a, _), _)| *a == group)
                .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.1.cmp(a.0.1)))
                .map(|((_, b), n)| ((*b).to_string(), *n));
            (
                group,
                Community {
                    label: ranked
                        .first()
                        .map(|(_, name)| (*name).to_string())
                        .unwrap_or_else(|| group.to_string()),
                    size: names.len(),
                    hubs: ranked
                        .iter()
                        .take(3)
                        .map(|(_, name)| Hub {
                            name: (*name).to_string(),
                            path: String::new(),
                            line: 0,
                        })
                        .collect(),
                    cross,
                },
            )
        })
        .collect();

    // `cross` was computed against the group's seed name; a reader needs the
    // other community's own label, which is its busiest member.
    let names: std::collections::BTreeMap<&str, String> = out
        .iter()
        .map(|(group, community)| (*group, community.label.clone()))
        .collect();
    let mut out: Vec<Community> = out
        .into_iter()
        .map(|(_, mut community)| {
            community.cross = community
                .cross
                .map(|(group, n)| (names.get(group.as_str()).cloned().unwrap_or(group), n));
            community
        })
        .collect();
    out.sort_by(|a, b| b.size.cmp(&a.size).then_with(|| a.label.cmp(&b.label)));
    out
}

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

    #[test]
    fn the_four_crashing_shapes_are_too_nested_and_real_files_are_not() {
        let d = 260;
        let quotes = "> ".repeat(d) + "x\n";
        let list: String = (0..d).map(|i| "  ".repeat(i) + "- a\n").collect();
        let seq: String = (0..d).map(|i| "  ".repeat(i) + "-\n").collect();
        let flat = "- ".repeat(d) + "x\n";
        assert!(too_nested("markdown", &quotes));
        assert!(too_nested("markdown", &list));
        assert!(too_nested("yaml", &seq));
        assert!(too_nested("yaml", &flat));
        // The same shapes at a depth people write are left to the grammar.
        let list: String = (0..40).map(|i| "  ".repeat(i) + "- a\n").collect();
        assert!(!too_nested("markdown", &list));
        assert!(!too_nested(
            "markdown",
            "> a quote\n>> a reply\n- item\n  - sub\n"
        ));
        assert!(
            !too_nested("rust", &quotes),
            "only the block grammars are capped"
        );
    }
}

#[cfg(test)]
mod tests {
    /// Two clusters joined by one edge come back as two communities, the same
    /// two twice. A map that regroups a codebase each time it is opened is
    /// not a map, which is why the pass is seeded by name order and capped.
    #[test]
    fn communities_are_the_same_twice_and_name_what_joins_them() {
        let edges: Vec<(String, String)> = [
            ("store_open", "store_read"),
            ("store_read", "store_write"),
            ("store_write", "store_open"),
            ("http_get", "http_parse"),
            ("http_parse", "http_send"),
            ("http_send", "http_get"),
            ("http_parse", "store_read"),
        ]
        .iter()
        .map(|(a, b)| (a.to_string(), b.to_string()))
        .collect();

        let first = communities(&edges);
        let second = communities(&edges);
        assert_eq!(first.len(), 2, "two clusters, one bridge: {first:?}");
        for (a, b) in first.iter().zip(second.iter()) {
            assert_eq!(a.label, b.label, "the label moved between two runs");
            assert_eq!(a.size, b.size);
            let names =
                |c: &Community| -> Vec<String> { c.hubs.iter().map(|h| h.name.clone()).collect() };
            assert_eq!(names(a), names(b), "the hubs moved between two runs");
        }
        for community in &first {
            assert_eq!(community.size, 3, "{community:?}");
            assert!(!community.hubs.is_empty(), "a community with no hub");
        }
        // The bridge is directed, so it is a cross edge out of one community
        // and not out of the other. Counting it both ways would say two
        // subsystems call each other when one of them only answers.
        let crossings: Vec<_> = first.iter().filter_map(|c| c.cross.clone()).collect();
        assert_eq!(crossings.len(), 1, "{first:?}");
        assert_eq!(crossings[0].1, 1, "one edge joins them");
        assert!(
            first.iter().any(|c| c.label == crossings[0].0),
            "a cross edge must name another community's label: {first:?}"
        );
    }

    /// Nothing to group is an empty list, not a panic and not one community
    /// holding everything.
    #[test]
    fn a_graph_with_no_edges_has_no_communities() {
        assert!(communities(&[]).is_empty());
    }

    use super::*;

    /// The fuzzer's SEGV and bash's twin: a character past U+00FF right after
    /// a character a scanner tests with narrow `isdigit` is replaced, byte for
    /// byte, and nothing else changes.
    #[test]
    fn a_wide_character_after_a_digit_is_kept_from_a_narrow_ctype_scanner() {
        let md = " 1\u{5641A}\u{FFFD}";
        let safe = ctype_safe("markdown", md);
        assert_eq!(safe.len(), md.len());
        assert_eq!(safe, " 1aaaa\u{FFFD}");
        assert_eq!(
            ctype_safe("bash", "echo {é..9} {\u{1F600}"),
            "echo {é..9} {aaaa"
        );
        assert!(matches!(
            ctype_safe("markdown", "1. café 2026 \u{1F600}"),
            std::borrow::Cow::Borrowed(_)
        ));
        assert!(matches!(
            ctype_safe("rust", md),
            std::borrow::Cow::Borrowed(_)
        ));
        // The graph of the original text, names read from the original.
        let g = extract(Path::new("a.md"), "# 1\u{1F600} heading\n\nbody\n")
            .unwrap()
            .unwrap();
        assert!(
            g.symbols.iter().any(|s| s.name.contains('\u{1F600}')),
            "{:?}",
            g.symbols
        );
    }

    /// The fuzzer's crash: nesting carried on past NULs on one line.
    #[test]
    fn nesting_that_continues_past_a_control_character_is_too_deep() {
        let line = format!("{}{}{}", ">".repeat(100), "\0".repeat(100), ">".repeat(130));
        assert!(too_nested("markdown", &line));
        assert!(!too_nested("markdown", &format!("{}\0text", ">".repeat(5))));
    }

    /// The pairwise versions the sweeps replaced (audit S18), as the oracle.
    fn contained_pairwise(defs: &[Def]) -> Vec<bool> {
        defs.iter()
            .map(|inner| {
                defs.iter().any(|outer| {
                    outer.name == inner.name
                        && outer.kind == inner.kind
                        && (outer.start, outer.end) != (inner.start, inner.end)
                        && outer.start <= inner.start
                        && outer.end >= inner.end
                })
            })
            .collect()
    }

    fn innermost_pairwise(defs: &[Def], skip: Option<usize>, at: usize) -> Option<usize> {
        let mut best: Option<usize> = None;
        for (i, d) in defs.iter().enumerate() {
            if Some(i) == skip || d.start > at || d.end <= at {
                continue;
            }
            if best.is_none_or(|b| d.end - d.start < defs[b].end - defs[b].start) {
                best = Some(i);
            }
        }
        best
    }

    #[test]
    fn the_sweeps_answer_what_the_pairwise_passes_did() {
        // A small deterministic generator: nested, crossing, equal and
        // duplicated ranges, a few shared names.
        let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
        let mut next = |n: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed % n) as usize
        };
        for _ in 0..300 {
            let count = 1 + next(40);
            let defs: Vec<Def> = (0..count)
                .map(|_| {
                    let start = next(200);
                    let end = start + 1 + next(80);
                    Def {
                        kind: ["function", "class"][next(2)].to_string(),
                        name: ["a", "b", "c"][next(3)].to_string(),
                        owner: None,
                        receiver: None,
                        start,
                        end,
                        start_line: 1,
                        end_line: 1,
                    }
                })
                .collect();
            assert_eq!(contained(&defs), contained_pairwise(&defs));
            let each = enclosing_each(&defs);
            for (i, d) in defs.iter().enumerate() {
                assert_eq!(each[i], innermost_pairwise(&defs, Some(i), d.start));
            }
            let at: Vec<usize> = (0..60).map(|_| next(300)).collect();
            let got = innermost_at(&defs, at.iter().copied(), None);
            for (q, pos) in at.iter().enumerate() {
                assert_eq!(got[q], innermost_pairwise(&defs, None, *pos));
            }
        }
    }
    use std::path::PathBuf;

    fn run(name: &str, src: &str) -> Extraction {
        extract(&PathBuf::from(name), src)
            .expect("extraction does not fail")
            .expect("the extension carries a grammar")
    }

    fn has_edge(e: &Extraction, from: &str, to: &str, kind: &str) -> bool {
        e.edges
            .iter()
            .any(|x| x.from == from && x.to == to && x.kind == kind)
    }

    fn confidence_of(e: &Extraction, to: &str, kind: &str) -> String {
        e.edges
            .iter()
            .find(|x| x.to == to && x.kind == kind)
            .map(|x| x.confidence.clone())
            .unwrap_or_else(|| panic!("no {kind} edge to {to} in {:?}", e.edges))
    }

    /// A macro invocation is not a call to a function of that name.
    ///
    /// `format!(...)` is the single worst case in the corpus: every function
    /// that formats a string looked like a caller of `store::format`, which on
    /// the semlith store meant 229 of them. The name the source writes is
    /// `format!`, and that is a different name from `format` — so that is what
    /// the edge records, and the two stop being confused for one another.
    #[test]
    fn a_macro_invocation_is_recorded_under_the_name_the_source_writes() {
        let e = run(
            "a.rs",
            "fn go() { let s = format!(\"{}\", 1); println!(\"{s}\"); helper(); }\nfn helper() {}\n",
        );
        assert!(
            !has_edge(&e, "go", "format", "calls"),
            "a `format!` is not a call to `fn format`: {:?}",
            e.edges
        );
        assert!(has_edge(&e, "go", "format!", "calls"), "{:?}", e.edges);
        assert!(has_edge(&e, "go", "println!", "calls"), "{:?}", e.edges);
        assert!(
            has_edge(&e, "go", "helper", "calls"),
            "an ordinary call is untouched: {:?}",
            e.edges
        );
    }

    /// A call written inside a macro's arguments is still a call (#244).
    ///
    /// tree-sitter-rust leaves a macro's arguments as an unparsed token tree,
    /// so `json!({ "x": f(1) })` held no `call_expression` and the graph had no
    /// edge for `f` — which is how semlith-cloud's call to
    /// `mcp::tool_list_tokens` inside a `json!` escaped the impact check on
    /// #238. The macro name itself stays a reference to the macro.
    #[test]
    fn a_call_inside_a_macro_argument_is_a_call() {
        let e = run(
            "a.rs",
            "#[cfg(not(test))]\nfn go(x: X) {\n    let v = json!({ \"x\": f(1), \"y\": vec![1] });\n    \
             let s = format!(\"{}\", a::g(2));\n    assert!(x.h());\n}\n",
        );
        let only = |to: &str| -> Vec<&Edge> {
            e.edges
                .iter()
                .filter(|x| x.from == "go" && x.to == to && x.kind == "calls")
                .collect()
        };
        assert_eq!(only("f").len(), 1, "{:?}", e.edges);
        let g = only("g");
        assert_eq!(g.len(), 1, "{:?}", e.edges);
        assert_eq!(g[0].hint.as_deref(), Some("a"), "{:?}", e.edges);
        let h = only("h");
        assert_eq!(h.len(), 1, "{:?}", e.edges);
        assert!(
            h[0].hint
                .as_deref()
                .is_some_and(|x| x.starts_with(RECEIVER)),
            "a method call inside a macro is still a method call: {:?}",
            e.edges
        );
        for name in ["json", "vec", "format", "assert"] {
            assert!(
                !has_edge(&e, "go", name, "calls"),
                "a macro name is not a call to `fn {name}`: {:?}",
                e.edges
            );
        }
        assert!(has_edge(&e, "go", "json!", "calls"), "{:?}", e.edges);
        assert!(
            !e.edges.iter().any(|x| x.to == "not"),
            "an attribute's arguments call nothing: {:?}",
            e.edges
        );
    }

    /// The #244 case end to end: a crate whose only call to
    /// `mcp::tool_list_tokens` sits inside a `json!`, indexed by the writer
    /// `index_set` uses, names that caller under neighbours and impact.
    #[test]
    fn a_caller_inside_json_is_a_neighbour_and_an_impact() {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        for (path, text) in [
            (
                "src/mcp.rs",
                "pub fn tool_list_tokens(counter: &Counter) -> usize { 0 }\n",
            ),
            (
                "src/routes.rs",
                "use crate::mcp;\nfn tools(counter: &Counter) -> Value {\n    \
                 json!({ \"tokens\": mcp::tool_list_tokens(counter) })\n}\n",
            ),
        ] {
            let file = crate::store::insert_file(&db, path, path, text.len() as u64, 0).unwrap();
            let e = extract(Path::new(path), text).unwrap().unwrap();
            crate::store::write_extraction(&db, &e, file, &[]).unwrap();
        }
        let n = neighbours(&db, "tool_list_tokens", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers.iter().any(|c| c.symbol.name == "tools"),
            "{:?}",
            n.callers
        );
        let reach = impact(&db, "tool_list_tokens", &[], 1, false, &Scope::all()).unwrap();
        assert!(
            reach.reached.iter().any(|r| r.name == "tools"),
            "{:?}",
            reach.reached
        );
    }

    #[test]
    fn a_file_with_no_grammar_yields_nothing_rather_than_failing() {
        // Markdown had no grammar until 0.17.0 and was this test's example of
        // a file the extractor skips. A file in no language at all is the
        // example that stays true.
        assert!(
            extract(&PathBuf::from("notes.txt"), "the lock is acquired")
                .unwrap()
                .is_none()
        );
    }

    /// A `const` and a `static` are definitions. The bundled tags query tags
    /// neither, so without the supplement the definition lift in
    /// `search_preferring` cannot fire for one and `semlith symbol MAX_NODES`
    /// answers nothing.
    #[test]
    fn rust_constants_and_statics_are_symbols() {
        let e = run(
            "limits.rs",
            "/// How many nodes a traversal may visit.\n\
             pub const MAX_NODES: usize = 4000;\n\
             static REGISTRY: &str = \"registry.json\";\n\
             fn helper() {}\n",
        );
        let named = |n: &str| e.symbols.iter().find(|s| s.name == n);
        let max_nodes = named("MAX_NODES")
            .unwrap_or_else(|| panic!("MAX_NODES is not a symbol: {:?}", e.symbols));
        assert_eq!(max_nodes.kind, "constant", "{max_nodes:?}");
        let registry = named("REGISTRY")
            .unwrap_or_else(|| panic!("REGISTRY is not a symbol: {:?}", e.symbols));
        assert_eq!(registry.kind, "constant", "{registry:?}");
        assert!(
            named("helper").is_some(),
            "the supplement broke the tags query"
        );
    }

    #[test]
    fn rust_carries_every_edge_kind_it_can_express() {
        let e = run(
            "lock.rs",
            "use std::fs::File;\n\
             struct Guard;\n\
             impl Guard {\n    fn open(&self) { File::create(\"x\"); helper(); }\n}\n\
             fn helper() {}\n",
        );
        assert!(e.symbols.iter().any(|s| s.name == "Guard"));
        assert!(e.symbols.iter().any(|s| s.name == "open"));
        assert!(has_edge(&e, "lock", "helper", "defines"), "{:?}", e.edges);
        assert!(has_edge(&e, "open", "helper", "calls"), "{:?}", e.edges);
        assert!(
            e.edges.iter().any(|x| x.kind == "imports"),
            "the supplementary query supplies imports: {:?}",
            e.edges
        );
    }

    /// The two halves of the stored confidence column, in one file. The call
    /// is to `create`, and the file imported the `File` it goes through, so
    /// the source named where it came from; `helper` is a bare name and did
    /// not.
    #[test]
    fn an_imported_name_is_extracted_and_a_bare_one_is_inferred() {
        let e = run(
            "a.rs",
            "use std::fs::File;\nfn go() { File::create(\"x\"); helper(); }\nfn helper() {}\n",
        );
        assert_eq!(confidence_of(&e, "create", "calls"), EXTRACTED);
        assert_eq!(confidence_of(&e, "helper", "calls"), INFERRED);
    }

    fn hint_of(e: &Extraction, to: &str, kind: &str) -> Option<String> {
        e.edges
            .iter()
            .find(|x| x.to == to && x.kind == kind)
            .unwrap_or_else(|| panic!("no {kind} edge to {to} in {:?}", e.edges))
            .hint
            .clone()
    }

    /// A scoped call is a call to the function, and the path in front of it is
    /// a lead about which definition of that function was meant. Until 0.15.0
    /// the path segment was a second `calls` edge, which recorded a call the
    /// source never makes and gave the path finder a module to walk through.
    #[test]
    fn a_scoped_rust_call_hints_at_its_module_and_does_not_call_it() {
        let e = run("a.rs", "fn go() { store::edges_out(db, name); }\n");
        assert!(has_edge(&e, "go", "edges_out", "calls"), "{:?}", e.edges);
        assert_eq!(hint_of(&e, "edges_out", "calls").as_deref(), Some("store"));
        assert!(
            !has_edge(&e, "go", "store", "calls"),
            "the module is not called: {:?}",
            e.edges
        );
    }

    /// A longer path hints with the segment nearest the name, because that is
    /// the one that names the module the definition lives in.
    #[test]
    fn a_longer_rust_path_hints_with_the_segment_nearest_the_name() {
        let e = run("a.rs", "fn go() { crate::store::edges_out(db); }\n");
        assert_eq!(hint_of(&e, "edges_out", "calls").as_deref(), Some("store"));
    }

    /// A method call's receiver is a lead too, reduced to its last identifier
    /// and marked as a receiver. `self` outside any `impl` names no type, so
    /// the mark stands alone.
    #[test]
    fn a_rust_method_call_hints_with_its_receiver() {
        let e = run(
            "a.rs",
            "fn go(&self) { self.index.search(v); self.flush(); }\n",
        );
        assert_eq!(hint_of(&e, "search", "calls").as_deref(), Some(".index"));
        assert_eq!(hint_of(&e, "flush", "calls").as_deref(), Some("."));
    }

    /// A Python object the file imports as a module is a module path; any
    /// other object is a receiver, and `self` is the enclosing class.
    #[test]
    fn python_and_typescript_qualified_calls_carry_the_object_as_a_hint() {
        let py = run(
            "m.py",
            "import json\n\nclass Store:\n    def go(self):\n        json.loads(raw)\n        app.render()\n        self.flush()\n",
        );
        assert_eq!(hint_of(&py, "loads", "calls").as_deref(), Some("json"));
        assert_eq!(hint_of(&py, "render", "calls").as_deref(), Some(".app"));
        assert_eq!(hint_of(&py, "flush", "calls").as_deref(), Some(".Store"));

        let ts = run("app.ts", "function go(){ store.search(q); }\n");
        assert_eq!(hint_of(&ts, "search", "calls").as_deref(), Some("store"));
    }

    /// A Rust method's receiver names its type where the source says it, and
    /// a method is qualified by the type it is implemented on (1.11).
    #[test]
    fn rust_receivers_name_their_type_and_methods_their_owner() {
        let src = "struct Member { store: Semlith }\n\
            struct Unreadable { store: String }\n\
            struct Fleet { members: Vec<Member> }\n\
            impl Fleet {\n\
                fn search_in(&self) { self.search_preferring(); }\n\
                fn search_preferring(&self) { self.members[0].store.search_preferring(); }\n\
            }\n\
            fn run(fleet: &mut Fleet) { fleet.open(); }\n\
            fn build() { let s = Semlith::open(p)?; s.index(); let t = Other { a: 1 }; t.go(); }\n";
        let e = run("fleet.rs", src);
        let owner_of = |name: &str| {
            e.symbols
                .iter()
                .find(|s| s.name == name)
                .map(|s| s.qualified.clone())
        };
        assert_eq!(owner_of("search_in").as_deref(), Some("Fleet::search_in"));
        assert_eq!(owner_of("run").as_deref(), Some("fleet::run"));
        let hint = |from: &str, to: &str| {
            e.edges
                .iter()
                .find(|x| x.from == from && x.to == to && x.kind == "calls")
                .and_then(|x| x.hint.clone())
        };
        assert_eq!(
            hint("search_in", "search_preferring").as_deref(),
            Some(".Fleet")
        );
        // Not recursion: the same name, on a field declared `store: Semlith`.
        assert_eq!(
            hint("search_preferring", "search_preferring").as_deref(),
            Some(".Semlith"),
            "{:?}",
            e.edges
        );
        assert_eq!(hint("run", "open").as_deref(), Some(".Fleet"));
        assert_eq!(hint("build", "index").as_deref(), Some(".Semlith"));
        assert_eq!(hint("build", "go").as_deref(), Some(".Other"));
        // A `for` binding is the element of what it iterates.
        let e = run(
            "a.rs",
            "struct Item; impl Item { fn go(&self) {} }\nstruct Bag { items: Vec<Item> }\nimpl Bag { fn all(&self) { for it in &self.items { it.go(); } } }\n",
        );
        let go = e
            .edges
            .iter()
            .find(|x| x.from == "all" && x.to == "go")
            .and_then(|x| x.hint.clone());
        assert_eq!(go.as_deref(), Some(".Item"), "{:?}", e.edges);
    }

    /// Recursion still adds no edge.
    #[test]
    fn rust_recursion_on_self_adds_no_edge() {
        let e = run(
            "a.rs",
            "struct A;\nimpl A { fn go(&self) { self.go(); } }\n",
        );
        assert!(!has_edge(&e, "go", "go", "calls"), "{:?}", e.edges);
    }

    /// One call reaches the extractor twice — once from the bundled query,
    /// once from the supplement — and only one of the two carries the hint.
    /// The edge that survives has to be the informed one.
    #[test]
    fn the_hinted_copy_of_a_doubly_captured_call_is_the_one_kept() {
        let e = run("a.rs", "fn go() { store::edges_out(db); }\n");
        let calls: Vec<&Edge> = e
            .edges
            .iter()
            .filter(|x| x.to == "edges_out" && x.kind == "calls")
            .collect();
        assert_eq!(calls.len(), 1, "{:?}", e.edges);
        assert_eq!(calls[0].hint.as_deref(), Some("store"));
    }

    /// A nested definition hangs off its parent, not off the file.
    #[test]
    fn nesting_produces_contains_rather_than_defines() {
        let e = run("m.py", "class Box:\n    def open(self):\n        pass\n");
        assert!(has_edge(&e, "Box", "open", "contains"), "{:?}", e.edges);
        assert!(has_edge(&e, "m", "Box", "defines"), "{:?}", e.edges);
    }

    #[test]
    fn typescript_calls_come_from_the_supplement() {
        let e = run(
            "app.ts",
            "import {a} from './m';\nfunction f(){ helper(); obj.go(); }\nfunction helper(){}\n",
        );
        assert!(has_edge(&e, "f", "helper", "calls"), "{:?}", e.edges);
        assert!(has_edge(&e, "f", "go", "calls"), "{:?}", e.edges);
        assert!(e.edges.iter().any(|x| x.kind == "imports"));
    }

    #[test]
    fn c_calls_and_includes_come_from_the_supplement() {
        let e = run(
            "main.c",
            "#include <stdio.h>\nint helper(){ return 1; }\nint main(){ return helper(); }\n",
        );
        assert!(has_edge(&e, "main", "helper", "calls"), "{:?}", e.edges);
        assert!(
            e.edges
                .iter()
                .any(|x| x.kind == "imports" && x.to == "stdio.h"),
            "{:?}",
            e.edges
        );
    }

    #[test]
    fn python_go_and_java_each_yield_symbols_and_edges() {
        let py = run(
            "m.py",
            "import os\ndef go():\n    helper()\ndef helper():\n    pass\n",
        );
        assert!(has_edge(&py, "go", "helper", "calls"), "{:?}", py.edges);
        assert!(py.edges.iter().any(|x| x.kind == "imports" && x.to == "os"));

        let go = run(
            "m.go",
            "package m\nimport \"fmt\"\nfunc helper() {}\nfunc Run() { helper() }\n",
        );
        assert!(has_edge(&go, "Run", "helper", "calls"), "{:?}", go.edges);
        assert!(
            go.edges
                .iter()
                .any(|x| x.kind == "imports" && x.to == "fmt")
        );

        let java = run(
            "A.java",
            "import java.util.List;\nclass A { void go(){ helper(); } void helper(){} }\n",
        );
        assert!(has_edge(&java, "go", "helper", "calls"), "{:?}", java.edges);
        assert!(java.edges.iter().any(|x| x.kind == "imports"));
        assert!(has_edge(&java, "A", "go", "contains"), "{:?}", java.edges);
    }

    /// One language's fixture and what the extractor must find in it.
    ///
    /// The fixture is a real file on disk under `tests/fixtures/graph/`, so it
    /// is written in the language rather than in a Rust string literal, and an
    /// editor, a formatter and a human all read it as what it is.
    struct Fixture {
        language: &'static str,
        /// Path under `tests/fixtures/graph/`.
        file: &'static str,
        /// Symbols that must be extracted, as (name, kind).
        symbols: &'static [(&'static str, &'static str)],
        /// Edges that must be extracted, as (from, to, kind).
        edges: &'static [(&'static str, &'static str, &'static str)],
    }

    /// What every language must yield, declared rather than discovered.
    ///
    /// A language with no row here fails
    /// `every_advertised_language_has_a_fixture`, so a grammar cannot be wired
    /// up and left unproven: "it compiled" is not "it extracts anything". The
    /// expectations are written first and the extractor is made to meet them —
    /// loosening a row to match what the code happened to produce is the one
    /// move this table exists to prevent.
    const FIXTURES: &[Fixture] = &[
        Fixture {
            language: "rust",
            file: "rust/lock.rs",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[
                ("acquire", "helper", "calls"),
                ("lock", "std::fs::File", "imports"),
            ],
        },
        Fixture {
            language: "typescript",
            file: "typescript/app.ts",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls"), ("app", "./m", "imports")],
        },
        Fixture {
            language: "python",
            file: "python/run.py",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls"), ("run", "os", "imports")],
        },
        Fixture {
            language: "go",
            file: "go/serve.go",
            symbols: &[
                ("MaxHolders", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls"), ("serve", "fmt", "imports")],
        },
        Fixture {
            language: "java",
            file: "java/Main.java",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("Main", "class"),
                ("helper", "method"),
                ("acquire", "method"),
            ],
            edges: &[
                ("acquire", "helper", "calls"),
                ("Main", "helper", "contains"),
            ],
        },
        Fixture {
            language: "c",
            file: "c/main.c",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "clojure",
            file: "clojure/lock.clj",
            symbols: &[
                ("max-holders", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "cpp",
            file: "cpp/lock.cpp",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("MAX_WAITERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "csharp",
            file: "csharp/Lock.cs",
            symbols: &[
                ("MaxHolders", "constant"),
                ("Lock", "class"),
                ("Helper", "method"),
                ("Acquire", "method"),
            ],
            edges: &[("Acquire", "Helper", "calls")],
        },
        Fixture {
            language: "css",
            file: "css/lock.css",
            symbols: &[("acquire", "selector"), ("lock", "selector")],
            edges: &[("lock", "base.css", "imports")],
        },
        Fixture {
            language: "dart",
            file: "dart/lock.dart",
            symbols: &[
                ("maxHolders", "variable"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "dockerfile",
            file: "dockerfile/Dockerfile",
            symbols: &[("build", "stage"), ("runtime", "stage")],
            edges: &[
                ("build", "debian", "imports"),
                ("runtime", "build", "imports"),
            ],
        },
        Fixture {
            language: "elixir",
            file: "elixir/lock.ex",
            symbols: &[
                ("max_holders", "constant"),
                ("Lock", "module"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "elm",
            file: "elm/Lock.elm",
            symbols: &[("helper", "function"), ("acquire", "function")],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "erlang",
            file: "erlang/lock.erl",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("lock", "module"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "fortran",
            file: "fortran/lock.f90",
            symbols: &[
                ("max_holders", "constant"),
                ("lock", "module"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "graphql",
            file: "graphql/lock.graphql",
            symbols: &[
                ("Lock", "type"),
                ("Holder", "type"),
                ("Acquire", "operation"),
            ],
            edges: &[("Lock", "holder", "contains")],
        },
        Fixture {
            language: "groovy",
            file: "groovy/lock.groovy",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "haskell",
            file: "haskell/Lock.hs",
            symbols: &[("helper", "function"), ("acquire", "function")],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "html",
            file: "html/lock.html",
            symbols: &[("acquire", "element")],
            edges: &[
                ("lock", "base.css", "imports"),
                ("lock", "app.js", "imports"),
            ],
        },
        Fixture {
            language: "javascript",
            file: "javascript/app.js",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls"), ("app", "./m", "imports")],
        },
        Fixture {
            language: "json",
            file: "json/lock.json",
            symbols: &[("name", "key"), ("acquire", "key"), ("timeout", "key")],
            edges: &[("acquire", "timeout", "contains")],
        },
        Fixture {
            language: "julia",
            file: "julia/lock.jl",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("Lock", "module"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "kotlin",
            file: "kotlin/Lock.kt",
            symbols: &[
                ("MAX_HOLDERS", "property"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "lua",
            file: "lua/lock.lua",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "makefile",
            file: "makefile/Makefile",
            symbols: &[("helper", "target"), ("acquire", "target")],
            edges: &[
                ("acquire", "helper", "references"),
                ("Makefile", "config.mk", "imports"),
            ],
        },
        Fixture {
            language: "markdown",
            file: "markdown/notes.md",
            symbols: &[("Lock", "heading"), ("Acquire", "heading")],
            edges: &[("Lock", "Acquire", "contains")],
        },
        Fixture {
            language: "nix",
            file: "nix/lock.nix",
            symbols: &[("helper", "binding"), ("acquire", "binding")],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "objective-c",
            file: "objective-c/Lock.m",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("Lock", "class"),
                ("helper", "method"),
                ("acquire", "method"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "ocaml",
            file: "ocaml/lock.ml",
            symbols: &[("helper", "function"), ("acquire", "function")],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "perl",
            file: "perl/lock.pl",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "php",
            file: "php/lock.php",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "powershell",
            file: "powershell/Lock.ps1",
            symbols: &[("Get-Helper", "function"), ("Get-Acquire", "function")],
            edges: &[("Get-Acquire", "Get-Helper", "calls")],
        },
        Fixture {
            language: "proto",
            file: "proto/lock.proto",
            symbols: &[("Lock", "message"), ("Acquire", "service"), ("Hold", "rpc")],
            edges: &[("lock", "base.proto", "imports")],
        },
        Fixture {
            language: "r",
            file: "r/lock.r",
            symbols: &[("helper", "function"), ("acquire", "function")],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "ruby",
            file: "ruby/lock.rb",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "method"),
                ("acquire", "method"),
            ],
            edges: &[("lock", "helper", "defines")],
        },
        Fixture {
            language: "scala",
            file: "scala/Lock.scala",
            symbols: &[
                ("MaxHolders", "constant"),
                ("Lock", "object"),
                // Members of `object Lock`, reached as `Lock.helper()`.
                ("helper", "method"),
                ("acquire", "method"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "shell",
            file: "shell/lock.sh",
            symbols: &[
                ("MAX_HOLDERS", "constant"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[
                ("acquire", "helper", "calls"),
                ("lock", "./config.sh", "imports"),
            ],
        },
        Fixture {
            language: "sql",
            file: "sql/lock.sql",
            symbols: &[("lock_holder", "table"), ("acquire", "view")],
            edges: &[("acquire", "lock_holder", "references")],
        },
        Fixture {
            language: "svelte",
            file: "svelte/Lock.svelte",
            symbols: &[("lock", "element")],
            edges: &[("Lock", "lock", "defines")],
        },
        Fixture {
            language: "swift",
            file: "swift/Lock.swift",
            symbols: &[
                ("maxHolders", "property"),
                ("helper", "function"),
                ("acquire", "function"),
            ],
            edges: &[("acquire", "helper", "calls")],
        },
        Fixture {
            language: "terraform",
            file: "terraform/lock.tf",
            symbols: &[("region", "block"), ("base", "block"), ("lock", "block")],
            edges: &[("lock", "region", "defines")],
        },
        Fixture {
            language: "toml",
            file: "toml/lock.toml",
            symbols: &[("name", "key"), ("acquire", "table")],
            edges: &[("acquire", "timeout", "contains")],
        },
        Fixture {
            language: "vue",
            file: "vue/Lock.vue",
            symbols: &[("lock", "element")],
            edges: &[("Lock", "lock", "defines")],
        },
        Fixture {
            language: "yaml",
            file: "yaml/lock.yaml",
            symbols: &[("name", "key"), ("acquire", "key"), ("timeout", "key")],
            edges: &[("acquire", "timeout", "contains")],
        },
        Fixture {
            language: "zig",
            file: "zig/lock.zig",
            symbols: &[
                ("MAX_HOLDERS", "variable"),
                ("helper", "function"),
                ("acquire", "function"),
                ("std", "variable"),
            ],
            // `const std = @import("std")` binds a name equal to the module
            // it imports, so the import is a self-edge and is dropped: the
            // binding itself is the fact worth recording, and it is a symbol.
            edges: &[("acquire", "helper", "calls")],
        },
    ];

    /// Languages whose fixture declares no symbol of kind `constant`, and why.
    ///
    /// Two different reasons live here, and each row says which it is, because
    /// "this language has nothing to extract" and "this language extracts it
    /// already" are not the same fact and a reader who conflates them will
    /// delete the wrong row.
    ///
    /// The first group has no construct for a named constant at all. A plain
    /// assignment is not one: a Makefile variable can be overridden on the
    /// command line, a CSS custom property can be redefined by a later rule,
    /// and a shell script that says `MAX=4` can say `MAX=5` on the next line —
    /// which is exactly why `shell` is not in this list and `readonly` is what
    /// its query matches. The second group is languages whose grammar already
    /// makes a constant a symbol under another kind. Nothing is added for
    /// those: a second capture over the same span leaves two rows for one
    /// declaration, each the other's innermost enclosing definition, and
    /// `semlith symbol` would answer a single `const val` with two definitions.
    const WITHOUT_CONSTANTS: &[(&str, &str)] = &[
        (
            "css",
            "a custom property is a variable a later rule can redefine",
        ),
        (
            "dart",
            "already a symbol; the bundled query calls it a variable",
        ),
        (
            "dockerfile",
            "ARG and ENV are build variables, overridable at build time",
        ),
        (
            "elm",
            "every binding is immutable, so none of them is the constant",
        ),
        ("graphql", "a schema names types and fields, never a value"),
        (
            "haskell",
            "every binding is immutable, so none of them is the constant",
        ),
        ("html", "markup, with no declaration of any kind"),
        (
            "json",
            "data; a member is a key and a value, not a declaration",
        ),
        (
            "kotlin",
            "already a symbol; `const val` is a property to the grammar",
        ),
        (
            "makefile",
            "a variable can be overridden on the command line",
        ),
        ("markdown", "prose"),
        (
            "nix",
            "a `let` or attribute binding is already a `binding` symbol",
        ),
        (
            "ocaml",
            "every `let` binding is immutable, so none of them is the constant",
        ),
        (
            "powershell",
            "a constant is `Set-Variable -Option Constant`, a call and not syntax",
        ),
        (
            "proto",
            "an enum value is a member of an enum, not a declared constant",
        ),
        (
            "r",
            "the language has no constant construct; `<-` binds and rebinds",
        ),
        (
            "sql",
            "there is no `CREATE CONSTANT`; a literal is written where it is used",
        ),
        (
            "svelte",
            "the grammar reads the markup and hands back the script as raw text",
        ),
        (
            "swift",
            "already a symbol; the bundled query calls `let` a property",
        ),
        (
            "terraform",
            "a local or a variable is a value HCL evaluates, not a constant",
        ),
        ("toml", "data; a key and a value, not a declaration"),
        (
            "vue",
            "the grammar reads the template and hands back the script as raw text",
        ),
        ("yaml", "data; a key and a value, not a declaration"),
        (
            "zig",
            "already a symbol; our own query calls `const` a variable",
        ),
    ];

    fn fixture_root() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/graph")
    }

    /// Prints each fixture's parse tree, for writing a tags query against a
    /// grammar whose node names nobody has memorised.
    ///
    /// ```sh
    /// cargo test --lib dump_fixture_trees -- --ignored --nocapture
    /// ```
    #[test]
    #[ignore = "a tool for writing queries, not a gate"]
    fn dump_fixture_trees() {
        let root = fixture_root();
        let mut languages: Vec<_> = crate::filter::LANGUAGES.iter().map(|e| e.name).collect();
        languages.sort_unstable();
        for name in languages {
            let dir = root.join(name);
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries {
                let path = entry.unwrap().path();
                let text = std::fs::read_to_string(&path).unwrap();
                let Some((language, _)) = grammar(name) else {
                    continue;
                };
                let mut parser = Parser::new();
                parser.set_language(&language).unwrap();
                let tree = parser.parse(&text, None).unwrap();
                println!(
                    "===== {name} :: {} =====\n{}",
                    path.file_name().unwrap().to_string_lossy(),
                    tree.root_node().to_sexp()
                );
            }
        }
    }

    /// Prints what each fixture actually extracts, for comparing against the
    /// row that declares what it should.
    ///
    /// ```sh
    /// cargo test --lib dump_fixture_extractions -- --ignored --nocapture
    /// ```
    #[test]
    #[ignore = "a tool for writing queries, not a gate"]
    fn dump_fixture_extractions() {
        let root = fixture_root();
        for fixture in FIXTURES {
            let text = std::fs::read_to_string(root.join(fixture.file)).unwrap();
            let e = extract(std::path::Path::new(fixture.file), &text)
                .unwrap()
                .unwrap();
            println!("===== {} =====", fixture.language);
            for s in &e.symbols {
                println!(
                    "  symbol {:14} {:24} {}-{}",
                    s.kind, s.name, s.start_line, s.end_line
                );
            }
            for x in &e.edges {
                println!(
                    "  edge   {:14} {} -> {} (line {:?})",
                    x.kind, x.from, x.to, x.line
                );
            }
        }
    }

    /// Every language the filter advertises has a fixture, so no grammar is
    /// wired up without something proving it extracts.
    #[test]
    fn every_advertised_language_has_a_fixture() {
        for entry in crate::filter::LANGUAGES {
            if WITHOUT_GRAMMAR.iter().any(|(name, _)| *name == entry.name) {
                continue;
            }
            assert!(
                FIXTURES.iter().any(|f| f.language == entry.name),
                "{} has a grammar but no fixture asserting what it extracts",
                entry.name
            );
        }
    }

    /// Every language with a construct for a named constant extracts one, and
    /// proves it from a fixture written in that language.
    ///
    /// Until 0.23.0 this held for Rust alone. The other forty-five advertised
    /// a graph and then answered `semlith symbol MAX_HOLDERS` with nothing, so
    /// the definition lift could not fire for the one kind of name an agent is
    /// most likely to type verbatim. The escape hatch is [`WITHOUT_CONSTANTS`],
    /// and it costs a sentence saying which language and why — "there was no
    /// time" is not a row anybody can write here.
    #[test]
    fn every_language_with_a_constant_construct_extracts_one() {
        for entry in crate::filter::LANGUAGES {
            let fixture = FIXTURES
                .iter()
                .find(|f| f.language == entry.name)
                .unwrap_or_else(|| panic!("{} has no fixture", entry.name));
            let declares = fixture.symbols.iter().any(|(_, kind)| *kind == "constant");
            match WITHOUT_CONSTANTS
                .iter()
                .find(|(name, _)| *name == entry.name)
            {
                Some((_, why)) => assert!(
                    !declares,
                    "{} is listed as extracting no constant ({why}) but its fixture declares one",
                    entry.name
                ),
                None => assert!(
                    declares,
                    "{} has a constant construct but no fixture proves one is extracted",
                    entry.name
                ),
            }
        }
    }

    /// Each language's fixture yields the symbols and edges its row declares.
    #[test]
    fn every_fixture_yields_what_it_declares() {
        let root = fixture_root();
        let mut wrong: Vec<String> = Vec::new();
        for fixture in FIXTURES {
            let path = root.join(fixture.file);
            let text = std::fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("{} is missing: {e}", path.display()));
            let extraction = extract(std::path::Path::new(fixture.file), &text)
                .unwrap_or_else(|e| panic!("{}: extraction failed: {e}", fixture.language))
                .unwrap_or_else(|| {
                    panic!(
                        "{}: no extractor reached {} — the extension is not in the table",
                        fixture.language, fixture.file
                    )
                });

            for (name, kind) in fixture.symbols {
                if !extraction
                    .symbols
                    .iter()
                    .any(|s| s.name == *name && s.kind == *kind)
                {
                    wrong.push(format!(
                        "{}: no {kind} named {name}; found {:?}",
                        fixture.language,
                        extraction
                            .symbols
                            .iter()
                            .map(|s| (&s.kind, &s.name))
                            .collect::<Vec<_>>()
                    ));
                }
            }

            for (from, to, kind) in fixture.edges {
                if !extraction
                    .edges
                    .iter()
                    .any(|e| e.from == *from && e.to == *to && e.kind == *kind)
                {
                    wrong.push(format!(
                        "{}: no {kind} edge {from} -> {to}; found {:?}",
                        fixture.language,
                        extraction
                            .edges
                            .iter()
                            .map(|e| (&e.from, &e.kind, &e.to))
                            .collect::<Vec<_>>()
                    ));
                }
            }
        }
        assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    }

    /// Every language the product advertises really parses, so the About page's
    /// list cannot claim a language the binary does not carry.
    ///
    /// This is the one-table rule as a test. The set is
    /// `filter::LANGUAGES` — what `--language` accepts and what the About page
    /// prints — and the only permitted gap is a row named in
    /// [`WITHOUT_GRAMMAR`] with its reason. Adding a language to the filter
    /// without a grammar fails here rather than shipping a language that
    /// filters but does not graph.
    #[test]
    fn every_advertised_language_has_a_working_grammar() {
        // Collected rather than asserted one at a time: with forty-six
        // languages, failing on the first one turns a ten-minute fix into
        // forty-six runs.
        let mut broken: Vec<String> = Vec::new();
        for entry in crate::filter::LANGUAGES {
            let lang = entry.name;
            if let Some((_, why)) = WITHOUT_GRAMMAR.iter().find(|(name, _)| *name == lang) {
                assert!(
                    grammar(lang).is_none(),
                    "{lang} is listed as having no grammar ({why}) but has one"
                );
                continue;
            }
            let Some((language, tags)) = grammar(lang) else {
                broken.push(format!("{lang}: advertised but has no grammar"));
                continue;
            };
            let mut parser = Parser::new();
            if let Err(e) = parser.set_language(&language) {
                broken.push(format!("{lang}: grammar is ABI-incompatible: {e}"));
                continue;
            }
            if let Err(e) = Query::new(&language, tags) {
                broken.push(format!("{lang}: tags query does not compile: {e:?}"));
            }
            let supplement = supplement(lang);
            if !supplement.is_empty()
                && let Err(e) = Query::new(&language, supplement)
            {
                broken.push(format!("{lang}: supplement does not compile: {e:?}"));
            }
        }
        assert!(broken.is_empty(), "{}", broken.join("\n"));
    }

    /// A file being saved mid-edit is the normal case under the watcher.
    #[test]
    fn a_file_that_does_not_parse_yields_what_it_could_read() {
        let e = run("a.rs", "fn good() {}\nfn broken( {\n");
        assert!(e.symbols.iter().any(|s| s.name == "good"));
    }

    /// The line an edge carries is the line the call was written on, not the
    /// line the function that contains it starts on. Those are the same only
    /// for a one-line function, which is why the fixture's call sits four
    /// lines below its `fn`.
    #[test]
    fn a_reference_edge_carries_the_line_the_call_was_written_on() {
        let e = run(
            "a.rs",
            "use other::helper;\n\nfn caller() {\n    let x = 1;\n    let _ = x;\n    helper();\n}\n",
        );
        let call = e
            .edges
            .iter()
            .find(|x| x.kind == "calls" && x.to == "helper")
            .unwrap_or_else(|| panic!("no call edge: {:?}", e.edges));
        assert_eq!(call.line, Some(6), "{:?}", e.edges);

        let import = e
            .edges
            .iter()
            .find(|x| x.kind == "imports")
            .unwrap_or_else(|| panic!("no import edge: {:?}", e.edges));
        assert_eq!(import.line, Some(1), "{:?}", e.edges);

        // Nothing this release extracts may leave the column empty: a NULL is
        // reserved for a row an older binary wrote.
        assert!(e.edges.iter().all(|x| x.line.is_some()), "{:?}", e.edges);
    }

    /// A re-export is the only thing between the name a caller wrote and the
    /// definition it meant. Each language records the alias as a symbol of its
    /// own and an `aliases` edge from it to the bare name it stands for.
    #[test]
    fn an_alias_becomes_a_symbol_and_an_edge_to_what_it_stands_for() {
        let rust = run("a.rs", "pub use store::Semlith as Store;\n");
        assert!(
            rust.symbols.iter().any(|s| s.name == "Store"),
            "{:?}",
            rust.symbols
        );
        assert!(
            has_edge(&rust, "Store", "Semlith", "aliases"),
            "{:?}",
            rust.edges
        );

        let py = run("a.py", "from x import search as find\n");
        assert!(has_edge(&py, "find", "search", "aliases"), "{:?}", py.edges);

        let ts = run("a.ts", "import { search as find } from './x';\n");
        assert!(has_edge(&ts, "find", "search", "aliases"), "{:?}", ts.edges);

        let go = run("a.go", "package m\nimport fp \"path/filepath\"\n");
        assert!(has_edge(&go, "fp", "filepath", "aliases"), "{:?}", go.edges);
    }

    /// A re-export that does not rename has nothing to cross: the alias and
    /// the definition are one name, and a self-edge would be noise.
    #[test]
    fn a_re_export_that_does_not_rename_adds_no_alias_edge() {
        let e = run("a.rs", "pub use store::Semlith;\n");
        assert!(
            !e.edges.iter().any(|x| x.kind == "aliases"),
            "{:?}",
            e.edges
        );
    }

    #[test]
    fn recursion_does_not_produce_a_self_edge() {
        let e = run("a.rs", "fn loops() { loops(); }\n");
        assert!(!has_edge(&e, "loops", "loops", "calls"), "{:?}", e.edges);
    }

    // ------------------------------------------------------------ traversal

    /// A chain `a -> b -> c -> d`, plus `e -> d`, in one in-memory store.
    fn chain() -> rusqlite::Connection {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        let file = crate::store::insert_file(&db, "a.rs", "h", 1, 0).unwrap();
        let mut id = std::collections::HashMap::new();
        for name in ["a", "b", "c", "d", "e", "lonely"] {
            let symbol = Symbol {
                kind: "function".to_string(),
                name: name.to_string(),
                qualified: name.to_string(),
                start_line: 1,
                end_line: 2,
            };
            id.insert(
                name,
                crate::store::insert_symbol(&db, file, None, &symbol).unwrap(),
            );
        }
        for (from, to) in [("a", "b"), ("b", "c"), ("c", "d"), ("e", "d")] {
            crate::store::insert_edge(&db, id[from], to, "calls", EXTRACTED, None, None).unwrap();
        }
        db
    }

    /// Two repositories in one store, each with its own `run` and its own
    /// caller of it. Scoped to one, every graph answer names that repository
    /// only -- the definition, the caller, the reached row -- and unscoped it
    /// names both, as before.
    #[test]
    fn a_scope_keeps_a_namesake_in_another_repository_out() {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        for repo in ["one", "two"] {
            let file =
                crate::store::insert_file(&db, &format!("/w/{repo}/x.rs"), "h", 1, 0).unwrap();
            let mut ids = Vec::new();
            for (name, line) in [("run", 1), (format!("go_{repo}").as_str(), 5)] {
                let symbol = Symbol {
                    kind: "function".to_string(),
                    name: name.to_string(),
                    qualified: name.to_string(),
                    start_line: line,
                    end_line: line + 2,
                };
                ids.push(crate::store::insert_symbol(&db, file, None, &symbol).unwrap());
            }
            crate::store::insert_edge(&db, ids[1], "run", "calls", EXTRACTED, None, None).unwrap();
        }
        let filter = crate::filter::Filter::new(&["one/**".to_string()], &[], &[]).unwrap();
        let scope = Scope::of(&db, &filter).unwrap();
        let names = |ends: &[crate::store::EdgeEnd]| {
            let mut n: Vec<String> = ends.iter().map(|e| e.symbol.name.clone()).collect();
            n.sort();
            n
        };

        let around = neighbours(&db, "run", &[], true, &scope).unwrap();
        assert_eq!(names(&around.callers), ["go_one"]);
        let everywhere = neighbours(&db, "run", &[], true, &Scope::all()).unwrap();
        assert_eq!(names(&everywhere.callers), ["go_one", "go_two"]);

        let reach = impact(&db, "run", &[], 3, false, &scope).unwrap();
        assert!(
            reach.definitions.iter().all(|d| d.path.contains("/one/")),
            "{reach:?}"
        );
        assert!(
            reach.reached.iter().all(|r| r.path.contains("/one/")),
            "{reach:?}"
        );
        assert!(
            reach.reached.iter().any(|r| r.name == "go_one"),
            "{reach:?}"
        );

        let rows = signatures(&db, &["run".to_string()], &scope).unwrap();
        assert_eq!(rows.len(), 1, "{rows:?}");
        assert!(rows[0].symbol.path.contains("/one/"));

        let found = evidence(&db, "run", &[], 20, true, &scope).unwrap();
        assert!(found.definitions.iter().all(|d| d.path.contains("/one/")));
        assert_eq!(names(&found.callers), ["go_one"]);
    }

    /// The block is one reply where 0.15.0 needed three, and the second ring
    /// is walked only through names the first ring settled — an ambiguous name
    /// is several unrelated definitions, and expanding one would put somebody
    /// else's callers into this symbol's context.
    #[test]
    fn the_evidence_block_carries_the_definition_both_rings_and_no_ambiguity() {
        let db = chain();
        let found = evidence(&db, "b", &dependency_kinds(), 20, false, &Scope::all()).unwrap();

        assert_eq!(found.name, "b");
        assert!(!found.definitions.is_empty(), "{found:?}");
        assert!(
            found.callers.iter().any(|e| e.symbol.name == "a"),
            "{:?}",
            found.callers
        );
        assert!(
            found.callees.iter().any(|e| e.symbol.name == "c"),
            "{:?}",
            found.callees
        );
        // `d` is two hops from `b`, through `c`.
        assert!(
            found.ego.iter().any(|h| h.name == "d" && h.via == "c"),
            "{:?}",
            found.ego
        );
        // The centre and the first ring are not in the second ring.
        assert!(
            found
                .ego
                .iter()
                .all(|h| h.name != "b" && h.name != "a" && h.name != "c"),
            "{:?}",
            found.ego
        );
        assert!(
            found.ego.len() <= EGO_LIMIT,
            "the ring is context, not an answer: {:?}",
            found.ego
        );

        let text = found.render("", "", &verbatim);
        assert!(text.contains("callers"), "{text}");
        assert!(text.contains("callees"), "{text}");
        assert!(text.contains("two hops out"), "{text}");
    }

    #[test]
    fn neighbours_separates_the_two_directions() {
        let db = chain();
        let n = neighbours(&db, "d", &[], false, &Scope::all()).unwrap();
        let mut callers: Vec<&str> = n.callers.iter().map(|e| e.symbol.name.as_str()).collect();
        callers.sort_unstable();
        assert_eq!(callers, ["c", "e"], "both callers of d");
        assert!(n.callees.is_empty(), "d calls nothing");
    }

    /// A cycle terminates rather than looping: the traversal marks a name seen
    /// before it expands it, so d -> a -> b -> c -> d ends.
    #[test]
    fn a_cycle_terminates_instead_of_looping() {
        let db = chain();
        let file = crate::store::insert_file(&db, "b.rs", "h", 1, 0).unwrap();
        let symbol = Symbol {
            kind: "function".to_string(),
            name: "d".to_string(),
            qualified: "d".to_string(),
            start_line: 1,
            end_line: 2,
        };
        let d = crate::store::insert_symbol(&db, file, None, &symbol).unwrap();
        crate::store::insert_edge(&db, d, "a", "calls", EXTRACTED, None, None).unwrap();
        // d -> a -> b -> c -> d is now a cycle; a large depth must still return.
        let path = shortest_path(&db, "a", "d", 50, false).unwrap();
        assert!(path.is_some(), "a still reaches d");
        assert!(
            path.unwrap().steps.len() <= 4,
            "a cycle inflated the shortest path"
        );
    }

    #[test]
    fn the_shortest_path_is_the_short_one_and_names_every_edge() {
        let db = chain();
        let path = shortest_path(&db, "a", "d", 10, false)
            .unwrap()
            .expect("a reaches d");
        let hops: Vec<(&str, &str)> = path
            .steps
            .iter()
            .map(|s| (s.from.as_str(), s.to.as_str()))
            .collect();
        assert_eq!(hops, [("a", "b"), ("b", "c"), ("c", "d")]);
        assert!(path.steps.iter().all(|s| s.kind == "calls"));
        assert!(path.steps.iter().all(|s| s.confidence == EXTRACTED));
        assert!(path.steps.iter().all(|s| !s.to_path.is_empty()));
        assert_eq!(path.summary.extracted, 3);
        assert_eq!(path.summary.seams, 0);
        assert!(!path.summary.hypothesis, "every hop is extracted");
    }

    /// The shape the release exists for: `start` calls `record`, and `record`
    /// is two unrelated functions in two files. One of them calls `finish`.
    ///
    /// The 0.14.0 finder walked out of one `record` and into the other without
    /// a word, and printed `start -> record -> finish` in the same format a
    /// real chain prints in.
    fn forked_name() -> rusqlite::Connection {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        let define = |db: &rusqlite::Connection, path: &str, name: &str, line: u32| {
            let file = crate::store::insert_file(db, path, path, 1, 0).unwrap_or_else(|_| {
                db.query_row("SELECT id FROM files WHERE path = ?1", [path], |r| r.get(0))
                    .unwrap()
            });
            let symbol = Symbol {
                kind: "function".to_string(),
                name: name.to_string(),
                qualified: name.to_string(),
                start_line: line,
                end_line: line + 1,
            };
            crate::store::insert_symbol(db, file, None, &symbol).unwrap()
        };
        let start = define(&db, "src/start.rs", "start", 10);
        define(&db, "src/one.rs", "record", 20);
        let second = define(&db, "src/two.rs", "record", 30);
        define(&db, "src/finish.rs", "finish", 40);

        // `start` calls a `record`, and nothing in its source says which.
        crate::store::insert_edge(&db, start, "record", "calls", INFERRED, None, None).unwrap();
        // Only the second `record` reaches `finish`.
        crate::store::insert_edge(&db, second, "finish", "calls", INFERRED, None, None).unwrap();
        db
    }

    /// By default the finder will not cross a name it cannot pin down, so the
    /// answer is that there is no chain. This is the central correction of the
    /// release: no answer beats a wrong answer dressed as a right one.
    #[test]
    fn a_chain_through_an_ambiguous_name_is_not_walked_by_default() {
        let db = forked_name();
        assert!(
            shortest_path(&db, "start", "finish", 6, false)
                .unwrap()
                .is_none(),
            "the only route crosses a name with two definitions"
        );
    }

    /// With `all_edges` the chain comes back, and every part of it says what
    /// it is worth: the hop is ambiguous, the join is a seam, the trailer
    /// counts it, and the sentence names it a hypothesis.
    #[test]
    fn the_same_chain_with_all_edges_is_labelled_rather_than_asserted() {
        let db = forked_name();
        let chain = shortest_path(&db, "start", "finish", 6, true)
            .unwrap()
            .expect("all_edges walks the ambiguous name");

        assert_eq!(chain.steps.len(), 2);
        assert_eq!(chain.steps[0].confidence, AMBIGUOUS);
        assert_eq!(chain.steps[0].definitions, 2);
        assert_eq!(chain.summary.seams, 1, "{:?}", chain.steps);
        assert_eq!(
            chain.summary.ambiguous_names,
            vec![("record".to_string(), 2)]
        );
        assert!(chain.summary.hypothesis);

        let rendered = chain.render("", "", &verbatim);
        assert!(rendered.contains("seam"), "{rendered}");
        assert!(rendered.contains("record: 2 definitions"), "{rendered}");
        assert!(
            rendered.contains("A hypothesis, not a finding."),
            "{rendered}"
        );
        assert!(
            rendered.contains("src/start.rs:10"),
            "every hop shows both endpoints: {rendered}"
        );
    }

    /// A chain with nothing to doubt says nothing about doubt. The trailer is
    /// still printed, because a reader should not have to know that silence
    /// means "all extracted".
    #[test]
    fn an_all_extracted_chain_carries_no_hypothesis_line() {
        let db = chain();
        let rendered = shortest_path(&db, "a", "d", 10, false)
            .unwrap()
            .expect("a reaches d")
            .render("", "", &verbatim);
        assert!(!rendered.contains("hypothesis"), "{rendered}");
        assert!(!rendered.contains("seam"), "{rendered}");
        assert!(rendered.contains("3 hops"), "{rendered}");
        assert!(rendered.contains("3 extracted"), "{rendered}");
    }

    /// The refusal and the failure are different sentences, because they are
    /// different answers, and only one of them has a flag that widens it.
    #[test]
    fn the_refusal_names_the_flag_that_widens_the_question() {
        let strict = not_connected("a", "b", 6, false);
        assert!(strict.contains("by resolved edges"), "{strict}");
        assert!(strict.contains("--all-edges"), "{strict}");

        let walked = not_connected("a", "b", 6, true);
        assert!(walked.contains("any edge in the store"), "{walked}");
        assert!(!walked.contains("--all-edges"), "{walked}");
    }

    /// Not connected is an answer, and so is not connected *within this depth*.
    #[test]
    fn an_unconnected_pair_returns_nothing_rather_than_erroring() {
        let db = chain();
        assert!(
            shortest_path(&db, "a", "lonely", 10, false)
                .unwrap()
                .is_none()
        );
        assert!(
            shortest_path(&db, "a", "d", 2, false).unwrap().is_none(),
            "d is three hops away, so a depth of two does not reach it"
        );
    }
}

/// The 2026-10-14 audit's graph defects (G1-G11 and item 30 of 0.42.0), each
/// replayed on a cut-down copy of the file the audit read, indexed under the
/// path it had there. Red on 0.41.x; the audit is
/// `full-regression-drive/14-10-2026/findings.md`.
#[cfg(test)]
mod audit_tests {
    use super::*;

    fn fixture(name: &str) -> String {
        let root =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/graph-audit");
        std::fs::read_to_string(root.join(name)).unwrap()
    }

    /// A store holding each fixture under the path the audit indexed it at,
    /// written by the writer `index_set` uses.
    fn store(files: &[(&str, &str)]) -> rusqlite::Connection {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        for (path, name) in files {
            let text = fixture(name);
            let file = crate::store::insert_file(&db, path, path, text.len() as u64, 0).unwrap();
            let e = extract(Path::new(path), &text).unwrap().unwrap();
            crate::store::write_extraction(&db, &e, file, &[]).unwrap();
        }
        db
    }

    fn ripgrep() -> rusqlite::Connection {
        store(&[
            ("crates/core/main.rs", "rust/ripgrep_main.rs"),
            ("crates/ignore/src/walk.rs", "rust/ripgrep_walk.rs"),
            ("crates/core/index/enabled.rs", "rust/ripgrep_enabled.rs"),
            ("crates/core/search.rs", "rust/ripgrep_search.rs"),
        ])
    }

    fn flask() -> rusqlite::Connection {
        store(&[
            ("src/flask/app.py", "python/flask_app.py"),
            ("src/flask/helpers.py", "python/flask_helpers.py"),
            ("src/flask/__init__.py", "python/flask_init.py"),
            ("tests/test_basic.py", "python/flask_test_basic.py"),
        ])
    }

    /// G1: `.build_parallel().run(||` is `WalkParallel::run`, and the audit got
    /// `main::run` "resolved". A method call never resolves to a free
    /// function, and a receiver nothing types leaves the edge ambiguous —
    /// `clone`, `clear` and `unwrap` the same.
    #[test]
    fn a_method_call_is_never_resolved_to_a_free_function() {
        let db = ripgrep();
        for from in ["search_parallel", "files_parallel"] {
            let out = crate::store::edges_out(&db, from, &dependency_kinds()).unwrap();
            for to in ["run", "clone", "clear", "unwrap"] {
                for e in out.iter().filter(|e| e.symbol.name == to) {
                    assert_eq!(
                        e.confidence, AMBIGUOUS,
                        "{from} -> {to} settled on {}:{} ({})",
                        e.symbol.path, e.symbol.start_line, e.symbol.qualified
                    );
                    assert!(
                        e.symbol.qualified != "main::run",
                        "{from} -> {to} names the free fn main::run"
                    );
                }
            }
            // `searcher.search(&result)` is a method, never the module search.rs.
            assert!(
                out.iter().all(|e| e.symbol.kind != "module"),
                "{from}: {out:?}"
            );
        }
    }

    /// G1: on that edge `path files_parallel search_parallel` printed a 2-hop
    /// "resolved" chain and trace cited main.rs:301 as a supporting fact.
    #[test]
    fn no_path_or_trace_crosses_an_untyped_method_call() {
        let db = ripgrep();
        let chain = shortest_path(&db, "files_parallel", "search_parallel", 6, false).unwrap();
        assert!(chain.is_none(), "{chain:?}");
        let t = trace(
            "files_parallel",
            "search_parallel",
            6,
            false,
            chain,
            |_, _| None,
            &verbatim,
        );
        assert!(
            t.lines.iter().all(|l| l.mark != "supporting fact"),
            "{:?}",
            t.lines
        );
    }

    /// `mod search;` beside `fn search` in main.rs made the bare call
    /// `search(&args, mode)` a tie: a call never means a module.
    #[test]
    fn a_call_never_means_a_module() {
        let db = ripgrep();
        let out = crate::store::edges_out(&db, "run", &dependency_kinds()).unwrap();
        let search: Vec<_> = out.iter().filter(|e| e.symbol.name == "search").collect();
        assert_eq!(search.len(), 1, "{search:?}");
        assert_eq!(search[0].confidence, RESOLVED, "{search:?}");
        assert_eq!(search[0].symbol.kind, "function", "{search:?}");
        let n = neighbours(&db, "search", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers
                .iter()
                .any(|c| c.symbol.name == "run" && c.confidence == RESOLVED),
            "{:?}",
            n.callers
        );
    }

    /// G2: `crate::search_parallel(args, mode)` on enabled.rs:14 is a caller.
    #[test]
    fn a_call_through_crate_is_a_caller() {
        let db = ripgrep();
        let n = neighbours(&db, "search_parallel", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers.iter().any(|c| c.symbol.name == "read"
                && c.symbol.path == "crates/core/index/enabled.rs"
                && c.line == Some(14)),
            "{:?}",
            n.callers
        );
    }

    /// G2: helpers.py `make_response` calls `current_app.make_response(args)`
    /// — another receiver's method of the same name, not itself.
    #[test]
    fn a_namesake_called_on_another_receiver_is_not_recursion() {
        let db = flask();
        let n = neighbours(&db, "Flask.make_response", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers
                .iter()
                .any(|c| c.symbol.path == "src/flask/helpers.py"
                    && c.symbol.name == "make_response"
                    && c.line == Some(27)),
            "{:?}",
            n.callers
        );
    }

    /// G3: the file `main.rs` and `fn main` share a name, and the module's
    /// `defines` edges were written onto `fn main` and printed as "call at
    /// line N" with N the definition's own line.
    #[test]
    fn a_module_edge_sits_on_the_module_and_is_not_a_call() {
        let db = ripgrep();
        let into =
            crate::store::edges_in(&db, "search_parallel", &["defines".to_string()]).unwrap();
        assert!(!into.is_empty());
        for e in &into {
            assert_eq!(e.symbol.kind, "module", "{e:?}");
            let site = call_site(e, &verbatim);
            assert!(!site.contains("call"), "{site}");
        }
        let main = crate::store::edges_out(&db, "main", &["defines".to_string()]).unwrap();
        assert!(!main.is_empty());
        assert!(main.iter().all(|e| e.from_line == Some(1)), "{main:?}");
    }

    /// G8: one edge, one confidence, whichever command shows it
    /// (test_basic.py `flask.make_response()`: impact said ambiguous,
    /// neighbors said inferred).
    #[test]
    fn neighbors_and_impact_give_one_edge_one_confidence() {
        let db = flask();
        let n = neighbours(&db, "make_response", &[], false, &Scope::all()).unwrap();
        let reach = impact(&db, "make_response", &[], 1, false, &Scope::all()).unwrap();
        let caller = n
            .callers
            .iter()
            .find(|c| c.symbol.name == "test_make_response")
            .expect("test_make_response calls make_response");
        let row = reach
            .reached
            .iter()
            .find(|r| r.name == "test_make_response")
            .expect("impact reaches test_make_response");
        assert_eq!(caller.confidence, row.confidence);
    }

    /// G4: `BaseResponse::Flask`, `t::Config`, `ft::Blueprint`: a top-level
    /// definition is owned by its module, never by an import alias.
    #[test]
    fn a_python_definition_is_not_owned_by_an_import_alias() {
        let e = extract(
            Path::new("src/flask/app.py"),
            &fixture("python/flask_app.py"),
        )
        .unwrap()
        .unwrap();
        let flask = e.symbols.iter().find(|s| s.name == "Flask").unwrap();
        assert_eq!(flask.qualified, "app::Flask");
        let method = e
            .symbols
            .iter()
            .find(|s| s.name == "make_response")
            .unwrap();
        assert_eq!(method.qualified, "Flask::make_response");
        for s in &e.symbols {
            for alias in ["BaseResponse::", "t::", "ft::", "cabc::", "_url_quote::"] {
                assert!(!s.qualified.starts_with(alias), "{s:?}");
            }
        }
        assert!(
            !e.edges
                .iter()
                .any(|x| x.kind == "contains"
                    && ["BaseResponse", "t", "ft"].contains(&x.from.as_str())),
            "{:?}",
            e.edges
        );
    }

    /// G5: an alias row is its import line, not `__init__.py:1-40` for a
    /// 39-line file.
    #[test]
    fn an_alias_row_is_its_import_line() {
        let e = extract(
            Path::new("src/flask/__init__.py"),
            &fixture("python/flask_init.py"),
        )
        .unwrap()
        .unwrap();
        for (name, line) in [("Flask", 2), ("make_response", 17), ("url_for", 22)] {
            let s = e
                .symbols
                .iter()
                .find(|s| s.name == name && s.kind == "alias")
                .unwrap_or_else(|| panic!("no alias {name}"));
            assert_eq!((s.start_line, s.end_line), (line, line), "{s:?}");
        }
    }

    /// G6: setext headings (an underline of `===` or `---`) are headings: the
    /// ripgrep CHANGELOG's gave `1-1871` past the end of the file, and a body
    /// line belonged to no section or the wrong one.
    #[test]
    fn setext_headings_define_their_own_sections() {
        let text = fixture("markdown/ripgrep_changelog.md");
        let lines = text.lines().count() as u32;
        let e = extract(Path::new("CHANGELOG.md"), &text).unwrap().unwrap();
        let headings: Vec<&Symbol> = e.symbols.iter().filter(|s| s.kind == "heading").collect();
        let titles: Vec<&str> = headings.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(
            titles,
            [
                "TBD",
                "15.2.0 (2026-07-15)",
                "15.1.0 (2025-10-22)",
                "15.0.0 (2025-10-15)",
                "12.1.1 (2020-05-29)"
            ]
        );
        let spans: Vec<(u32, u32)> = headings
            .iter()
            .map(|s| (s.start_line, s.end_line))
            .collect();
        assert_eq!(spans, [(1, 5), (6, 35), (36, 53), (54, 65), (66, lines)]);
        for h in &headings {
            assert_eq!(h.qualified, format!("CHANGELOG::{}", h.name), "{h:?}");
        }
    }

    /// The census `stats` prints counts a call through a receiver the way the
    /// resolver settles it: ripgrep's `searcher.clone()` was "resolved"
    /// because the store held one `clone`, a method of another type.
    #[test]
    fn the_census_counts_an_untyped_method_call_as_ambiguous() {
        let dir = tempfile::tempdir().unwrap();
        let db = crate::store::open(&dir.path().join("store.db")).unwrap();
        crate::store::read_only(&db, false).unwrap();
        for (path, text) in [
            ("src/a.rs", "fn caller(t: Thing) { t.go(); }\n"),
            (
                "src/b.rs",
                "struct Other;\nimpl Other {\n    fn go(&self) {}\n}\n",
            ),
        ] {
            let file = crate::store::insert_file(&db, path, path, 1, 0).unwrap();
            let e = extract(Path::new(path), text).unwrap().unwrap();
            crate::store::write_extraction(&db, &e, file, &[]).unwrap();
        }
        let rust = crate::store::coverage_by_language(&db)
            .unwrap()
            .into_iter()
            .find(|r| r.language == "rust")
            .unwrap();
        assert_eq!((rust.resolved, rust.ambiguous), (0, 1), "{rust:?}");
        let out = crate::store::edges_out(&db, "caller", &[]).unwrap();
        assert!(out.iter().all(|e| e.confidence == AMBIGUOUS), "{out:?}");
    }

    /// flask's tests call `flask.Flask(...)`, and the checkout's own folder
    /// is `flask`: the folder named every candidate, so a test's subclass of
    /// `Flask` won as "extracted" on 72 edges of the audit's store.
    #[test]
    fn a_folder_both_files_sit_in_names_no_candidate() {
        let db = store(&[
            ("/w/flask/src/flask/app.py", "python/flask_app.py"),
            ("/w/flask/src/flask/__init__.py", "python/flask_init.py"),
            (
                "/w/flask/tests/test_config.py",
                "python/flask_test_config.py",
            ),
            ("/w/flask/tests/test_basic.py", "python/flask_test_basic.py"),
        ]);
        // The 17 left after that: `flask.Flask(...)` beside the subclass, in
        // test_config.py itself. The module path names flask, not this file.
        for from in ["test_response_type_errors", "test_config_from_object"] {
            let out = crate::store::edges_out(&db, from, &[]).unwrap();
            let flask: Vec<_> = out.iter().filter(|e| e.symbol.name == "Flask").collect();
            assert!(!flask.is_empty(), "{from}");
            for e in flask {
                assert!(
                    e.confidence == AMBIGUOUS || e.symbol.path.contains("/src/flask/"),
                    "{from}: {e:?}"
                );
            }
        }
        // A bare `Flask(__name__)` beside the subclass still means it.
        let out = crate::store::edges_out(&db, "test_custom_config_class", &[]).unwrap();
        let own: Vec<_> = out
            .iter()
            .filter(|e| e.symbol.name == "Flask" && e.kind == "calls")
            .collect();
        assert_eq!(own.len(), 1, "{own:?}");
        assert_eq!(own[0].symbol.path, "/w/flask/tests/test_config.py");
    }

    /// A structural edge is the file saying where its own definition sits:
    /// `steps` holding a `run:` key is not a maybe-caller of a Rust `run`,
    /// and a struct's `contains` edge means its own method.
    #[test]
    fn a_structural_edge_means_its_own_file() {
        let db = store(&[
            (".github/workflows/ci.yml", "yaml/ripgrep_ci.yml"),
            ("crates/core/main.rs", "rust/ripgrep_main.rs"),
            ("crates/ignore/src/walk.rs", "rust/ripgrep_walk.rs"),
        ]);
        let n = neighbours(&db, "run", &[], false, &Scope::all()).unwrap();
        let structural: Vec<_> = n
            .callers
            .iter()
            .filter(|c| c.kind == "contains" || c.kind == "defines")
            .collect();
        assert!(!structural.is_empty());
        for c in structural {
            assert_eq!(c.confidence, EXTRACTED, "{c:?}");
        }
        let out = crate::store::edges_out(&db, "steps", &["contains".to_string()]).unwrap();
        assert!(
            out.iter()
                .all(|e| e.symbol.path == ".github/workflows/ci.yml"),
            "{out:?}"
        );
    }

    /// G9, G10: `symbol run -k 3` said "3 definitions" of 52, with nothing
    /// saying the list was cut, and the default list was YAML `run:` keys
    /// ahead of every Rust `run`.
    #[test]
    fn symbol_counts_every_definition_and_lists_code_first() {
        let db = store(&[
            (".github/workflows/ci.yml", "yaml/ripgrep_ci.yml"),
            ("crates/core/main.rs", "rust/ripgrep_main.rs"),
            ("crates/ignore/src/walk.rs", "rust/ripgrep_walk.rs"),
        ]);
        let total = 7 + 2;
        let found = evidence(&db, "run", &dependency_kinds(), 3, false, &Scope::all()).unwrap();
        let kinds: Vec<&str> = found.definitions.iter().map(|d| d.kind.as_str()).collect();
        assert_eq!(
            &kinds[..2],
            ["function", "method"],
            "{:?}",
            found.definitions
        );
        let text = found.render("", "", &verbatim);
        assert!(
            text.contains(&format!("{total} definitions of this name")),
            "{text}"
        );
        assert!(text.contains("3 shown"), "{text}");
        let all = evidence(&db, "run", &dependency_kinds(), 20, false, &Scope::all()).unwrap();
        assert_eq!(all.definitions.len(), total, "{:?}", all.definitions);
        assert!(!all.render("", "", &verbatim).contains("shown"));
    }

    /// G11: several names at once kept a heading out that one name finds.
    #[test]
    fn several_names_answer_with_the_rows_one_name_does() {
        let db = store(&[
            ("CHANGELOG.md", "markdown/ripgrep_changelog.md"),
            ("crates/core/main.rs", "rust/ripgrep_main.rs"),
        ]);
        let one = evidence(&db, "15.2.0 (2026-07-15)", &[], 20, false, &Scope::all()).unwrap();
        assert_eq!(one.definitions.len(), 1);
        let names = [
            "15.2.0 (2026-07-15)".to_string(),
            "search_parallel".to_string(),
        ];
        let rows = signatures(&db, &names, &Scope::all()).unwrap();
        let asked: Vec<&str> = rows.iter().map(|r| r.asked.as_str()).collect();
        assert_eq!(
            asked,
            ["15.2.0 (2026-07-15)", "search_parallel"],
            "{rows:?}"
        );
    }

    /// G7: `symbol --json` printed two "kind" keys per caller, so a parser
    /// kept the edge's and lost the symbol's.
    #[test]
    fn an_edge_end_serialises_one_kind_key() {
        let db = ripgrep();
        let found = evidence(
            &db,
            "search_parallel",
            &dependency_kinds(),
            20,
            false,
            &Scope::all(),
        )
        .unwrap();
        assert!(!found.callers.is_empty());
        let json = serde_json::to_string(&found.callers[0]).unwrap();
        assert_eq!(json.matches("\"kind\":").count(), 1, "{json}");
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(value["symbol_kind"], "function", "{value}");
        assert_eq!(value["kind"], "calls", "{value}");
    }

    /// cobra's completions.go: every name in a `const ( ... )` block spanned
    /// the whole block, so each was qualified by another, and the two being
    /// each other's parent hung the receiver pass until the file was given up
    /// as unparsed. Each name is its own line now.
    #[test]
    fn a_go_const_block_gives_each_name_its_own_line() {
        let text = "package cobra\n\nconst (\n\t// ShellCompRequestCmd is the name of the hidden command.\n\tShellCompRequestCmd = \"__complete\"\n\t// ShellCompNoDescRequestCmd is the name of the other one.\n\tShellCompNoDescRequestCmd = \"__completeNoDesc\"\n)\n\nfunc (c *Command) initCompleteCmd() {\n\tc.AddCommand(ShellCompRequestCmd)\n}\n";
        let e = extract(Path::new("completions.go"), text).unwrap().unwrap();
        for (name, line) in [("ShellCompRequestCmd", 5), ("ShellCompNoDescRequestCmd", 7)] {
            let s = e.symbols.iter().find(|s| s.name == name).unwrap();
            assert_eq!(s.qualified, format!("completions::{name}"), "{s:?}");
            assert_eq!((s.start_line, s.end_line), (line, line), "{s:?}");
        }
    }

    /// Item 30: "Called and not found" was cobra's builtins and standard
    /// library — `Errorf` 198 times, `len`, `append`, `os`.
    #[test]
    fn called_and_not_found_leaves_out_builtins_and_the_standard_library() {
        let db = store(&[("command.go", "go/cobra_command.go")]);
        let (targets, distinct) = crate::store::unresolved_targets(&db, 20).unwrap();
        let names: Vec<&str> = targets.iter().map(|(n, _)| n.as_str()).collect();
        assert!(names.contains(&"validateRequiredFlags"), "{names:?}");
        for builtin in [
            "Errorf",
            "len",
            "append",
            "os",
            "fmt",
            "strings",
            "TrimSpace",
            "Fprintln",
        ] {
            assert!(!names.contains(&builtin), "{builtin} in {names:?}");
        }
        assert_eq!(distinct, names.len() as i64);
        assert!(crate::store::builtin_targets(&db).unwrap() >= 7);
    }
}

/// semlith#245: a free function beside a method of the same name.
///
/// `pub fn lane(id)` and `impl Enabled { fn lane(&self, id) }` both sit in
/// src/accel.rs. A bare `lane(id)` there tied at rank 1, and
/// `crate::accel::lane("ane")` from daemon.rs tied at rank 2, so both callers
/// were ambiguous and the cloud impact check missed them. In a language with
/// no implicit receiver a call that is neither `x.f()` nor `Type::f()` cannot
/// reach a method, so it means the free function.
#[cfg(test)]
mod tie_tests {
    use super::*;

    /// A store holding each `(path, source)` pair, written by the writer
    /// `index_set` uses.
    fn store(files: &[(&str, &str)]) -> rusqlite::Connection {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        crate::store::prepare_for_tests(&db);
        for (path, text) in files {
            let file = crate::store::insert_file(&db, path, path, text.len() as u64, 0).unwrap();
            let e = extract(Path::new(path), text).unwrap().unwrap();
            crate::store::write_extraction(&db, &e, file, &[]).unwrap();
        }
        db
    }

    const ACCEL: &str = r#"pub fn lane(id: &str) -> Option<u8> {
    if id == "ane" { Some(1) } else { None }
}

pub struct Enabled;

impl Enabled {
    pub fn lane(&self, id: &str) -> bool {
        id == "ane"
    }
}

pub fn warm() {
    lane("ane");
}

fn typed(e: &Enabled) {
    Enabled::lane(e, "x");
}
"#;

    /// `from`'s call to `to` settled on the definition at `path` named
    /// `qualified`, from both ends: `edges_out` from the caller, and the
    /// caller row `neighbours` lists for the callee.
    fn settles_on(db: &rusqlite::Connection, from: &str, to: &str, path: &str, qualified: &str) {
        let out = crate::store::edges_out(db, from, &dependency_kinds()).unwrap();
        let hits: Vec<_> = out.iter().filter(|e| e.symbol.name == to).collect();
        assert_eq!(hits.len(), 1, "{from} -> {to} did not settle: {hits:#?}");
        assert!(
            [RESOLVED, EXTRACTED].contains(&hits[0].confidence.as_str()),
            "{from} -> {to} is {}: {hits:#?}",
            hits[0].confidence
        );
        assert_eq!(
            (
                hits[0].symbol.path.as_str(),
                hits[0].symbol.qualified.as_str()
            ),
            (path, qualified),
            "{from} -> {to}"
        );
        let n = neighbours(db, to, &[], false, &Scope::all()).unwrap();
        let caller: Vec<_> = n.callers.iter().filter(|c| c.symbol.name == from).collect();
        assert_eq!(caller.len(), 1, "{from} as a caller of {to}: {caller:#?}");
        assert!(
            [RESOLVED, EXTRACTED].contains(&caller[0].confidence.as_str()),
            "{from} as a caller of {to} is {}: {caller:#?}",
            caller[0].confidence
        );
        assert_eq!(
            caller[0].means.as_deref(),
            Some(qualified),
            "{from} as a caller of {to}"
        );
    }

    /// semlith#245, in-file: `warm()` calls `lane("ane")` beside both the free
    /// `accel::lane` and `Enabled::lane`. Rust has no implicit `self`, so the
    /// bare call is the free function.
    #[test]
    fn rust_bare_call_beside_a_method_means_the_free_function() {
        let db = store(&[("src/accel.rs", ACCEL)]);
        settles_on(&db, "warm", "lane", "src/accel.rs", "accel::lane");
    }

    /// semlith#245, from daemon.rs: `crate::accel::lane("ane")` names
    /// accel.rs, which holds both `lane`s; a module path never reaches a
    /// method, so `run` is a resolved caller of the free function.
    #[test]
    fn rust_module_path_call_means_the_free_function() {
        let db = store(&[
            ("src/accel.rs", ACCEL),
            (
                "src/daemon.rs",
                "fn run() {\n    crate::accel::lane(\"ane\");\n}\n",
            ),
        ]);
        settles_on(&db, "run", "lane", "src/accel.rs", "accel::lane");
    }

    /// semlith#245, cross-root: the cloud worker calls
    /// `semlith::accel::lane("remote")` from another repository root.
    #[test]
    fn rust_module_path_call_from_another_root_means_the_free_function() {
        let db = store(&[
            ("semlith/src/accel.rs", ACCEL),
            (
                "semlith-cloud/src/bin/worker.rs",
                "fn warm_remote() {\n    semlith::accel::lane(\"remote\");\n}\n",
            ),
        ]);
        settles_on(
            &db,
            "warm_remote",
            "lane",
            "semlith/src/accel.rs",
            "accel::lane",
        );
    }

    const PYTHON_M: &str = "def f():\n    return 1\n\n\nclass C:\n    def f(self):\n        return 2\n\n\ndef g():\n    f()\n";

    /// Python reaches a method only through `self.f()` or `C.f()`: a bare
    /// `f()` in m.py, beside `def f()` and `class C: def f(self)`, is the
    /// module's function. Python records the method as a function owned by
    /// `C` (`C::f`).
    #[test]
    fn python_bare_call_beside_a_method_means_the_free_function() {
        let db = store(&[("pkg/m.py", PYTHON_M)]);
        settles_on(&db, "g", "f", "pkg/m.py", "m::f");
    }

    /// `from m import f` imports the module's function, never `C.f`: both sat
    /// in the imported file and tied at rank 3.
    #[test]
    fn python_imported_bare_call_means_the_free_function() {
        let db = store(&[
            ("pkg/m.py", PYTHON_M),
            ("pkg/user.py", "from m import f\n\n\ndef h():\n    f()\n"),
        ]);
        settles_on(&db, "h", "f", "pkg/m.py", "m::f");
    }

    /// JavaScript reaches a class method only through `this.f()`: a bare
    /// `f()` beside `function f()` and `class C { f() {} }` is the function.
    #[test]
    fn javascript_bare_call_beside_a_method_means_the_free_function() {
        let db = store(&[(
            "web/a.js",
            "function f() {\n  return 1;\n}\n\nclass C {\n  f() {\n    return 2;\n  }\n}\n\nfunction g() {\n  f();\n}\n",
        )]);
        settles_on(&db, "g", "f", "web/a.js", "a::f");
    }

    /// The TypeScript form of the JavaScript case.
    #[test]
    fn typescript_bare_call_beside_a_method_means_the_free_function() {
        let db = store(&[(
            "web/a.ts",
            "function f(): number {\n  return 1;\n}\n\nclass C {\n  f(): number {\n    return 2;\n  }\n}\n\nfunction g(): void {\n  f();\n}\n",
        )]);
        settles_on(&db, "g", "f", "web/a.ts", "a::f");
    }

    /// Go reaches a method only through a value (`t.F()`): a bare `F()` beside
    /// `func F()` and `func (t T) F()` is the function. Go records the method
    /// as kind "method" qualified by the package (`a::F`), not by `T`.
    #[test]
    fn go_bare_call_beside_a_method_means_the_free_function() {
        let db = store(&[(
            "go/a.go",
            "package a\n\ntype T struct{}\n\nfunc F() int { return 1 }\n\nfunc (t T) F() int { return 2 }\n\nfunc G() {\n\tF()\n}\n",
        )]);
        let out = crate::store::edges_out(&db, "G", &dependency_kinds()).unwrap();
        let hits: Vec<_> = out.iter().filter(|e| e.symbol.name == "F").collect();
        assert_eq!(hits.len(), 1, "G -> F did not settle: {hits:#?}");
        assert_eq!(hits[0].confidence, RESOLVED, "{hits:#?}");
        assert_eq!(hits[0].symbol.kind, "function", "{hits:#?}");
        assert_eq!(hits[0].symbol.start_line, 5, "{hits:#?}");
        let n = neighbours(&db, "F", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers
                .iter()
                .any(|c| c.symbol.name == "G" && c.confidence == RESOLVED),
            "{:?}",
            n.callers
        );
    }

    /// Guard: `Enabled::lane(e, "x")` names the type, so tier 0 settles it on
    /// the method — the free `lane` beside it does not take it.
    #[test]
    fn rust_type_path_call_still_means_the_method() {
        let db = store(&[("src/accel.rs", ACCEL)]);
        settles_on(&db, "typed", "lane", "src/accel.rs", "Enabled::lane");
    }

    /// Guard: Java has an implicit `this`, so `helper()` inside `class A`
    /// is `A.helper`, not `Util.helper` elsewhere. Today it settles on the
    /// method in the calling file (rank 1); Java records both as methods.
    #[test]
    fn java_bare_call_keeps_the_implicit_receiver() {
        let db = store(&[
            (
                "java/A.java",
                "class A {\n    void helper() {}\n    void run() {\n        helper();\n    }\n}\n",
            ),
            (
                "java/Util.java",
                "class Util {\n    static void helper() {}\n}\n",
            ),
        ]);
        settles_on(&db, "run", "helper", "java/A.java", "A::helper");
    }

    /// Guard: Kotlin has an implicit `this`, so `helper()` inside `class A`
    /// is the member, even with a top-level `fun helper()` in util.kt — the
    /// one free function a rule for receiver-less languages would wrongly
    /// prefer. Today the member settles at rank 1.
    #[test]
    fn kotlin_bare_call_keeps_the_implicit_receiver() {
        let db = store(&[
            (
                "kt/A.kt",
                "class A {\n    fun helper() {}\n    fun run() {\n        helper()\n    }\n}\n",
            ),
            ("kt/util.kt", "fun helper() {}\n"),
        ]);
        settles_on(&db, "run", "helper", "kt/A.kt", "A::helper");
    }

    /// Guard: `crate::m::g()` where m.rs holds only methods named `g` — on
    /// two types — has no free function to prefer, so it stays a tie.
    #[test]
    fn rust_module_path_call_with_only_methods_stays_ambiguous() {
        let db = store(&[
            (
                "src/m.rs",
                "pub struct S;\npub struct T;\n\nimpl S {\n    pub fn g(&self) {}\n}\n\nimpl T {\n    pub fn g(&self) {}\n}\n",
            ),
            ("src/daemon.rs", "fn other() {\n    crate::m::g();\n}\n"),
        ]);
        let out = crate::store::edges_out(&db, "other", &dependency_kinds()).unwrap();
        let hits: Vec<_> = out.iter().filter(|e| e.symbol.name == "g").collect();
        assert_eq!(hits.len(), 2, "{hits:#?}");
        assert!(hits.iter().all(|e| e.confidence == AMBIGUOUS), "{hits:#?}");
        let n = neighbours(&db, "g", &[], false, &Scope::all()).unwrap();
        assert!(
            n.callers.iter().any(|c| c.symbol.name == "other"
                && c.confidence == AMBIGUOUS
                && c.means.is_none()),
            "{:?}",
            n.callers
        );
    }

    /// A method that wraps the free function of its own name:
    /// `impl Enabled { fn lane(&self, id) { lane(id) } }`. The bare call was
    /// read as recursion and recorded nothing, so impact never saw it. With no
    /// implicit receiver it is a call to the free fn, in Rust and Python alike.
    #[test]
    fn a_method_calling_the_free_function_of_its_name_is_a_call() {
        let rust = "pub fn lane(id: &str) -> Option<u8> {\n    None\n}\n\npub struct Enabled;\n\nimpl Enabled {\n    pub fn lane(&self, id: &str) -> bool {\n        lane(id).is_some()\n    }\n}\n";
        let db = store(&[("src/accel.rs", rust)]);
        settles_on(&db, "lane", "lane", "src/accel.rs", "accel::lane");
        let python = "def f():\n    return 1\n\n\nclass C:\n    def f(self):\n        return f()\n";
        let db = store(&[("pkg/m.py", python)]);
        settles_on(&db, "f", "f", "pkg/m.py", "m::f");
    }

    /// Recursion still adds no self-edge: a free fn calling itself, a method
    /// calling itself through `self`, and a Java method's bare call to its
    /// own name, which there can be `this.helper()`.
    #[test]
    fn recursion_still_records_no_edge() {
        let rust = "fn count(n: u32) -> u32 {\n    if n == 0 { 0 } else { count(n - 1) }\n}\n\nstruct S;\n\nimpl S {\n    fn walk(&self) {\n        self.walk();\n    }\n}\n";
        let db = store(&[("src/r.rs", rust)]);
        for name in ["count", "walk"] {
            let out = crate::store::edges_out(&db, name, &dependency_kinds()).unwrap();
            assert!(
                out.iter().all(|e| e.symbol.name != name),
                "{name}: {out:#?}"
            );
        }
        let java = "class A {\n    void helper() {\n        helper();\n    }\n}\n";
        let db = store(&[("src/A.java", java)]);
        let out = crate::store::edges_out(&db, "helper", &dependency_kinds()).unwrap();
        assert!(out.iter().all(|e| e.symbol.name != "helper"), "{out:#?}");
    }

    /// `from`'s call to `to` settled on the definition starting at `line` in
    /// `path`, for when two definitions share a qualified name.
    fn settles_at(db: &rusqlite::Connection, from: &str, to: &str, path: &str, line: u32) {
        let out = crate::store::edges_out(db, from, &dependency_kinds()).unwrap();
        let hits: Vec<_> = out
            .iter()
            .filter(|e| e.symbol.name == to && e.kind == "calls")
            .collect();
        assert_eq!(hits.len(), 1, "{from} -> {to} did not settle: {hits:#?}");
        assert!(
            [RESOLVED, EXTRACTED].contains(&hits[0].confidence.as_str()),
            "{from} -> {to} is {}: {hits:#?}",
            hits[0].confidence
        );
        assert_eq!(
            (hits[0].symbol.path.as_str(), hits[0].symbol.start_line),
            (path, line),
            "{from} -> {to}: {hits:#?}"
        );
    }

    fn kind_of(db: &rusqlite::Connection, name: &str, line: u32) -> String {
        db.query_row(
            "SELECT kind FROM symbols WHERE name = ?1 AND start_line = ?2",
            rusqlite::params![name, line],
            |r| r.get(0),
        )
        .unwrap()
    }

    /// #247: a top-level `fun helper()` in A.kt is qualified `A::helper`, the
    /// same as `class A`'s member. The member is a method now, the top-level
    /// one is a free function, `main`'s bare call (no `this` at the top
    /// level) means the top-level one and `run`'s means the member.
    #[test]
    fn kotlin_top_level_functions_and_members_are_told_apart() {
        let kt = "fun helper() {}\n\nfun main() {\n    helper()\n}\n\nclass A {\n    fun helper() {}\n    fun run() {\n        helper()\n    }\n}\n";
        let db = store(&[("src/A.kt", kt)]);
        assert_eq!(kind_of(&db, "helper", 1), "function");
        assert_eq!(kind_of(&db, "helper", 8), "method");
        settles_at(&db, "main", "helper", "src/A.kt", 1);
        settles_at(&db, "run", "helper", "src/A.kt", 8);
    }

    /// #248: a Go method is qualified by its receiver type, so `t.F()` on the
    /// method's own receiver and the method expression `T.F(t)` settle on
    /// `T::F`, and a bare `F()` on the package's function.
    #[test]
    fn go_methods_are_qualified_by_their_receiver_type() {
        let go = "package a\n\ntype T struct{}\n\nfunc F() {}\n\nfunc (t T) F() {}\n\nfunc (t *T) G() {\n\tt.F()\n}\n\nfunc H() {\n\tF()\n}\n\nfunc K(t T) {\n\tT.F(t)\n}\n";
        let db = store(&[("a/a.go", go)]);
        let qualified: String = db
            .query_row(
                "SELECT qualified FROM symbols WHERE name = 'F' AND kind = 'method'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(qualified, "T::F");
        settles_at(&db, "G", "F", "a/a.go", 7);
        settles_at(&db, "H", "F", "a/a.go", 5);
        settles_at(&db, "K", "F", "a/a.go", 7);
    }

    /// In a Python class body a bare name reads the class's own namespace:
    /// `x = deco(1)` is `C.deco`, not the module's `deco`.
    #[test]
    fn python_class_body_call_means_the_class_def() {
        let py = "def deco(f):\n    return f\n\n\nclass C:\n    def deco(f):\n        return f\n\n    x = deco(1)\n\n    def m(self):\n        return deco(2)\n";
        let db = store(&[("pkg/m.py", py)]);
        settles_at(&db, "C", "deco", "pkg/m.py", 6);
        // From inside a method a bare name reads the module, never the class.
        settles_at(&db, "m", "deco", "pkg/m.py", 1);
    }

    /// Two definitions of one name in one file keep their own calls: `B::new`
    /// calling `helper()` was written onto `A::new`, the first `new`, and the
    /// call site on line 5 was lost.
    #[test]
    fn same_named_definitions_in_one_file_keep_their_own_calls() {
        let rs = "fn helper() {}\nstruct A;\nimpl A { fn new() -> A { helper(); A } }\nstruct B;\nimpl B { fn new() -> B { helper(); B } }\n";
        let db = store(&[("src/x.rs", rs)]);
        let n = neighbours(&db, "helper", &[], false, &Scope::all()).unwrap();
        let mut lines: Vec<_> = n
            .callers
            .iter()
            .filter(|c| c.symbol.name == "new")
            .map(|c| (c.symbol.start_line, c.line, c.confidence.clone()))
            .collect();
        lines.sort();
        assert_eq!(
            lines,
            vec![
                (3, Some(3), RESOLVED.to_string()),
                (5, Some(5), RESOLVED.to_string())
            ]
        );
    }

    /// `go(self.go())` inside `S::go`: the receiver call is recursion, the
    /// bare call on the same line is the free fn and is kept.
    #[test]
    fn a_bare_call_beside_a_receiver_copy_on_its_line_is_kept() {
        let rs = "fn go(x: u8) {}\nstruct S;\nimpl S {\n    fn go(&self) -> u8 {\n        go(self.go());\n        0\n    }\n}\n";
        let db = store(&[("src/r.rs", rs)]);
        settles_at(&db, "go", "go", "src/r.rs", 1);
    }

    /// A C++ out-of-line definition is qualified by the scope it names, in
    /// any file: `Foo::bar` is a method of `Foo`, `ns::helper` a function of
    /// the namespace.
    #[test]
    fn cpp_out_of_line_definitions_are_qualified_by_their_scope() {
        let cpp = "void Foo::bar() {}\nvoid ns::helper() {}\n";
        let db = store(&[("src/impl.cpp", cpp)]);
        let row = |name: &str| -> (String, String) {
            db.query_row(
                "SELECT kind, qualified FROM symbols WHERE name = ?1",
                [name],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap()
        };
        assert_eq!(row("bar"), ("method".to_string(), "Foo::bar".to_string()));
        assert_eq!(
            row("helper"),
            ("function".to_string(), "ns::helper".to_string())
        );
    }

    /// A Rust integration test is a crate of its own: the cloud worker's
    /// `semlith::accel::lane("remote")` tied src/accel.rs's `lane` with a
    /// helper `lane` in tests/accel.rs. The test file's own call still means
    /// its own helper.
    #[test]
    fn a_rust_test_crate_is_reachable_only_from_beside_it() {
        let tests = "fn lane(id: &str) -> bool {\n    id == \"cpu\"\n}\n\n#[test]\nfn t() {\n    lane(\"cpu\");\n}\n";
        let db = store(&[
            ("semlith/src/accel.rs", ACCEL),
            ("semlith/tests/accel.rs", tests),
            (
                "semlith-cloud/src/bin/worker.rs",
                "fn warm_remote() {\n    semlith::accel::lane(\"remote\");\n}\n",
            ),
        ]);
        settles_at(&db, "warm_remote", "lane", "semlith/src/accel.rs", 1);
        settles_at(&db, "t", "lane", "semlith/tests/accel.rs", 1);
    }

    /// An enum variant is a value of its enum: `Kind::Catchup.lane()` is
    /// `Kind::lane`, not any other type's `lane`, in an expression and in a
    /// macro's arguments alike.
    #[test]
    fn a_rust_enum_variant_receiver_names_its_enum() {
        let rs = "enum Kind {\n    Catchup,\n}\n\nimpl Kind {\n    fn lane(&self) -> u8 {\n        1\n    }\n}\n\nstruct Other;\n\nimpl Other {\n    fn lane(&self) -> u8 {\n        2\n    }\n}\n\nfn first() -> u8 {\n    Kind::Catchup.lane()\n}\n\nfn second() {\n    assert_eq!(Kind::Catchup.lane(), 1);\n}\n";
        let db = store(&[("src/jobs.rs", rs)]);
        settles_at(&db, "first", "lane", "src/jobs.rs", 6);
        // The same receiver inside a macro's arguments.
        settles_at(&db, "second", "lane", "src/jobs.rs", 6);
    }

    /// A Rust `fn` inside `mod tests { }` is a function: the grammar shapes
    /// a module body like an `impl`'s and tagged it a method, so the 0.44.1
    /// rule dropped it and ripgrep's escape.rs tests called a `b` in
    /// another repository (found by the ground-truth pass).
    #[test]
    fn a_rust_fn_in_a_module_body_is_a_function() {
        let escape = "#[cfg(test)]\nmod tests {\n    fn b(s: &str) -> String {\n        s.to_string()\n    }\n\n    #[test]\n    fn empty() {\n        b(\"\");\n    }\n}\n";
        let other = "struct G;\n\nimpl G {\n    fn b(&self) {}\n}\n";
        let py = "def outer():\n    def b():\n        pass\n    return b\n";
        let db = store(&[
            ("crates/cli/src/escape.rs", escape),
            ("crates/index/src/literal.rs", other),
            ("tests/test_x.py", py),
        ]);
        assert_eq!(kind_of(&db, "b", 3), "function");
        settles_at(&db, "empty", "b", "crates/cli/src/escape.rs", 3);
    }

    /// A module path naming nothing the store holds leaves the store:
    /// ripgrep's `std::env::current_dir()` was resolved onto the one
    /// `current_dir` in hiargs.rs. An inline `mod m { fn f() }` is still
    /// named by `m::f()`.
    #[test]
    fn a_module_path_naming_nothing_here_does_not_settle() {
        let hiargs = "pub fn current_dir() -> u8 {\n    0\n}\n";
        let walk = "use crate::dir::{Ignore, IgnoreBuilder};\n\nfn get_or_set_current_dir() {\n    std::env::current_dir();\n}\n\nmod m {\n    pub fn f() {}\n}\n\nfn g() {\n    m::f();\n}\n";
        let other = "fn f() {}\n";
        // A method of that name in a file the caller imports for something
        // else places nothing for a path that names `env`.
        let dir = "pub struct IgnoreBuilder;\n\nimpl IgnoreBuilder {\n    pub fn current_dir(&self) {}\n}\n";
        let db = store(&[
            ("crates/core/flags/hiargs.rs", hiargs),
            ("crates/ignore/src/walk.rs", walk),
            ("crates/other/src/lib.rs", other),
            ("crates/ignore/src/dir.rs", dir),
        ]);
        let out =
            crate::store::edges_out(&db, "get_or_set_current_dir", &dependency_kinds()).unwrap();
        assert!(
            out.iter()
                .all(|e| e.symbol.name != "current_dir" || e.confidence == AMBIGUOUS),
            "{out:#?}"
        );
        settles_at(&db, "g", "f", "crates/ignore/src/walk.rs", 8);
    }

    /// `impl SinkError for Box<dyn Error>` names no type, so its methods are
    /// the trait's rather than free functions of the file.
    #[test]
    fn a_method_of_an_unnameable_impl_belongs_to_its_trait() {
        let sink = "pub trait SinkError {\n    fn error_message(m: &str) -> Self;\n}\n\nimpl SinkError for Box<dyn std::error::Error> {\n    fn error_message(m: &str) -> Self {\n        m.into()\n    }\n}\n";
        let db = store(&[("src/sink.rs", sink)]);
        let row: (String, String) = db
            .query_row(
                "SELECT kind, qualified FROM symbols WHERE name = 'error_message' AND start_line = 6",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(
            row,
            ("method".to_string(), "SinkError::error_message".to_string())
        );
    }

    /// The no-receiver rule counts only candidates still standing: a Rust
    /// call whose only free namesakes sit in another crate's tests/ (or are
    /// Python, whose tests/ is no Rust crate) kept nothing at all, and the
    /// edge lost every definition (`get(&m)` on a closure parameter in
    /// ripgrep against flask's tests).
    #[test]
    fn the_no_receiver_rule_counts_only_candidates_left() {
        let lib = "pub struct G;\n\nimpl G {\n    pub fn get(&self) {}\n}\n";
        let caller = "fn attach(get: impl Fn()) {\n    get();\n}\n";
        let helper = "fn get() {}\n";
        let py = "def outer():\n    def get():\n        pass\n";
        let db = store(&[
            ("crates/a/src/lib.rs", lib),
            ("crates/b/src/hiargs.rs", caller),
            ("crates/a/tests/t.rs", helper),
            ("flask/tests/test_x.py", py),
        ]);
        let out = crate::store::edges_in_resolved(&db, "get", &dependency_kinds()).unwrap();
        let call = out
            .iter()
            .find(|i| i.end.symbol.name == "attach")
            .expect("attach calls get");
        assert!(!call.means.is_empty(), "{call:#?}");
    }

    /// JavaScript member calls are receiver calls, not bare ones:
    /// `this.close()` inside an object literal's method means that object's
    /// `close` in the same file, and `view.sel.clear()` is not the file's
    /// free `clear` (both read as bare calls once the rule existed).
    #[test]
    fn javascript_member_calls_are_not_bare() {
        let js = "const menu = {\n  close() {\n    return 1;\n  },\n  ensure() {\n    this.close();\n  },\n};\n\nfunction close() {}\n\nfunction clear() {}\n\nfunction paint(view) {\n  view.sel.clear();\n}\n";
        let db = store(&[("src/app.js", js)]);
        settles_at(&db, "ensure", "close", "src/app.js", 2);
        let out = crate::store::edges_out(&db, "paint", &dependency_kinds()).unwrap();
        assert!(
            out.iter()
                .all(|e| e.symbol.name != "clear" || e.confidence == AMBIGUOUS),
            "{out:#?}"
        );
    }

    /// A TypeScript `this.f()` names its class and settles on `C.f`, beside
    /// a free `f` of the same file.
    #[test]
    fn typescript_this_call_means_the_class_method() {
        let ts = "function f() {}\n\nclass C {\n  f() {}\n  g() {\n    this.f();\n  }\n}\n";
        let db = store(&[("src/c.ts", ts)]);
        settles_at(&db, "g", "f", "src/c.ts", 4);
    }

    /// A Python attribute named like an imported module is no module path to
    /// a free function: `d.fixtures.bulk()` in flask's drive is
    /// `Fixtures.bulk`, and fixtures.py holds no free `bulk`.
    #[test]
    fn a_module_path_drops_methods_only_for_a_free_function_it_places() {
        let fixtures = "class Fixtures:\n    def bulk(self):\n        return 1\n";
        let other = "def bulk():\n    return 2\n";
        let caller = "import fixtures\n\n\ndef run(d):\n    d.fixtures.bulk()\n";
        let db = store(&[
            ("drive/fixtures.py", fixtures),
            ("drive/other.py", other),
            ("drive/findings.py", caller),
        ]);
        settles_at(&db, "run", "bulk", "drive/fixtures.py", 2);
    }

    /// A grouped Rust `use` places what it imports: atlassian.rs's
    /// `use super::{Item, gdrive::{base, url}};` names gdrive.rs, so a bare
    /// `url(..)` there is gdrive's `url`.
    #[test]
    fn a_grouped_rust_use_places_its_module() {
        let gdrive = "pub(super) fn url(base: &str) -> String {\n    base.to_string()\n}\n";
        let daemon = "fn url() -> u8 {\n    0\n}\n";
        let atlassian = "use super::{\n    Item,\n    gdrive::{base, url},\n};\n\nfn account() {\n    url(\"x\");\n}\n";
        let db = store(&[
            ("cloud/src/connectors/gdrive.rs", gdrive),
            ("core/src/daemon.rs", daemon),
            ("cloud/src/connectors/atlassian.rs", atlassian),
        ]);
        settles_at(&db, "account", "url", "cloud/src/connectors/gdrive.rs", 1);
    }
}