knot 1.12.0

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
use anyhow::{Context, Result};
use neo4rs::query;

use super::GraphDb;

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MatchTier {
    ExactFqn,
    FqnSuffix,
    ExactName,
    SignaturePrefix,
    /// Anchored prefix match on target entity name for queries under [`MIN_FUZZY_LEN`].
    NamePrefix,
    Fuzzy,
}

/// Lightweight projection of an Entity used as a root candidate.
///
/// Distinct from [`TargetRow`] (which lacks `signature`/`docstring`) because
/// the subgraph root is rendered in the response and surfaced through the
/// `root_resolution` disclosure — so the fields the consumer expects to see
/// must be present on the candidate row.
///
/// This is the canonical type; `models::RootCandidateLite` is an alias of it
/// so the wire payload and the db projection cannot drift apart.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RootCandidate {
    pub uuid: String,
    pub name: String,
    pub fqn: Option<String>,
    pub kind: Option<String>,
    pub signature: Option<String>,
    pub docstring: Option<String>,
    pub file_path: Option<String>,
    pub start_line: Option<i64>,
}

impl MatchTier {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::ExactFqn => "exact_fqn",
            Self::FqnSuffix => "fqn_suffix",
            Self::ExactName => "exact_name",
            Self::SignaturePrefix => "signature_prefix",
            Self::NamePrefix => "name_prefix",
            Self::Fuzzy => "fuzzy",
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TargetRow {
    pub uuid: String,
    pub name: String,
    pub fqn: String,
    pub kind: String,
    pub file_path: String,
    pub start_line: i64,
    /// Repository the resolved target belongs to (`""` when the node predates
    /// repo attribution). Makes `resolution.targets[]` self-labeling.
    pub repo_name: String,
}

/// Minimum length of the query string for Fuzzy match to be enabled.
/// This prevents very short queries from matching almost everything.
pub const MIN_FUZZY_LEN: usize = 4;

/// Default maximum number of targets to return before truncating.
/// Keeps the performance reasonable and prevents huge outputs.
pub const DEFAULT_MAX_TARGETS: usize = 25;

/// Hard ceiling for the number of targets a single resolution may return.
/// Callers may raise the cap up to this value (MCP `max_targets` /
/// CLI `--max-targets`) but never beyond it.
pub const MAX_TARGETS_CEILING: usize = 500;

pub fn target_resolution_tiers(name: &str) -> Vec<(MatchTier, &'static str)> {
    let mut tiers = Vec::new();

    // A bare name equal to a bare FQN is indistinguishable from a name match;
    // gating on separators keeps intent explicit and lets name homonyms
    // (class vs module-level function) surface via ExactName.
    // This mirrors the FqnSuffix gating.
    if name.contains('.') || name.contains("::") {
        tiers.push((MatchTier::ExactFqn, "target.fqn = $name"));
        tiers.push((
            MatchTier::FqnSuffix,
            "target.fqn ENDS WITH '.' + $name OR target.fqn ENDS WITH '::' + $name",
        ));
    }

    tiers.push((MatchTier::ExactName, "target.name = $name"));

    if name.contains('(') {
        tiers.push((
            MatchTier::SignaturePrefix,
            "(target.name + COALESCE(target.signature, '')) STARTS WITH $name",
        ));
    }

    if name.len() >= MIN_FUZZY_LEN {
        tiers.push((
            MatchTier::Fuzzy,
            "toLower(target.fqn) CONTAINS $name_lower \
             OR toLower(target.name + COALESCE(target.signature, '')) CONTAINS $name_lower",
        ));
    } else if !name.is_empty() {
        // Below MIN_FUZZY_LEN, CONTAINS degenerates into matching unrelated
        // names (`use` is a substring of every `*STATUSES` constant), so the
        // short-query tier is an anchored prefix on the name only. The FQN is
        // deliberately excluded: Rust/Java FQNs start with the crate/package,
        // so an FQN prefix would match a whole repository. The empty-name
        // guard matters because `STARTS WITH ''` is true for every row.
        tiers.push((
            MatchTier::NamePrefix,
            "toLower(target.name) STARTS WITH $name_lower",
        ));
    }

    tiers
}

/// Root-preference rank for an entity kind (wire format, i.e. the snake_case
/// string stored in Neo4j — `SubgraphNode.kind` is read straight from the
/// `root.kind` property, and `EntityKind`'s wire form is its `Display` impl,
/// `src/models/entity.rs:148-265`). Lower ranks win.
///
/// Seed list lifted from `is_type_like` (`non_calls.rs:10-47`) minus the
/// namespaces: a `csharp_namespace` named like a type must not outrank the
/// type. Namespaces are containers, ranked below callables.
pub fn root_kind_rank(kind: Option<&str>) -> u8 {
    let Some(kind) = kind else {
        return 4;
    };
    match kind {
        // --- rank 0: type declarations --------------------------------------
        // `class` / `interface` / `enum` (generic, language-agnostic Display forms)
        "class" | "interface" | "enum"
        // Kotlin
        | "kotlin_class" | "kotlin_interface" | "kotlin_object"
        | "kotlin_companion_object" | "kotlin_enum"
        // Rust
        | "rust_struct" | "rust_enum" | "rust_union" | "rust_trait"
        | "rust_type_alias"
        // Python
        | "python_class"
        // C / C++
        | "c_struct" | "cpp_class"
        // Groovy
        | "groovy_class" | "groovy_interface" | "groovy_trait" | "groovy_enum"
        // C#
        | "csharp_class" | "csharp_interface" | "csharp_struct" | "csharp_record"
        | "csharp_enum" | "csharp_delegate" => 0,

        // --- rank 1: callables -----------------------------------------------
        "method" | "function"
        | "kotlin_function" | "kotlin_method"
        | "rust_function" | "rust_method" | "rust_macro_def"
        | "rust_impl"
        | "python_function" | "python_method"
        | "c_function" | "cpp_method"
        | "csharp_method" | "csharp_constructor" | "csharp_local_function"
        | "csharp_operator" | "csharp_indexer"
        | "groovy_method" | "groovy_function"
        | "macro_definition"
        | "scss_function" | "scss_mixin"
        | "vcl_subroutine" | "vcl_builtin_sub"
        | "vcc_function" | "vcc_method" => 1,

        // --- rank 2: members / data ------------------------------------------
        "constant"
        | "kotlin_property"
        | "rust_constant" | "rust_static"
        | "python_constant"
        | "csharp_property" | "csharp_field" | "csharp_constant" | "csharp_event"
        | "groovy_property"
        | "config_property"
        | "helm_value"
        | "css_variable"
        | "scss_variable" => 2,

        // --- rank 3: containers ----------------------------------------------
        "rust_module" | "python_module"
        | "cpp_namespace" | "csharp_namespace"
        | "markdown_document" | "markdown_section" => 3,

        // --- rank 4: everything else (build_, k8s_, HTML_, vtc_, project_identity, …)
        _ => 4,
    }
}

/// Order root candidates by `(root_kind_rank, file_path, start_line, uuid)`.
///
/// The trailing `(file_path, start_line, uuid)` tail is a total order —
/// required because neither `name` nor `fqn` is unique (`<module>` entities
/// share both; partial classes share both; etc.). Mirrors the
/// `m.fqn, m.uuid` tail of `find_entities_by_name_prefix`
/// (`query.rs:529-559`).
///
/// `Option` fields default to a deterministic empty/`0` value so the sort
/// is total even when a row misses any of them.
pub fn rank_root_candidates(mut candidates: Vec<RootCandidate>) -> Vec<RootCandidate> {
    candidates.sort_by(|a, b| {
        let ra = root_kind_rank(a.kind.as_deref());
        let rb = root_kind_rank(b.kind.as_deref());
        ra.cmp(&rb)
            .then_with(|| a.file_path.cmp(&b.file_path))
            .then_with(|| a.start_line.cmp(&b.start_line))
            .then_with(|| a.uuid.cmp(&b.uuid))
    });
    candidates
}

/// Relationship types the `find_references` buckets cover in a single
/// round-trip, via `type(r)` in the projection.
///
/// Produced-and-consumed edges only: `CONTAINS` (containment, not use) and
/// `DEPENDS_ON` (repository level, served by `knot deps`) are deliberately
/// absent, and `GENERIC_BOUND` is never built by the pipeline.
pub fn find_references_rel_labels() -> &'static str {
    "CALLS|EXTENDS|IMPLEMENTS|REFERENCES|MACRO_CALLS|REFERENCES_DOM|USES_CSS_CLASS\
     |IMPORTS_SCRIPT|IMPORTS_STYLESHEET|USES_BACKEND|USES_PROBE|USES_ACL\
     |INCLUDES|IMPORTS_VMOD|DECLARED_UNUSED|ROUTES_TO"
}

pub fn relationship_query(rel_labels: &str, repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "WHERE target.repo_name IN $repo_names AND target.uuid IN $target_uuids"
    } else {
        "WHERE target.uuid IN $target_uuids"
    };

    format!(
        "MATCH (entity:Entity)-[r:{rel_labels}]->(target:Entity)
         {repo_filter}
         RETURN type(r) AS rel_type,
                entity.name, entity.kind, entity.file_path, entity.start_line, entity.signature,
                entity.repo_name AS repo_name,
                target.name AS target_name, target.fqn AS target_fqn,
                target.file_path AS target_file_path,
                target.start_line AS target_start_line, target.signature AS target_signature,
                target.repo_name AS target_repo_name
         ORDER BY target.fqn, entity.file_path, entity.start_line"
    )
}

/// Cipher for the `overridden_by` bucket: implementations/overrides declared
/// in subtypes of the resolved targets.
pub fn overridden_by_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "WHERE target.repo_name IN $repo_names AND target.uuid IN $target_uuids"
    } else {
        "WHERE target.uuid IN $target_uuids"
    };

    format!(
        "MATCH (entity:Entity)-[:OVERRIDES*1..]->(target:Entity)
         {repo_filter}
           AND entity.uuid <> target.uuid
         RETURN DISTINCT entity.name, entity.kind, entity.file_path, entity.start_line, entity.signature,
                entity.repo_name AS repo_name,
                target.name AS target_name, target.fqn AS target_fqn,
                target.file_path AS target_file_path,
                target.start_line AS target_start_line, target.signature AS target_signature,
                target.repo_name AS target_repo_name
         ORDER BY target.fqn, entity.file_path, entity.start_line"
    )
}

/// Cipher for the `overrides` bucket: the supertype methods the resolved
/// targets implement or override. The projection is mirrored (target ↔ entity)
/// so both buckets share `parse_reference_row` — including the repo aliases,
/// which are swapped for the same reason (`target.repo_name` labels the row's
/// *entity*, `entity.repo_name` labels the row's *target*).
pub fn overrides_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "WHERE entity.repo_name IN $repo_names AND entity.uuid IN $target_uuids"
    } else {
        "WHERE entity.uuid IN $target_uuids"
    };

    format!(
        "MATCH (entity:Entity)-[:OVERRIDES*1..]->(target:Entity)
         {repo_filter}
           AND entity.uuid <> target.uuid
         RETURN DISTINCT target.name AS `entity.name`, target.kind AS `entity.kind`,
                target.file_path AS `entity.file_path`, target.start_line AS `entity.start_line`,
                target.signature AS `entity.signature`,
                target.repo_name AS repo_name,
                entity.name AS target_name, entity.fqn AS target_fqn,
                entity.file_path AS target_file_path,
                entity.start_line AS target_start_line, entity.signature AS target_signature,
                entity.repo_name AS target_repo_name
         ORDER BY entity.file_path, entity.start_line"
    )
}

/// Cipher for the `dispatched_calls` bucket: callers whose `CALLS` edge is
/// bound to a method related to a resolved target through `OVERRIDES`, in
/// either direction — calls bound to an override of the target (the target
/// is an interface/superclass method) and calls bound to a supertype method
/// the target overrides (dynamic dispatch can reach the target). Siblings are
/// excluded: both legs are directed. Rows carry the *bound* method as their
/// target so the reader sees which declaration the call statically names.
pub fn dispatched_calls_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "WHERE target.repo_name IN $repo_names AND target.uuid IN $target_uuids"
    } else {
        "WHERE target.uuid IN $target_uuids"
    };

    format!(
        "CALL {{
           MATCH (bound:Entity)-[:OVERRIDES*1..]->(target:Entity)
           {repo_filter}
           RETURN bound
           UNION
           MATCH (target:Entity)-[:OVERRIDES*1..]->(bound:Entity)
           {repo_filter}
           RETURN bound
         }}
         WITH bound WHERE NOT bound.uuid IN $target_uuids
         MATCH (entity:Entity)-[:CALLS]->(bound)
         RETURN DISTINCT entity.name, entity.kind, entity.file_path, entity.start_line, entity.signature,
                entity.repo_name AS repo_name,
                bound.name AS target_name, bound.fqn AS target_fqn,
                bound.file_path AS target_file_path,
                bound.start_line AS target_start_line, bound.signature AS target_signature,
                bound.repo_name AS target_repo_name
         ORDER BY target_fqn, entity.file_path, entity.start_line"
    )
}

pub fn find_callers_query(repo_names: &[String]) -> String {
    if !repo_names.is_empty() {
        "MATCH (caller:Entity)-[:CALLS]->(callee:Entity)
         WHERE callee.repo_name IN $repo_names
           AND (callee.name = $name
            OR callee.fqn = $name)
         RETURN caller.name, caller.kind, caller.file_path, caller.start_line, caller.signature,
                caller.repo_name AS repo_name"
            .to_string()
    } else {
        "MATCH (caller:Entity)-[:CALLS]->(callee:Entity)
         WHERE callee.name = $name
            OR callee.fqn = $name
         RETURN caller.name, caller.kind, caller.file_path, caller.start_line, caller.signature,
                caller.repo_name AS repo_name"
            .to_string()
    }
}

pub fn get_file_entities_query(repo_names: &[String]) -> String {
    if repo_names.len() == 1 {
        "MATCH (e:Entity {file_path: $file_path, repo_name: $repo_name})
         RETURN e.name, e.kind, e.signature, e.docstring, e.start_line, e.decorators
         ORDER BY e.start_line"
            .to_string()
    } else if repo_names.len() > 1 {
        "MATCH (e:Entity)
         WHERE e.file_path = $file_path AND e.repo_name IN $repo_names
         RETURN e.name, e.kind, e.signature, e.docstring, e.start_line, e.decorators
         ORDER BY e.start_line"
            .to_string()
    } else {
        "MATCH (e:Entity {file_path: $file_path})
         RETURN e.name, e.kind, e.signature, e.docstring, e.start_line, e.decorators
         ORDER BY e.start_line"
            .to_string()
    }
}

pub fn get_file_outgoing_references_query(repo_names: &[String]) -> String {
    // The outgoing-reference edge set mirrors `find_references_rel_labels`
    // minus the file-level IMPORTS/INCLUDES/DECLARED_UNUSED edges, whose
    // targets are file containers rather than the definitions this section
    // lists (IMPORTS_SCRIPT/IMPORTS_STYLESHEET reach `explore` through
    // their own pipeline instead).
    if repo_names.len() == 1 {
        "MATCH (src:Entity {file_path: $file_path, repo_name: $repo_name})
              -[r:CALLS|EXTENDS|IMPLEMENTS|REFERENCES|MACRO_CALLS|REFERENCES_DOM|USES_CSS_CLASS|USES_BACKEND|USES_PROBE|USES_ACL]->
              (dst:Entity)
         WHERE dst.file_path <> $file_path OR NOT dst.repo_name IN $repo_names
         RETURN type(r) AS rel,
                dst.name AS name,
                dst.kind AS kind,
                dst.file_path AS file_path,
                dst.start_line AS line
         ORDER BY rel, name"
            .to_string()
    } else if repo_names.len() > 1 {
        "MATCH (src:Entity)
              -[r:CALLS|EXTENDS|IMPLEMENTS|REFERENCES|MACRO_CALLS|REFERENCES_DOM|USES_CSS_CLASS|USES_BACKEND|USES_PROBE|USES_ACL]->
              (dst:Entity)
         WHERE src.file_path = $file_path AND src.repo_name IN $repo_names
           AND (dst.file_path <> $file_path OR NOT dst.repo_name IN $repo_names)
         RETURN type(r) AS rel,
                dst.name AS name,
                dst.kind AS kind,
                dst.file_path AS file_path,
                dst.start_line AS line
         ORDER BY rel, name"
            .to_string()
    } else {
        "MATCH (src:Entity {file_path: $file_path})
              -[r:CALLS|EXTENDS|IMPLEMENTS|REFERENCES|MACRO_CALLS|REFERENCES_DOM|USES_CSS_CLASS|USES_BACKEND|USES_PROBE|USES_ACL]->
              (dst:Entity)
         WHERE dst.file_path <> $file_path
         RETURN type(r) AS rel,
                dst.name AS name,
                dst.kind AS kind,
                dst.file_path AS file_path,
                dst.start_line AS line
         ORDER BY rel, name"
            .to_string()
    }
}

/// Cipher for the read-only file listing used by the `list_files` CLI
/// subcommand and MCP tool: distinct repo-relative paths of the scoped
/// repositories with their entity counts, deterministically ordered.
/// `prefix` pre-narrows paths via Cypher's literal `STARTS WITH` (the
/// directory-boundary rule is applied per page by `path_matches` caller-side,
/// so `src/api` pre-fetches `src/api-notes.md` but discards it during paged
/// filtering). `None` (no prefix) lists every file of the scope.
pub fn list_files_query(repo_scoped: bool) -> String {
    let prefix_clause = "WHERE e.file_path STARTS WITH $prefix ";
    let repo_clause = if repo_scoped {
        "AND e.repo_name IN $repo_names "
    } else {
        ""
    };
    format!(
        "MATCH (e:Entity) \
         {prefix_clause}{repo_clause}\
         RETURN e.file_path AS file_path, e.repo_name AS repo_name, count(e) AS entity_count \
         ORDER BY e.repo_name, e.file_path \
         SKIP $skip \
         LIMIT $limit"
    )
}

/// HTTP endpoints (issue #33) with the handler each one routes to, ordered
/// by `(repo_name, name)`. `limit` bounds the read.
pub fn list_endpoints_query(repo_scoped: bool) -> String {
    let repo_clause = if repo_scoped {
        "WHERE e.repo_name IN $repo_names "
    } else {
        ""
    };
    format!(
        "MATCH (e:Entity {{kind: 'http_endpoint'}}) \
         {repo_clause}\
         OPTIONAL MATCH (e)-[:ROUTES_TO]->(h:Entity) \
         RETURN e.repo_name AS repo_name, e.name AS name, e.file_path AS file_path, \
                e.start_line AS start_line, h.fqn AS handler_fqn \
         ORDER BY e.repo_name, e.name \
         LIMIT $limit"
    )
}

pub fn find_files_by_suffix_query(suffix_fragment: &str, repo_names: &[String]) -> String {
    if !repo_names.is_empty() {
        format!(
            "MATCH (e:Entity) \
             WHERE ({suffix_fragment}) AND e.repo_name IN $repo_names \
             RETURN DISTINCT e.file_path AS file_path, e.repo_name AS repo_name \
             ORDER BY e.file_path LIMIT 50"
        )
    } else {
        format!(
            "MATCH (e:Entity) \
             WHERE ({suffix_fragment}) \
             RETURN DISTINCT e.file_path AS file_path, e.repo_name AS repo_name \
             ORDER BY e.file_path LIMIT 50"
        )
    }
}

/// Cipher for the caller-recall bridge: the `(caller_uuid, target_uuid)`
/// pairs that CALL any of the given target UUIDs. Used by
/// `search_hybrid_context` to pull the callers of the strongest semantic
/// hits into the candidate pool and to count how many top roots each
/// caller touches — a shared caller of several roots is strong evidence of
/// the described behaviour's entry point (`login` calls both
/// `normalize_email` and `verify_credentials_or_fail`).
pub fn caller_links_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "AND caller.repo_name IN $repo_names"
    } else {
        ""
    };
    format!(
        "MATCH (caller:Entity)-[:CALLS]->(target:Entity)
         WHERE target.uuid IN $target_uuids {repo_filter}
         RETURN DISTINCT caller.uuid AS caller_uuid, target.uuid AS target_uuid
         ORDER BY caller_uuid, target_uuid
         LIMIT $limit"
    )
}

/// Per-entity row of the re-rank's root-set coverage annotation
/// ([`QueryExt::fetch_root_coverage`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootCoverage {
    /// Entity the row annotates (the Qdrant↔Neo4j bridge key).
    pub uuid: String,
    /// Fully qualified name of the entity (`""` when the node predates FQN
    /// attribution). Absent from the Qdrant payload, so the search pipeline
    /// must fetch it here for the generic-name guard in `rank`.
    pub fqn: String,
    /// How many of the top semantic roots the entity calls directly.
    pub direct_roots: usize,
    /// How many top roots the entity reaches through exactly one helper
    /// (`(e)-[:CALLS]->(helper)-[:CALLS]->(root)`), *excluding* roots it
    /// already calls directly — transitive coverage never double counts.
    pub transitive_roots: usize,
    /// Total outgoing CALLS degree of the entity, independent of the root
    /// set. Consumed by `rank`'s neutral-kind behavior boost: a kind the
    /// taxonomy scores neutral (`constant`…) whose node orchestrates ≥ 2
    /// calls is behavior, not a bare constant.
    pub out_degree: usize,
}

/// Cipher for the re-rank's root-set coverage annotation. Both patterns are
/// anchored on the indexed `uuid` at *both* ends, so the expansion is driven
/// by `$pool_uuids`/`$root_uuids` (the caller caps both) rather than by the
/// graph's fan-out: depth is fixed at 2 hops and every `collect` is bounded
/// by the root set, never by the caller's in-degree.
pub fn root_coverage_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "AND e.repo_name IN $repo_names"
    } else {
        ""
    };
    format!(
        "MATCH (e:Entity)
         WHERE e.uuid IN $pool_uuids {repo_filter}
         OPTIONAL MATCH (e)-[:CALLS]->(d:Entity) WHERE d.uuid IN $root_uuids
         WITH e, collect(DISTINCT d.uuid) AS direct
         OPTIONAL MATCH (e)-[:CALLS]->(:Entity)-[:CALLS]->(t:Entity)
           WHERE t.uuid IN $root_uuids AND NOT t.uuid IN direct
         WITH e, direct, collect(DISTINCT t.uuid) AS indirect
         OPTIONAL MATCH (e)-[:CALLS]->(o:Entity)
         WITH e, direct, indirect, count(DISTINCT o) AS out_degree
         RETURN e.uuid AS uuid, e.fqn AS fqn,
                size(direct) AS direct_roots, size(indirect) AS transitive_roots,
                out_degree
         ORDER BY uuid
         LIMIT $limit"
    )
}

/// Cipher for the two-hop caller-recall bridge: callers of the callers of
/// `target_uuids` (entry points that reach a top semantic root through
/// exactly one helper). Anchored on `$target_uuids` at both ends so the
/// expansion is driven by the caller's seed cap, never by graph fan-out;
/// `caller.uuid IN $target_uuids` is excluded because one-hop callers are
/// already fetched by [`caller_links_query`].
pub fn caller_links_depth2_query(repo_scoped: bool) -> String {
    let repo_filter = if repo_scoped {
        "AND caller.repo_name IN $repo_names"
    } else {
        ""
    };
    format!(
        "MATCH (caller:Entity)-[:CALLS]->(helper:Entity)-[:CALLS]->(target:Entity)
         WHERE target.uuid IN $target_uuids
           AND NOT caller.uuid IN $target_uuids {repo_filter}
         RETURN DISTINCT caller.uuid AS caller_uuid, target.uuid AS target_uuid
         ORDER BY caller_uuid, target_uuid
         LIMIT $limit"
    )
}

/// Cipher for one tier of the reference-target resolution ladder used by
/// `resolve_reference_targets`. `predicate` is the post-`WHERE` match
/// expression produced by `target_resolution_tiers` (e.g.
/// `target.fqn = $name`); `repo_scoped` toggles the `repo_name IN` guard.
pub fn reference_target_query(predicate: &str, repo_scoped: bool) -> String {
    let repo_clause = if repo_scoped {
        "target.repo_name IN $repo_names AND "
    } else {
        ""
    };

    format!(
        "MATCH (target:Entity)
         WHERE {repo_clause}({predicate})
         RETURN target.uuid, target.name, target.fqn, target.kind, target.file_path,
                target.start_line, target.repo_name
         ORDER BY target.fqn"
    )
}

/// Outcome of resolving a subgraph root by name: the ranked winner, the
/// ladder tier that produced it, the un-truncated tier count, and every
/// candidate of the winning tier in rank order (already bounded by the
/// ladder's `LIMIT 25`) — so callers can build the `root_resolution`
/// disclosure without re-running the tier query.
pub(crate) struct ResolvedSubgraphRoot {
    pub winner: RootCandidate,
    pub tier: MatchTier,
    pub total_candidates: usize,
    /// All candidates of the winning tier, in rank order.
    pub ranked: Vec<RootCandidate>,
}

/// Outcome of the reference-target resolution ladder used by
/// [`GraphDbExt::find_references`].
///
/// `total` is the **pre-truncation** tier count: the tier Cypher carries no
/// `LIMIT` clause, so it is the real number of entities the queried name
/// resolved to. `targets` is capped at `max_targets` and is what relationship
/// buckets are built from — consumers must treat bucket counts as partial
/// whenever `truncated` is `true`.
///
/// `hidden_non_code` / `hidden_kinds` count the matched entities excluded by
/// the kind filter ([`crate::cli_tools::kinds::KindFilter`]) so the response
/// can disclose them instead of presenting a silently narrowed view.
pub(crate) struct ResolvedTargets {
    pub targets: Vec<TargetRow>,
    pub tier: MatchTier,
    pub truncated: bool,
    pub total: usize,
    pub hidden_non_code: usize,
    pub hidden_kinds: Vec<String>,
}

/// Cap a resolved target list, preserving the true pre-truncation total.
///
/// Mirrors `finalize_nodes` in `query_subgraph.rs`: the length must be
/// measured **before** `truncate`, otherwise downstream consumers report the
/// sample size as the total (the v1.10.0 truncation-reporting bug).
fn finalize_targets(
    targets: Vec<TargetRow>,
    tier: MatchTier,
    max_targets: usize,
) -> ResolvedTargets {
    let total = targets.len();
    let truncated = total > max_targets;
    let mut targets = targets;
    if truncated {
        targets.truncate(max_targets);
    }
    ResolvedTargets {
        targets,
        tier,
        truncated,
        total,
        hidden_non_code: 0,
        hidden_kinds: Vec::new(),
    }
}

/// Maximum number of distinct hidden kinds named in the disclosure; the
/// full picture is always recoverable via `kinds=all`.
const HIDDEN_KINDS_DISCLOSURE_CAP: usize = 6;

/// Split resolved target rows into `(allowed, hidden)` under `filter`.
///
/// Free function so the partition contract is unit-testable without a
/// database: the ladder treats "every row hidden" the same as "no rows"
/// (it keeps walking tiers), and callers need the hidden side only for the
/// disclosure message.
fn partition_by_kind(
    rows: Vec<TargetRow>,
    filter: &crate::cli_tools::kinds::KindFilter,
) -> (Vec<TargetRow>, Vec<TargetRow>) {
    let mut allowed = Vec::new();
    let mut hidden = Vec::new();
    for row in rows {
        if filter.allows(&row.kind) {
            allowed.push(row);
        } else {
            hidden.push(row);
        }
    }
    (allowed, hidden)
}

/// Fold one tier's hidden rows into the accumulated disclosure state:
/// deduplicating by `uuid` (a row may match in several tiers) and keeping
/// the distinct kind list sorted and capped for rendering.
fn fold_hidden(
    hidden_rows: Vec<TargetRow>,
    hidden_uuids: &mut std::collections::HashSet<String>,
    hidden_kinds: &mut Vec<String>,
) -> usize {
    let mut newly_hidden = 0usize;
    for row in hidden_rows {
        if hidden_uuids.insert(row.uuid.clone()) {
            newly_hidden += 1;
        }
        if !hidden_kinds.contains(&row.kind) {
            hidden_kinds.push(row.kind.clone());
        }
    }
    hidden_kinds.sort();
    newly_hidden
}

impl GraphDb {
    /// Shared Cypher execution for both caller-bridge depths (`depth2`
    /// selects `caller_links_depth2_query` over `caller_links_query`).
    /// Inherent implementation helper behind [`QueryExt::find_caller_links`]
    /// and [`QueryExt::find_caller_links_depth2`]; not part of the trait.
    async fn find_caller_links_depth2_matching(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
        limit: usize,
        depth2: bool,
    ) -> Result<Vec<(String, String)>> {
        if target_uuids.is_empty() {
            return Ok(Vec::new());
        }
        let query_str = if depth2 {
            caller_links_depth2_query(!repo_names.is_empty())
        } else {
            caller_links_query(!repo_names.is_empty())
        };
        let mut q = query(&query_str)
            .param("target_uuids", target_uuids.to_vec())
            .param("limit", limit as i64);
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for caller-recall bridge")?;

        let mut links = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            match (
                row.get::<String>("caller_uuid"),
                row.get::<String>("target_uuid"),
            ) {
                (Ok(caller), Ok(target)) => links.push((caller, target)),
                _ => continue,
            }
        }
        Ok(links)
    }

    async fn resolve_reference_targets(
        &self,
        name: &str,
        repo_names: &[String],
        max_targets: usize,
        kind_filter: &crate::cli_tools::kinds::KindFilter,
    ) -> Result<ResolvedTargets> {
        let tiers = target_resolution_tiers(name);

        let repo_scoped = !repo_names.is_empty();

        // Hidden rows accumulate across tiers, deduplicated by uuid: a row
        // may match in ExactName and again in Fuzzy when an earlier tier
        // produced no *allowed* hits and the ladder kept walking.
        let mut hidden_uuids = std::collections::HashSet::new();
        let mut hidden_kinds: Vec<String> = Vec::new();
        let mut hidden_non_code = 0usize;

        for (tier, predicate) in tiers {
            let query_str = reference_target_query(predicate, repo_scoped);

            // `name_lower` is only consumed by the Fuzzy tier's predicate;
            // binding it on every tier keeps the call sites uniform (an
            // unused query parameter is harmless in neo4rs).
            let mut q = query(&query_str)
                .param("name", name)
                .param("name_lower", name.to_lowercase());
            if repo_scoped {
                q = q.param("repo_names", repo_names.to_vec());
            }

            let mut rows = self.graph.execute(q).await.context(format!(
                "Failed to resolve targets for tier {}",
                tier.as_str()
            ))?;

            let mut targets = Vec::new();
            while let Ok(Some(row)) = rows.next().await {
                let uuid = row.get::<String>("target.uuid").unwrap_or_default();
                let name = row.get::<String>("target.name").unwrap_or_default();
                let fqn = row.get::<String>("target.fqn").unwrap_or_default();
                let kind = row.get::<String>("target.kind").unwrap_or_default();
                let file_path = row.get::<String>("target.file_path").unwrap_or_default();
                let start_line = row.get::<i64>("target.start_line").unwrap_or(0);
                let repo_name = row.get::<String>("target.repo_name").unwrap_or_default();

                targets.push(TargetRow {
                    uuid,
                    name,
                    fqn,
                    kind,
                    file_path,
                    start_line,
                    repo_name,
                });
            }

            if targets.is_empty() {
                continue;
            }

            let (allowed, hidden) = partition_by_kind(targets, kind_filter);
            hidden_non_code += fold_hidden(hidden, &mut hidden_uuids, &mut hidden_kinds);

            if !allowed.is_empty() {
                let mut resolved = finalize_targets(allowed, tier, max_targets);
                resolved.hidden_non_code = hidden_non_code;
                hidden_kinds.truncate(HIDDEN_KINDS_DISCLOSURE_CAP);
                resolved.hidden_kinds = hidden_kinds;
                return Ok(resolved);
            }
            // Every hit of this tier was filtered out: keep walking the
            // ladder — an all-metadata tier must not shadow a code hit in
            // a later tier.
        }

        let default_tier = target_resolution_tiers(name)
            .last()
            .map(|(tier, _)| *tier)
            .unwrap_or(MatchTier::ExactName);
        Ok(ResolvedTargets {
            targets: Vec::new(),
            tier: default_tier,
            truncated: false,
            total: 0,
            hidden_non_code,
            hidden_kinds: {
                let mut kinds = hidden_kinds;
                kinds.truncate(HIDDEN_KINDS_DISCLOSURE_CAP);
                kinds
            },
        })
    }

    /// Resolve a user-supplied entity name to exactly one root candidate,
    /// walking the same tier ladder as `resolve_reference_targets` with early
    /// stop, then applying `rank_root_candidates` inside the winning tier.
    ///
    /// Returns `Some(...)` only when the ladder produced at least one hit.
    /// `total_candidates` is the **un-truncated** tier count (the ladder
    /// queries `LIMIT 25` for ranking fairness; the caller may surface this
    /// in the disclosure). `ranked` carries the winning tier's full candidate
    /// list from the same query that produced the winner, so callers never
    /// need to re-run the tier.
    pub(crate) async fn resolve_subgraph_root(
        &self,
        name: &str,
        repo_name: &str,
    ) -> Result<Option<ResolvedSubgraphRoot>> {
        let tiers = target_resolution_tiers(name);

        for (tier, predicate) in tiers {
            // Build a query per tier. The predicates are local-name aware
            // (e.g. `target.fqn = $name`) — they are reused verbatim from
            // `target_resolution_tiers(name)`.
            let query_str = format!(
                "MATCH (target:Entity)
                 WHERE target.repo_name = $repo_name AND ({predicate})
                 RETURN target.uuid, target.name, target.fqn, target.kind,
                        target.signature, target.docstring, target.file_path, target.start_line
                 ORDER BY target.fqn
                 LIMIT 25"
            );

            let q = query(&query_str)
                .param("name", name)
                // Unused by every tier except Fuzzy, whose predicate matches
                // on the lowercased form; binding it unconditionally keeps
                // this call site in lockstep with `resolve_reference_targets`.
                .param("name_lower", name.to_lowercase())
                .param("repo_name", repo_name);

            let mut rows = self.graph.execute(q).await.context(format!(
                "Failed to resolve subgraph root for tier {}",
                tier.as_str()
            ))?;

            let mut candidates = Vec::new();
            while let Ok(Some(row)) = rows.next().await {
                candidates.push(RootCandidate {
                    uuid: row.get::<String>("target.uuid").unwrap_or_default(),
                    name: row.get::<String>("target.name").unwrap_or_default(),
                    fqn: row.get::<String>("target.fqn").ok(),
                    kind: row.get::<String>("target.kind").ok(),
                    signature: row.get::<String>("target.signature").ok(),
                    docstring: row.get::<String>("target.docstring").ok(),
                    file_path: row.get::<String>("target.file_path").ok(),
                    start_line: row.get::<i64>("target.start_line").ok(),
                });
            }

            if !candidates.is_empty() {
                let total = candidates.len();
                let ranked = rank_root_candidates(candidates);
                // Safe: ranked is non-empty (candidates was non-empty above).
                let winner = ranked.first().cloned().expect("ranked non-empty");
                return Ok(Some(ResolvedSubgraphRoot {
                    winner,
                    tier,
                    total_candidates: total,
                    ranked,
                }));
            }
        }

        Ok(None)
    }

    /// Run one reference query and collect its rows.
    ///
    /// `label` only feeds the error context so a failure names the bucket that
    /// broke.
    async fn collect_reference_rows(
        &self,
        query_str: &str,
        target_uuids: &[String],
        repo_names: &[String],
        label: &str,
    ) -> Result<Vec<serde_json::Value>> {
        let mut q = query(query_str).param("target_uuids", target_uuids.to_vec());
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context(format!("Failed to query Neo4j for {label} relationships"))?;

        let mut collected = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            collected.push(parse_reference_row(row));
        }
        Ok(collected)
    }

    /// Run `q`, scoped to `repo_names` when any, and map every row with
    /// `to_json` into a JSON array. `what` only feeds the error context.
    async fn collect_json_rows(
        &self,
        mut q: neo4rs::Query,
        repo_names: &[String],
        what: &str,
        to_json: impl Fn(neo4rs::Row) -> serde_json::Value,
    ) -> Result<serde_json::Value> {
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }
        let mut rows = self
            .graph
            .execute(q)
            .await
            .context(format!("Failed to query Neo4j for {what}"))?;
        let mut results = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            results.push(to_json(row));
        }
        Ok(serde_json::json!(results))
    }
}

/// Extension trait for query and read operations.
#[expect(
    async_fn_in_trait,
    reason = "async trait method is required for the db interfaces"
)]
pub trait QueryExt {
    async fn get_entities_with_dependencies(
        &self,
        uuids: &[String],
        repo_names: &[String],
    ) -> Result<serde_json::Value>;
    async fn find_references(
        &self,
        entity_name: &str,
        repo_names: &[String],
        max_targets: usize,
        kinds: Option<&str>,
    ) -> Result<serde_json::Value>;
    /// Reference buckets of already-resolved targets, keyed exactly like
    /// [`QueryExt::find_references`] minus its `resolution` block. Used when
    /// the caller already holds the entity UUIDs (search enrichment), so no
    /// name-based resolution can merge homonyms.
    async fn find_references_for_targets(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
    ) -> Result<serde_json::Value>;
    async fn find_callers(
        &self,
        entity_name: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value>;
    async fn get_file_entities(
        &self,
        file_path: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value>;
    async fn find_entities_by_name_prefix(
        &self,
        prefix: &str,
        repo_names: &[String],
        limit: usize,
    ) -> Result<serde_json::Value>;
    async fn get_file_outgoing_references(
        &self,
        file_path: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value>;
    /// Suffix-based fallback used by `explore_file` (§4 of
    /// `docs/specs/relative_file_paths.md`). `suffix_fragment` is the
    /// fragment after `WHERE e.file_path ` in the Cipher query (e.g.
    /// `ENDS WITH '/Cargo.toml'`). Returns a list of distinct
    /// `(file_path, repo_name)` pairs that match.
    async fn find_files_by_suffix(
        &self,
        suffix_fragment: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value>;

    /// Read-only file listing (see [`list_files_query`]): distinct
    /// `(file_path, repo_name)` pairs with entity counts, ordered by
    /// `(repo_name, file_path)`. `prefix` is the normalized repo-relative
    /// directory prefix ("" = list everything); `skip` and `limit` control pagination.
    async fn list_files(
        &self,
        prefix: &str,
        repo_names: &[String],
        skip: usize,
        limit: usize,
    ) -> Result<serde_json::Value>;

    /// HTTP endpoints with their handlers (see [`list_endpoints_query`]),
    /// at most `limit` rows.
    async fn list_endpoints(
        &self,
        repo_names: &[String],
        limit: usize,
    ) -> Result<serde_json::Value>;

    /// Caller-recall bridge: `(caller_uuid, target_uuid)` CALL edges
    /// crossing any of `target_uuids`, scoped to `repo_names` (empty =
    /// all). `limit` caps the pair count. Used by `search_hybrid_context`
    /// to add the callers of its top semantic hits to the candidate pool
    /// and to weight callers by how many top roots they touch.
    async fn find_caller_links(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<(String, String)>>;

    /// Two-hop variant of [`find_caller_links`]: callers of the callers of
    /// `target_uuids` (`(caller)-[:CALLS]->(helper)-[:CALLS]->(target)`).
    /// Recalls entry points that reach a top semantic root through exactly
    /// one helper when no direct caller was seeded; `limit` caps the pair
    /// count the same way.
    async fn find_caller_links_depth2(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<(String, String)>>;

    /// Root-set coverage annotation for the `search_hybrid_context` re-rank:
    /// for each pool UUID, its FQN plus how many of the top semantic roots it
    /// calls directly (`(e)-[:CALLS]->(root)`) and through exactly one helper
    /// (`(e)-[:CALLS]->(helper)-[:CALLS]->(root)`, excluding direct ones).
    /// `limit` caps the returned row count. One bounded round trip replaces
    /// both the per-row FQN lookup and the old bridge-side caller counting.
    async fn fetch_root_coverage(
        &self,
        pool_uuids: &[String],
        root_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<RootCoverage>>;
}

impl QueryExt for GraphDb {
    /// Fetch entities by UUIDs along with their dependencies (outgoing CALLS relationships).
    async fn get_entities_with_dependencies(
        &self,
        uuids: &[String],
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        if uuids.is_empty() {
            return Ok(serde_json::json!([]));
        }

        let mut results = Vec::new();

        let repo_clause = if !repo_names.is_empty() {
            " AND m.repo_name IN $repo_names"
        } else {
            ""
        };
        let query_str = format!(
            "MATCH (m:Entity) WHERE m.uuid = $uuid{repo_clause}
             OPTIONAL MATCH (m)-[:CALLS]->(dep:Entity)
             RETURN m.name, m.kind, m.fqn, m.signature, m.docstring, m.file_path,
                    m.start_line, m.repo_name AS repo_name,
                    collect(DISTINCT coalesce(dep.fqn, dep.name)) as dependencies"
        );

        for uuid in uuids {
            let mut q = query(&query_str).param("uuid", uuid.as_str());
            if !repo_names.is_empty() {
                q = q.param("repo_names", repo_names.to_vec());
            }

            let mut row = self
                .graph
                .execute(q)
                .await
                .context("Failed to query Neo4j for entity dependencies")?;

            if let Ok(Some(row_data)) = row.next().await {
                let name = row_data.get::<String>("m.name").ok();
                let kind = row_data.get::<String>("m.kind").ok();
                let fqn = row_data.get::<String>("m.fqn").ok();
                let signature = row_data.get::<String>("m.signature").ok();
                let docstring = row_data.get::<String>("m.docstring").ok();
                let file_path = row_data.get::<String>("m.file_path").ok();
                let start_line = row_data.get::<i64>("m.start_line").ok();
                let repo_name = row_data.get::<String>("repo_name").ok();
                let dependencies = qualified_callee_labels(
                    &row_data
                        .get::<Vec<String>>("dependencies")
                        .unwrap_or_default(),
                );

                let entity_json = serde_json::json!({
                    "uuid": uuid,
                    "name": name,
                    "kind": kind,
                    "fqn": fqn,
                    "signature": signature,
                    "docstring": docstring,
                    "file_path": file_path,
                    "start_line": start_line,
                    "repo_name": repo_name,
                    "dependencies": dependencies,
                });

                results.push(entity_json);
            }
        }

        Ok(serde_json::json!(results))
    }

    /// Find all entities that reference a given entity via any produced
    /// relationship type (see [`find_references_rel_labels`]). Returns
    /// results grouped by relationship type.
    ///
    /// `kinds` scopes the target resolution (`None` = default code-kind
    /// filter, `all` = no filtering, otherwise an alias/exact-kind list —
    /// see [`crate::cli_tools::kinds::KindFilter`]).
    async fn find_references(
        &self,
        entity_name: &str,
        repo_names: &[String],
        max_targets: usize,
        kinds: Option<&str>,
    ) -> Result<serde_json::Value> {
        let kind_filter = crate::cli_tools::kinds::KindFilter::parse(kinds);

        // Clamp the requested cap so a caller cannot push a huge scan silently.
        let max_targets = max_targets.clamp(1, MAX_TARGETS_CEILING);

        // Stage 1: Resolve targets
        let resolved = self
            .resolve_reference_targets(entity_name, repo_names, max_targets, &kind_filter)
            .await?;

        let target_uuids: Vec<String> = resolved.targets.iter().map(|t| t.uuid.clone()).collect();

        // Stages 2 and 3: the buckets of the resolved targets.
        let mut results = self
            .find_references_for_targets(&target_uuids, repo_names)
            .await?;

        // Add the resolution info — `total_targets` is the real pre-truncation
        // entity count so downstream formatters can quantify truncation; the
        // kind-filter fields disclose what the filter removed.
        results["resolution"] = serde_json::json!({
            "query": entity_name,
            "tier": resolved.tier,
            "fuzzy": matches!(resolved.tier, MatchTier::Fuzzy),
            "truncated": resolved.truncated,
            "total_targets": resolved.total,
            "kind_filter": kind_filter.wire_label(),
            "hidden_non_code": resolved.hidden_non_code,
            "hidden_kinds": resolved.hidden_kinds,
            "targets": resolved.targets
        });

        Ok(results)
    }

    async fn find_references_for_targets(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        // Every bucket the multi-label query can produce is pre-initialized;
        // empty ones stay as `[]` so the wire shape is stable (formatters
        // and tests rely on the keys existing).
        let mut results = serde_json::json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "macro_calls": [],
            "references_dom": [],
            "uses_css_class": [],
            "imports_script": [],
            "imports_stylesheet": [],
            "uses_backend": [],
            "uses_probe": [],
            "uses_acl": [],
            "includes": [],
            "imports_vmod": [],
            "declared_unused": [],
            "routes_to": [],
            "overridden_by": [],
            "overrides": [],
            "dispatched_calls": []
        });

        if target_uuids.is_empty() {
            return Ok(results);
        }

        // Stage 2: one labelled multi-relationship query instead of one
        // round-trip per bucket. The global `ORDER BY` remains the intra-bucket
        // order; the stable partition below preserves it per bucket.
        let query_str = relationship_query(find_references_rel_labels(), !repo_names.is_empty());
        let rows = self
            .collect_reference_rows(&query_str, target_uuids, repo_names, "references")
            .await?;
        partition_reference_rows(&rows, &mut results);

        // Stage 3: OVERRIDES buckets, plus the calls that reach a target
        // through dynamic dispatch (bound to an override or a supertype).
        for (result_key, query_str) in [
            ("overridden_by", overridden_by_query(!repo_names.is_empty())),
            ("overrides", overrides_query(!repo_names.is_empty())),
            (
                "dispatched_calls",
                dispatched_calls_query(!repo_names.is_empty()),
            ),
        ] {
            let rows = self
                .collect_reference_rows(&query_str, target_uuids, repo_names, result_key)
                .await?;
            if let Some(arr) = results.get_mut(result_key) {
                *arr = serde_json::json!(rows);
            }
        }

        Ok(results)
    }

    /// Find all entities that call a given entity (reverse dependency lookup).
    /// **Deprecated:** Use `find_references()` instead for comprehensive relationship tracking.
    async fn find_callers(
        &self,
        entity_name: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        let mut results = Vec::new();

        let query_str = find_callers_query(repo_names);

        let mut q = query(&query_str).param("name", entity_name);
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for callers")?;

        while let Ok(Some(row)) = rows.next().await {
            let caller_json = serde_json::json!({
                "name": row.get::<String>("caller.name").ok(),
                "kind": row.get::<String>("caller.kind").ok(),
                "file_path": row.get::<String>("caller.file_path").ok(),
                "start_line": row.get::<i64>("caller.start_line").ok(),
                "signature": row.get::<String>("caller.signature").ok(),
                "repo_name": row.get::<String>("repo_name").ok(),
            });
            results.push(caller_json);
        }

        Ok(serde_json::json!(results))
    }

    /// Get all entities within a specific file.
    async fn get_file_entities(
        &self,
        file_path: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        let mut results = Vec::new();

        let query_str = get_file_entities_query(repo_names);

        let mut q = query(&query_str).param("file_path", file_path);
        if repo_names.len() == 1 {
            q = q.param("repo_name", repo_names[0].as_str());
        } else if repo_names.len() > 1 {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for file entities")?;

        while let Ok(Some(row)) = rows.next().await {
            let decorators = row.get::<Vec<String>>("e.decorators").unwrap_or_default();

            let entity_json = serde_json::json!({
                "name": row.get::<String>("e.name").ok(),
                "kind": row.get::<String>("e.kind").ok(),
                "signature": row.get::<String>("e.signature").ok(),
                "docstring": row.get::<String>("e.docstring").ok(),
                "start_line": row.get::<i64>("e.start_line").ok(),
                "decorators": decorators,
            });
            results.push(entity_json);
        }

        Ok(serde_json::json!(results))
    }

    async fn find_entities_by_name_prefix(
        &self,
        prefix: &str,
        repo_names: &[String],
        limit: usize,
    ) -> Result<serde_json::Value> {
        let repo_clause = if !repo_names.is_empty() {
            " AND m.repo_name IN $repo_names"
        } else {
            ""
        };

        let query_str = format!(
            "MATCH (m:Entity)
             WHERE toLower(m.name) STARTS WITH toLower($prefix){repo_clause}
             OPTIONAL MATCH (m)-[:CALLS]->(dep:Entity)
             RETURN m.uuid AS uuid, m.name, m.kind, m.fqn, m.signature, m.docstring,
                    m.file_path, m.start_line, m.repo_name AS repo_name,
                    collect(dep.name) as dependencies
             ORDER BY CASE WHEN toLower(m.name) = toLower($prefix) THEN 0 ELSE 1 END,
                      size(m.name),
                      m.fqn,
                      m.uuid
             LIMIT $limit"
        );

        let mut q = query(&query_str)
            .param("prefix", prefix)
            .param("limit", limit as i64);
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for entities by name prefix")?;

        let mut results = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            let entity_json = serde_json::json!({
                "uuid": row.get::<String>("uuid").ok(),
                "name": row.get::<String>("m.name").ok(),
                "kind": row.get::<String>("m.kind").ok(),
                "fqn": row.get::<String>("m.fqn").ok(),
                "signature": row.get::<String>("m.signature").ok(),
                "docstring": row.get::<String>("m.docstring").ok(),
                "file_path": row.get::<String>("m.file_path").ok(),
                "start_line": row.get::<i64>("m.start_line").ok(),
                "repo_name": row.get::<String>("repo_name").ok(),
                "dependencies": row.get::<Vec<String>>("dependencies").unwrap_or_default(),
            });
            results.push(entity_json);
        }

        Ok(serde_json::json!(results))
    }

    async fn get_file_outgoing_references(
        &self,
        file_path: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        let mut results = Vec::new();

        let query_str = get_file_outgoing_references_query(repo_names);

        let mut q = query(&query_str).param("file_path", file_path);
        if repo_names.len() == 1 {
            q = q
                .param("repo_name", repo_names[0].as_str())
                .param("repo_names", repo_names.to_vec());
        } else if repo_names.len() > 1 {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for file outgoing references")?;

        while let Ok(Some(row)) = rows.next().await {
            let entry = serde_json::json!({
                "rel": row.get::<String>("rel").ok(),
                "name": row.get::<String>("name").ok(),
                "kind": row.get::<String>("kind").ok(),
                "file_path": row.get::<String>("file_path").ok(),
                "line": row.get::<i64>("line").ok(),
            });
            results.push(entry);
        }

        Ok(serde_json::json!(results))
    }

    async fn find_files_by_suffix(
        &self,
        suffix_fragment: &str,
        repo_names: &[String],
    ) -> Result<serde_json::Value> {
        // `suffix_fragment` is the post-`WHERE` text, e.g.
        // "ENDS WITH '/src/lib.rs'". We hardcode the rest of the WHERE so
        // callers cannot inject arbitrary Cipher; the fragment is built by
        // `ends_with_suffix_query` which only ever interpolates a string
        // literal, so SQL/Cipher injection is not possible here.
        let query_str = find_files_by_suffix_query(suffix_fragment, repo_names);
        self.collect_json_rows(query(&query_str), repo_names, "files by suffix", |row| {
            serde_json::json!({
                "file_path": row.get::<String>("file_path").ok(),
                "repo_name": row.get::<String>("repo_name").ok(),
            })
        })
        .await
    }

    /// Read-only file listing (see [`list_files_query`]).
    async fn list_files(
        &self,
        prefix: &str,
        repo_names: &[String],
        skip: usize,
        limit: usize,
    ) -> Result<serde_json::Value> {
        let query_str = list_files_query(!repo_names.is_empty());
        let mut q = query(&query_str)
            .param("prefix", prefix.to_string())
            .param("skip", skip as i64)
            .param("limit", limit as i64);
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for file listing")?;

        let mut results = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            results.push(serde_json::json!({
                "file_path": row.get::<String>("file_path").ok(),
                "repo_name": row.get::<String>("repo_name").ok(),
                "entity_count": row.get::<i64>("entity_count").ok(),
            }));
        }
        Ok(serde_json::json!(results))
    }

    /// HTTP endpoints with their handlers (see [`list_endpoints_query`]).
    async fn list_endpoints(
        &self,
        repo_names: &[String],
        limit: usize,
    ) -> Result<serde_json::Value> {
        let query_str = list_endpoints_query(!repo_names.is_empty());
        let q = query(&query_str).param("limit", limit as i64);
        self.collect_json_rows(q, repo_names, "HTTP endpoints", |row| {
            serde_json::json!({
                "repo_name": row.get::<String>("repo_name").ok(),
                "name": row.get::<String>("name").ok(),
                "file_path": row.get::<String>("file_path").ok(),
                "start_line": row.get::<i64>("start_line").ok(),
                "handler_fqn": row.get::<String>("handler_fqn").ok(),
            })
        })
        .await
    }

    /// Caller-recall bridge: `(caller_uuid, target_uuid)` edges. One
    /// bounded query; a failure surfaces to the caller, which treats the
    /// bridge as best-effort.
    async fn find_caller_links(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<(String, String)>> {
        self.find_caller_links_depth2_matching(target_uuids, repo_names, limit, false)
            .await
    }

    /// Two-hop caller-recall bridge (see trait docs).
    async fn find_caller_links_depth2(
        &self,
        target_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<(String, String)>> {
        self.find_caller_links_depth2_matching(target_uuids, repo_names, limit, true)
            .await
    }

    /// Root-set coverage annotation (see trait docs). One bounded query; a
    /// failure surfaces to the caller, which treats the annotation as
    /// best-effort and keeps the un-annotated pool.
    async fn fetch_root_coverage(
        &self,
        pool_uuids: &[String],
        root_uuids: &[String],
        repo_names: &[String],
        limit: usize,
    ) -> Result<Vec<RootCoverage>> {
        if pool_uuids.is_empty() || root_uuids.is_empty() {
            return Ok(Vec::new());
        }
        let query_str = root_coverage_query(!repo_names.is_empty());
        let mut q = query(&query_str)
            .param("pool_uuids", pool_uuids.to_vec())
            .param("root_uuids", root_uuids.to_vec())
            .param("limit", limit as i64);
        if !repo_names.is_empty() {
            q = q.param("repo_names", repo_names.to_vec());
        }

        let mut rows = self
            .graph
            .execute(q)
            .await
            .context("Failed to query Neo4j for root-set coverage")?;

        let mut coverage = Vec::new();
        while let Ok(Some(row)) = rows.next().await {
            if let (Ok(uuid), Ok(fqn), Ok(direct), Ok(transitive), Ok(out_degree)) = (
                row.get::<String>("uuid"),
                row.get::<String>("fqn"),
                row.get::<i64>("direct_roots"),
                row.get::<i64>("transitive_roots"),
                row.get::<i64>("out_degree"),
            ) {
                coverage.push(RootCoverage {
                    uuid,
                    fqn,
                    direct_roots: direct.max(0) as usize,
                    transitive_roots: transitive.max(0) as usize,
                    out_degree: out_degree.max(0) as usize,
                });
            }
        }
        Ok(coverage)
    }
}

/// Short display label of a callee FQN: its last two segments, keeping the
/// FQN's own separator (`com.x.Adjuster.computeValue` → `Adjuster.computeValue`,
/// `knot::db::GraphDb::connect` → `GraphDb::connect`). The owning type (or
/// module) tells homonym callees apart without the full package path; a
/// path-like owner keeps only its last path component.
pub(crate) fn qualified_callee_label(fqn: &str) -> String {
    let Some((owner_path, member, separator)) = split_last_segment(fqn) else {
        return fqn.to_string();
    };
    let owner = split_last_segment(owner_path).map_or(owner_path, |(_, owner, _)| owner);
    let owner = owner.rsplit('/').next().unwrap_or(owner);
    if owner.is_empty() {
        member.to_string()
    } else {
        format!("{owner}{separator}{member}")
    }
}

/// Split `fqn` at its last `::` or `.` separator, whichever comes later.
fn split_last_segment(fqn: &str) -> Option<(&str, &str, &'static str)> {
    let colon = fqn.rfind("::").map(|i| (i, "::"));
    let dot = fqn.rfind('.').map(|i| (i, "."));
    let (index, separator) = match (colon, dot) {
        (Some(c), Some(d)) => {
            if c.0 > d.0 {
                c
            } else {
                d
            }
        }
        (c, d) => c.or(d)?,
    };
    Some((&fqn[..index], &fqn[index + separator.len()..], separator))
}

/// Map callee FQNs to [`qualified_callee_label`], dropping duplicate labels
/// while keeping first-seen order.
fn qualified_callee_labels(fqns: &[String]) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    fqns.iter()
        .map(|fqn| qualified_callee_label(fqn))
        .filter(|label| seen.insert(label.clone()))
        .collect()
}

fn parse_reference_row(row: neo4rs::Row) -> serde_json::Value {
    serde_json::json!({
        "name": row.get::<String>("entity.name").ok(),
        "kind": row.get::<String>("entity.kind").ok(),
        "file_path": row.get::<String>("entity.file_path").ok(),
        "start_line": row.get::<i64>("entity.start_line").ok(),
        "signature": row.get::<String>("entity.signature").ok(),
        "repo_name": row.get::<String>("repo_name").ok(),
        "target_name": row.get::<String>("target_name").ok(),
        "target_fqn": row.get::<String>("target_fqn").ok(),
        "target_file_path": row.get::<String>("target_file_path").ok(),
        "target_start_line": row.get::<i64>("target_start_line").ok(),
        "target_signature": row.get::<String>("target_signature").ok(),
        "target_repo_name": row.get::<String>("target_repo_name").ok(),
        // Present only in the multi-label reference query; absent (from the
        // old single-label shape without the rel alias) it maps to `None`,
        // which the partition falls back to `references` for.
        "rel_type": row.get::<String>("rel_type").ok(),
    })
}

/// Bucket-key mapping from a Cypher relationship label to the JSON result
/// key `find_references` fills. Rows from the multi-label query land here;
/// `OVERRIDES` rows need nothing here — the `overridden_by` / `overrides`
/// buckets come from their own mirrored queries (Stage 3).
fn reference_bucket_key(rel_type: &str) -> Option<&'static str> {
    match rel_type {
        "CALLS" => Some("calls"),
        "EXTENDS" => Some("extends"),
        "IMPLEMENTS" => Some("implements"),
        "REFERENCES" => Some("references"),
        "MACRO_CALLS" => Some("macro_calls"),
        "REFERENCES_DOM" => Some("references_dom"),
        "USES_CSS_CLASS" => Some("uses_css_class"),
        "IMPORTS_SCRIPT" => Some("imports_script"),
        "IMPORTS_STYLESHEET" => Some("imports_stylesheet"),
        "USES_BACKEND" => Some("uses_backend"),
        "USES_PROBE" => Some("uses_probe"),
        "USES_ACL" => Some("uses_acl"),
        "INCLUDES" => Some("includes"),
        "IMPORTS_VMOD" => Some("imports_vmod"),
        "DECLARED_UNUSED" => Some("declared_unused"),
        "ROUTES_TO" => Some("routes_to"),
        _ => None,
    }
}

/// Distribute multi-label reference rows into the result buckets.
///
/// Deliberately a **stable** partition: the Cypher carries a global
/// `ORDER BY target.fqn, entity.file_path, entity.start_line`, and walking
/// the rows in query order while appending preserves that per-bucket order
/// exactly — the determinism contract the v1.9.4 fix pinned.
///
/// Rows lacking `rel_type` (legacy single-label wire shape) fall back to
/// `references`; rows with an unknown `rel_type` are skipped rather than
/// misfiled.
fn partition_reference_rows(rows: &[serde_json::Value], results: &mut serde_json::Value) {
    for row in rows {
        let bucket = match row.get("rel_type").and_then(|v| v.as_str()) {
            None => "references",
            Some(rel_type) => match reference_bucket_key(rel_type) {
                Some(bucket) => bucket,
                None => continue,
            },
        };
        if let Some(arr) = results.get_mut(bucket).and_then(|v| v.as_array_mut()) {
            arr.push(row.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::GraphDb;
    use super::QueryExt;
    use crate::db::graph::connection::ConnectExt;

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_get_entities_with_dependencies_empty() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db.get_entities_with_dependencies(&[], &[]).await;
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.is_array());
        assert_eq!(json.as_array().unwrap().len(), 0);
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_get_entities_with_dependencies() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let uuids = vec!["550e8400-e29b-41d4-a716-446655440000".to_string()];
        let result = graph_db
            .get_entities_with_dependencies(&uuids, &["test-repo".to_string()])
            .await;
        // Should not fail even if UUID doesn't exist
        assert!(result.is_ok());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_find_references() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db
            .find_references("nonexistent_entity", &[], DEFAULT_MAX_TARGETS, None)
            .await;
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.is_object());
        assert!(json.get("calls").is_some());
        assert!(json.get("extends").is_some());
        assert!(json.get("implements").is_some());
        assert!(json.get("references").is_some());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_find_references_with_repo() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db
            .find_references(
                "nonexistent_entity",
                &["test-repo".to_string()],
                DEFAULT_MAX_TARGETS,
                None,
            )
            .await;
        assert!(result.is_ok());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_find_callers() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db.find_callers("nonexistent_entity", &[]).await;
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.is_array());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_find_callers_with_repo() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db
            .find_callers("nonexistent_entity", &["test-repo".to_string()])
            .await;
        assert!(result.is_ok());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_get_file_entities() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db
            .get_file_entities("/test/path/File.java", &[])
            .await;
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.is_array());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn test_get_file_entities_with_repo() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let result = graph_db
            .get_file_entities("/test/path/File.java", &["test-repo".to_string()])
            .await;
        assert!(result.is_ok());
    }

    #[ignore = "requires local Neo4j instance running on bolt://localhost:7687"]
    #[tokio::test]
    async fn param_binding_uses_repo_names_list() {
        let graph_db = GraphDb::connect("bolt://localhost:7687", "neo4j", "password")
            .await
            .expect("Failed to connect to Neo4j");

        let rows = graph_db
            .collect_reference_rows(
                "MATCH (target:Entity) WHERE target.repo_name IN $repo_names RETURN target.name AS entity.name",
                &["uuid-1".to_string()],
                &["repo1".to_string(), "repo2".to_string()],
                "test",
            )
            .await;
        assert!(rows.is_ok());
    }

    use super::{
        DEFAULT_MAX_TARGETS, MAX_TARGETS_CEILING, MatchTier, RootCandidate, TargetRow,
        caller_links_depth2_query, caller_links_query, dispatched_calls_query, finalize_targets,
        find_callers_query, find_files_by_suffix_query, find_references_rel_labels, fold_hidden,
        get_file_entities_query, get_file_outgoing_references_query, overridden_by_query,
        overrides_query, partition_by_kind, partition_reference_rows, rank_root_candidates,
        reference_bucket_key, reference_target_query, relationship_query, root_coverage_query,
        root_kind_rank, target_resolution_tiers,
    };

    #[test]
    fn test_tier_ladder_order_for_plain_name() {
        // A plain name skips FqnSuffix and ExactFqn: every FQN ends with `.<name>`, so the
        // suffix tier would shadow the more precise ExactName tier, and bare name FQN matching is indistinguishable from exact name.
        // "Offline" has len 7, so it gets Fuzzy tier, but no signature prefix because no '('
        let tiers = target_resolution_tiers("Offline");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped, vec![MatchTier::ExactName, MatchTier::Fuzzy]);

        // "Off" has len 3, so it gets NamePrefix instead of Fuzzy
        let tiers = target_resolution_tiers("Off");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped, vec![MatchTier::ExactName, MatchTier::NamePrefix]);
    }

    #[test]
    fn test_tier_ladder_includes_fqn_suffix_for_qualified_name() {
        for name in ["GestureOwner.Off", "Config::load"] {
            let tiers = target_resolution_tiers(name);
            let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
            assert_eq!(
                mapped,
                vec![
                    MatchTier::ExactFqn,
                    MatchTier::FqnSuffix,
                    MatchTier::ExactName,
                    MatchTier::Fuzzy
                ],
                "unexpected ladder for `{name}`"
            );
        }
    }

    #[test]
    fn test_tier_ladder_includes_signature_prefix_when_parenthesised() {
        let tiers = target_resolution_tiers("accept(List");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(
            mapped,
            vec![
                MatchTier::ExactName,
                MatchTier::SignaturePrefix,
                MatchTier::Fuzzy
            ]
        );
    }

    #[test]
    fn test_tier_ladder_uses_name_prefix_for_short_names() {
        let tiers = target_resolution_tiers("Id");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped, vec![MatchTier::ExactName, MatchTier::NamePrefix]);
    }

    #[test]
    fn short_query_ladder_has_name_prefix_and_no_fuzzy() {
        let tiers = target_resolution_tiers("use");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert!(mapped.contains(&MatchTier::NamePrefix));
        assert!(!mapped.contains(&MatchTier::Fuzzy));
    }

    #[test]
    fn name_prefix_predicate_is_anchored_lowered_and_param_bound() {
        let tiers = target_resolution_tiers("use");
        let (_, pred) = tiers
            .iter()
            .find(|(t, _)| *t == MatchTier::NamePrefix)
            .expect("name_prefix tier for short query");
        assert!(pred.contains("STARTS WITH"));
        assert!(pred.contains("toLower("));
        assert!(pred.contains("$name_lower"));
        assert!(!pred.contains("CONTAINS"));
        assert!(!pred.contains("target.fqn"));
    }

    #[test]
    fn long_query_ladder_is_unchanged_by_prefix_tier() {
        let tiers = target_resolution_tiers("useS");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped, vec![MatchTier::ExactName, MatchTier::Fuzzy]);
        assert!(!mapped.contains(&MatchTier::NamePrefix));
    }

    #[test]
    fn exact_name_precedes_name_prefix_tier() {
        let tiers = target_resolution_tiers("use");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        let exact_idx = mapped
            .iter()
            .position(|t| *t == MatchTier::ExactName)
            .unwrap();
        let prefix_idx = mapped
            .iter()
            .position(|t| *t == MatchTier::NamePrefix)
            .unwrap();
        assert!(exact_idx < prefix_idx);
    }

    #[test]
    fn signature_prefix_precedes_name_prefix_for_short_query() {
        let tiers = target_resolution_tiers("f(x");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(
            mapped,
            vec![
                MatchTier::ExactName,
                MatchTier::SignaturePrefix,
                MatchTier::NamePrefix
            ]
        );
    }

    #[test]
    fn empty_query_gets_no_prefix_tier() {
        let tiers = target_resolution_tiers("");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped, vec![MatchTier::ExactName]);
        assert!(!mapped.contains(&MatchTier::NamePrefix));
    }

    #[test]
    fn test_dotted_query_starts_with_exact_fqn() {
        let tiers = target_resolution_tiers("Foo.bar");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped[0], MatchTier::ExactFqn);

        let tiers = target_resolution_tiers("Foo::bar");
        let mapped: Vec<MatchTier> = tiers.iter().map(|(t, _)| *t).collect();
        assert_eq!(mapped[0], MatchTier::ExactFqn);
    }

    #[test]
    fn test_fqn_suffix_predicate_is_separator_anchored() {
        let tiers = target_resolution_tiers("GestureOwner.Off");
        let fqn_suffix_pred = tiers
            .iter()
            .find(|(t, _)| *t == MatchTier::FqnSuffix)
            .unwrap()
            .1;
        assert!(fqn_suffix_pred.contains("ENDS WITH '.' + $name"));
        assert!(fqn_suffix_pred.contains("ENDS WITH '::' + $name"));
        assert!(!fqn_suffix_pred.contains("CONTAINS"));
    }

    #[test]
    fn test_signature_predicate_is_prefix_anchored() {
        let tiers = target_resolution_tiers("accept(List");
        let sig_pred = tiers
            .iter()
            .find(|(t, _)| *t == MatchTier::SignaturePrefix)
            .unwrap()
            .1;
        assert!(sig_pred.contains("STARTS WITH $name"));
        assert!(!sig_pred.contains("CONTAINS"));
    }

    #[test]
    fn test_relationship_query_matches_on_uuid_set() {
        let query_str = relationship_query("CALLS", false);
        assert!(query_str.contains("target.uuid IN $target_uuids"));
        assert!(query_str.contains("ORDER BY target.fqn"));
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_relationship_query_repo_scoped_variant() {
        let query_str = relationship_query("CALLS", true);
        assert!(query_str.contains("target.repo_name IN $repo_names"));
        assert!(query_str.contains("target.uuid IN $target_uuids"));
    }

    // ---- §Kind-filtered resolution + multi-label reference query ----------

    use crate::cli_tools::kinds::KindFilter;

    fn target_row(uuid: &str, kind: &str) -> TargetRow {
        TargetRow {
            uuid: uuid.to_string(),
            name: uuid.to_string(),
            fqn: format!("repo::{uuid}"),
            kind: kind.to_string(),
            file_path: "f.rs".to_string(),
            start_line: 1,
            repo_name: "repo".to_string(),
        }
    }

    #[test]
    fn fuzzy_tier_predicate_is_case_insensitive_and_param_bound() {
        let tiers = target_resolution_tiers("hikari");
        let (_, fuzzy) = tiers
            .iter()
            .find(|(t, _)| *t == MatchTier::Fuzzy)
            .expect("fuzzy tier for 6-char name");
        assert!(fuzzy.contains("toLower("));
        assert!(fuzzy.contains("$name_lower"));
        // The raw case-sensitive form must be gone.
        assert!(!fuzzy.contains("target.fqn CONTAINS $name "));
        assert!(!fuzzy.contains(") CONTAINS $name OR"));
    }

    #[test]
    fn exact_tiers_keep_case_sensitive_exactness() {
        let tiers = target_resolution_tiers("Hikari");
        for (tier, pred) in &tiers {
            if matches!(
                tier,
                MatchTier::ExactFqn | MatchTier::FqnSuffix | MatchTier::ExactName
            ) {
                assert!(
                    pred.contains("$name"),
                    "exact tier {tier:?} must match the raw name"
                );
                assert!(!pred.contains("toLower"));
            }
        }
    }

    #[test]
    fn partition_by_kind_separates_code_from_metadata() {
        let rows = vec![
            target_row("u1", "rust_function"),
            target_row("u2", "build_dependency"),
            target_row("u3", "markdown_section"),
            target_row("u4", "html_id"),
            target_row("u5", "vcl_backend"),
        ];
        let default = KindFilter::parse(None);
        let (allowed, hidden) = partition_by_kind(rows, &default);
        let names: Vec<&str> = allowed.iter().map(|r| r.uuid.as_str()).collect();
        assert_eq!(names, vec!["u1", "u4", "u5"]);
        assert_eq!(hidden.len(), 2);
    }

    #[test]
    fn partition_by_kind_honours_any_filter() {
        let rows = vec![
            target_row("u1", "rust_function"),
            target_row("u2", "build_dependency"),
        ];
        let any = KindFilter::parse(Some("all"));
        let (allowed, hidden) = partition_by_kind(rows, &any);
        assert_eq!(allowed.len(), 2);
        assert!(hidden.is_empty());
    }

    #[test]
    fn fold_hidden_dedupes_by_uuid_and_collects_sorted_kinds() {
        let mut uuids = std::collections::HashSet::new();
        let mut kinds: Vec<String> = Vec::new();
        let n1 = fold_hidden(
            vec![
                target_row("u1", "build_dependency"),
                target_row("u2", "markdown_section"),
            ],
            &mut uuids,
            &mut kinds,
        );
        // Same row seen again in a later tier (uuid duplicate), new kind.
        let n2 = fold_hidden(
            vec![
                target_row("u1", "build_dependency"),
                target_row("u3", "cargo_feature"),
            ],
            &mut uuids,
            &mut kinds,
        );
        assert_eq!(n1, 2);
        assert_eq!(n2, 1, "the repeated uuid must not recount");
        assert_eq!(
            kinds,
            vec!["build_dependency", "cargo_feature", "markdown_section"]
        );
    }

    #[test]
    fn rel_label_list_covers_every_produced_edge_type() {
        let labels = find_references_rel_labels();
        for label in [
            "CALLS",
            "EXTENDS",
            "IMPLEMENTS",
            "REFERENCES",
            "MACRO_CALLS",
            "REFERENCES_DOM",
            "USES_CSS_CLASS",
            "IMPORTS_SCRIPT",
            "IMPORTS_STYLESHEET",
            "USES_BACKEND",
            "USES_PROBE",
            "USES_ACL",
            "INCLUDES",
            "IMPORTS_VMOD",
            "DECLARED_UNUSED",
            "ROUTES_TO",
        ] {
            assert!(labels.contains(label), "{label} missing from {labels}");
        }
        // Deliberately excluded edge types.
        assert!(!labels.contains("CONTAINS"));
        assert!(!labels.contains("DEPENDS_ON"));
        assert!(!labels.contains("OVERRIDES"));
    }

    #[test]
    fn relationship_query_projects_rel_type() {
        let query_str = relationship_query(find_references_rel_labels(), false);
        assert!(query_str.contains("type(r) AS rel_type"));
        assert!(query_str.contains("|MACRO_CALLS"));
        assert!(query_str.contains("ORDER BY target.fqn"));
    }

    #[test]
    fn qualified_callee_label_keeps_owner_and_separator() {
        use super::qualified_callee_label;
        assert_eq!(
            qualified_callee_label("com.example.pricing.StandardAdjuster.computeValue"),
            "StandardAdjuster.computeValue"
        );
        assert_eq!(
            qualified_callee_label("knot::db::graph::GraphDb::find_references"),
            "GraphDb::find_references"
        );
        assert_eq!(
            qualified_callee_label("caller_summary::standard::compute_value"),
            "standard::compute_value"
        );
        assert_eq!(qualified_callee_label("Foo::bar"), "Foo::bar");
        assert_eq!(qualified_callee_label("helper"), "helper");
    }

    #[test]
    fn qualified_callee_label_uses_the_last_separator_kind() {
        use super::qualified_callee_label;
        // Mixed separators: the member hangs off the later one.
        assert_eq!(
            qualified_callee_label("pkg.mod::Type::method"),
            "Type::method"
        );
        assert_eq!(
            qualified_callee_label("pkg::mod.Type.method"),
            "Type.method"
        );
        // A path-like owner keeps only its last path component.
        assert_eq!(
            qualified_callee_label("src/utils/format::formatDate"),
            "format::formatDate"
        );
    }

    #[test]
    fn qualified_callee_labels_drop_duplicates_in_order() {
        let fqns = vec![
            "a.Alpha.run".to_string(),
            "b.Beta.stop".to_string(),
            "c.Alpha.run".to_string(),
        ];
        assert_eq!(
            super::qualified_callee_labels(&fqns),
            vec!["Alpha.run".to_string(), "Beta.stop".to_string()]
        );
    }

    #[test]
    fn parse_reference_row_carries_rel_type() {
        // parse_reference_row needs a real neo4rs::Row to run; the mapping
        // it feeds is what this test pins. Every produced label maps to its
        // own bucket; unknown labels are skipped by the partition.
        assert_eq!(reference_bucket_key("CALLS"), Some("calls"));
        assert_eq!(reference_bucket_key("EXTENDS"), Some("extends"));
        assert_eq!(reference_bucket_key("IMPLEMENTS"), Some("implements"));
        assert_eq!(reference_bucket_key("REFERENCES"), Some("references"));
        assert_eq!(reference_bucket_key("MACRO_CALLS"), Some("macro_calls"));
        assert_eq!(
            reference_bucket_key("REFERENCES_DOM"),
            Some("references_dom")
        );
        assert_eq!(
            reference_bucket_key("USES_CSS_CLASS"),
            Some("uses_css_class")
        );
        assert_eq!(
            reference_bucket_key("IMPORTS_SCRIPT"),
            Some("imports_script")
        );
        assert_eq!(
            reference_bucket_key("IMPORTS_STYLESHEET"),
            Some("imports_stylesheet")
        );
        assert_eq!(reference_bucket_key("USES_BACKEND"), Some("uses_backend"));
        assert_eq!(reference_bucket_key("INCLUDES"), Some("includes"));
        assert_eq!(
            reference_bucket_key("DECLARED_UNUSED"),
            Some("declared_unused")
        );
        assert_eq!(reference_bucket_key("ROUTES_TO"), Some("routes_to"));
        assert_eq!(reference_bucket_key("CONTAINS"), None);
        assert_eq!(reference_bucket_key("DEPENDS_ON"), None);
    }

    #[test]
    fn partition_reference_rows_is_order_preserving_per_bucket() {
        // The Cypher returns rows globally ordered; the per-bucket order
        // must be the order of arrival (v1.9.4 determinism contract).
        let rows: Vec<serde_json::Value> = [
            ("REFERENCES", "a"),
            ("MACRO_CALLS", "b1"),
            ("MACRO_CALLS", "b2"),
            ("REFERENCES", "c"),
            ("REFERENCES_DOM", "d"),
        ]
        .iter()
        .map(|(rel, name)| {
            serde_json::json!({"rel_type": rel, "name": name, "file_path": "f.rs", "start_line": 1})
        })
        .collect();

        let mut results = serde_json::json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
            "macro_calls": [],
            "references_dom": [],
        });
        partition_reference_rows(&rows, &mut results);

        let calls: Vec<&str> = results["references"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r.get("name").and_then(|v| v.as_str()).unwrap())
            .collect();
        assert_eq!(calls, vec!["a", "c"], "bucket keeps arrival order");

        let macros: Vec<&str> = results["macro_calls"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r.get("name").and_then(|v| v.as_str()).unwrap())
            .collect();
        assert_eq!(macros, vec!["b1", "b2"]);
        assert_eq!(results["references_dom"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn partition_reference_rows_falls_back_for_legacy_rows() {
        // Pre-fix rows carry no rel_type; they were REFERENCES-only.
        let rows = vec![serde_json::json!({"name": "a", "file_path": "f.rs"})];
        let mut results = serde_json::json!({
            "calls": [],
            "extends": [],
            "implements": [],
            "references": [],
        });
        partition_reference_rows(&rows, &mut results);
        assert_eq!(results["references"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn test_overridden_by_query_unscoped() {
        let query_str = overridden_by_query(false);
        assert!(query_str.contains("target.uuid IN $target_uuids"));
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_overridden_by_query_repo_scoped() {
        let query_str = overridden_by_query(true);
        assert!(query_str.contains("target.repo_name IN $repo_names"));
        assert!(query_str.contains("target.uuid IN $target_uuids"));
    }

    #[test]
    fn test_overrides_query_unscoped() {
        let query_str = overrides_query(false);
        assert!(query_str.contains("entity.uuid IN $target_uuids"));
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_overrides_query_repo_scoped() {
        let query_str = overrides_query(true);
        assert!(query_str.contains("entity.repo_name IN $repo_names"));
        assert!(query_str.contains("entity.uuid IN $target_uuids"));
    }

    #[test]
    fn dispatched_calls_query_walks_both_directed_override_legs() {
        for repo_scoped in [false, true] {
            let query_str = dispatched_calls_query(repo_scoped);
            assert!(query_str.contains("(bound:Entity)-[:OVERRIDES*1..]->(target:Entity)"));
            assert!(query_str.contains("(target:Entity)-[:OVERRIDES*1..]->(bound:Entity)"));
            // Undirected traversal would leak sibling implementations.
            assert!(!query_str.contains("-[:OVERRIDES*1..]-("));
            assert!(query_str.contains("UNION"));
            assert!(query_str.contains("NOT bound.uuid IN $target_uuids"));
            assert!(query_str.contains("MATCH (entity:Entity)-[:CALLS]->(bound)"));
            assert_eq!(
                query_str.matches("$repo_names").count(),
                if repo_scoped { 2 } else { 0 },
                "repo_scoped={repo_scoped}: {query_str}"
            );
        }
    }

    #[test]
    fn dispatched_calls_query_projects_bound_method_as_target() {
        let query_str = dispatched_calls_query(true);
        assert!(query_str.contains("entity.repo_name AS repo_name"));
        assert!(query_str.contains("bound.fqn AS target_fqn"));
        assert!(query_str.contains("bound.repo_name AS target_repo_name"));
        assert!(query_str.contains("ORDER BY target_fqn, entity.file_path, entity.start_line"));
    }

    #[test]
    fn test_find_callers_query_unscoped() {
        let query_str = find_callers_query(&[]);
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_find_callers_query_repo_scoped() {
        let query_str = find_callers_query(&["a".to_string()]);
        assert!(query_str.contains("callee.repo_name IN $repo_names"));
    }

    // ---- reference repo attribution (v1.8.1) ----

    #[test]
    fn reference_target_query_preserves_tier_projection() {
        let scoped = reference_target_query("target.fqn = $name", true);
        assert!(scoped.contains("MATCH (target:Entity)"));
        assert!(scoped.contains("WHERE target.repo_name IN $repo_names AND (target.fqn = $name)"));
        assert!(scoped.contains(
            "RETURN target.uuid, target.name, target.fqn, target.kind, target.file_path"
        ));
        assert!(scoped.contains("target.start_line, target.repo_name"));
        assert!(scoped.contains("ORDER BY target.fqn"));

        let unscoped = reference_target_query("target.fqn = $name", false);
        assert!(unscoped.contains("WHERE (target.fqn = $name)"));
        assert!(!unscoped.contains("$repo_names"));
    }

    #[test]
    fn relationship_query_projects_both_repo_names() {
        for repo_scoped in [false, true] {
            let query_str = relationship_query("CALLS", repo_scoped);
            assert!(
                query_str.contains("entity.repo_name AS repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
            assert!(
                query_str.contains("target.repo_name AS target_repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
        }
    }

    #[test]
    fn overridden_by_query_projects_both_repo_names() {
        for repo_scoped in [false, true] {
            let query_str = overridden_by_query(repo_scoped);
            assert!(
                query_str.contains("entity.repo_name AS repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
            assert!(
                query_str.contains("target.repo_name AS target_repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
        }
    }

    #[test]
    fn overrides_query_projects_mirrored_repo_aliases() {
        for repo_scoped in [false, true] {
            let query_str = overrides_query(repo_scoped);
            // Mirrored projection: the Cipher `target` node is the row's
            // entity and the Cipher `entity` node is the row's target, so
            // the aliases MUST be swapped. Getting this backwards is silent.
            assert!(
                query_str.contains("target.repo_name AS repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
            assert!(
                query_str.contains("entity.repo_name AS target_repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
            assert!(
                !query_str.contains("entity.repo_name AS repo_name"),
                "unswapped alias leaked into the mirrored query: {query_str}"
            );
        }
    }

    #[test]
    fn reference_target_query_projects_repo_name() {
        for repo_scoped in [false, true] {
            let query_str = reference_target_query("target.name = $name", repo_scoped);
            assert!(
                query_str.contains("target.repo_name"),
                "repo_scoped={repo_scoped}: {query_str}"
            );
        }
    }

    #[test]
    fn find_callers_query_projects_caller_repo_name() {
        let unscoped = find_callers_query(&[]);
        assert!(unscoped.contains("caller.repo_name AS repo_name"));
        let scoped = find_callers_query(&["a".to_string()]);
        assert!(scoped.contains("caller.repo_name AS repo_name"));
    }

    #[test]
    fn reference_queries_keep_existing_order_by() {
        let rel = relationship_query("CALLS", true);
        assert!(rel.contains("ORDER BY target.fqn, entity.file_path, entity.start_line"));
        let overridden_by = overridden_by_query(true);
        assert!(overridden_by.contains("ORDER BY target.fqn, entity.file_path, entity.start_line"));
        let overrides = overrides_query(true);
        assert!(overrides.contains("ORDER BY entity.file_path, entity.start_line"));
        let tier = reference_target_query("target.name = $name", true);
        assert!(tier.contains("ORDER BY target.fqn"));
    }

    #[test]
    fn target_row_serializes_repo_name() {
        let row = TargetRow {
            uuid: "uuid-1".to_string(),
            name: "work".to_string(),
            fqn: "scope_alpha::src::shared_util::SharedUtil::work".to_string(),
            kind: "method".to_string(),
            file_path: "src/shared_util.ts".to_string(),
            start_line: 3,
            repo_name: "scope_alpha".to_string(),
        };
        let serialized = serde_json::to_string(&row).expect("serialize TargetRow");
        assert!(serialized.contains("\"repo_name\":\"scope_alpha\""));
        let deserialized: TargetRow =
            serde_json::from_str(&serialized).expect("deserialize TargetRow");
        assert_eq!(deserialized.repo_name, "scope_alpha");
    }

    #[test]
    fn test_get_file_entities_query_unscoped() {
        let query_str = get_file_entities_query(&[]);
        assert!(query_str.contains("MATCH (e:Entity {file_path: $file_path})"));
        assert!(!query_str.contains("repo_name"));
    }

    #[test]
    fn caller_links_query_is_scoped_and_capped() {
        let unscoped = caller_links_query(false);
        assert!(unscoped.contains("-[:CALLS]->"));
        assert!(unscoped.contains("target.uuid IN $target_uuids"));
        assert!(
            !unscoped.contains("caller.repo_name"),
            "unscoped must not filter repo"
        );
        assert!(unscoped.contains("LIMIT $limit"));
        assert!(unscoped.contains("target.uuid AS target_uuid"));

        let scoped = caller_links_query(true);
        assert!(scoped.contains("caller.repo_name IN $repo_names"));
    }

    #[test]
    fn root_coverage_query_is_anchored_scoped_and_capped() {
        let unscoped = root_coverage_query(false);
        // Both hop patterns present, each anchored on the fixed root set.
        assert!(unscoped.contains("WHERE e.uuid IN $pool_uuids"));
        assert!(unscoped.contains("(e)-[:CALLS]->(d:Entity) WHERE d.uuid IN $root_uuids"));
        assert!(unscoped.contains("(e)-[:CALLS]->(:Entity)-[:CALLS]->(t:Entity)"));
        // Transitive coverage excludes roots already covered directly.
        assert!(unscoped.contains("NOT t.uuid IN direct"));
        assert!(unscoped.contains("AS direct_roots"));
        assert!(unscoped.contains("AS transitive_roots"));
        // Deterministic truncation.
        assert!(unscoped.contains("ORDER BY uuid"));
        assert!(unscoped.contains("LIMIT $limit"));
        assert!(
            !unscoped.contains("$repo_names"),
            "unscoped must not reference the repo filter"
        );

        let scoped = root_coverage_query(true);
        assert!(scoped.contains("e.repo_name IN $repo_names"));
        // The coverage row now carries the neutral-kind behavior boost's
        // input: the total outgoing CALLS degree.
        assert!(unscoped.contains("out_degree"));
    }

    #[test]
    fn caller_links_depth2_query_is_anchored_two_hopped_and_capped() {
        let unscoped = caller_links_depth2_query(false);
        // Two hops, anchored on the fixed seed at both ends.
        assert!(unscoped.contains("WHERE target.uuid IN $target_uuids"));
        assert!(
            unscoped
                .contains("(caller:Entity)-[:CALLS]->(helper:Entity)-[:CALLS]->(target:Entity)")
        );
        // One-hop callers are fetched by the depth-1 query; no overlap.
        assert!(unscoped.contains("NOT caller.uuid IN $target_uuids"));
        // Bounded, no path-varargs expansion.
        assert!(unscoped.contains("DISTINCT"));
        assert!(unscoped.contains("LIMIT $limit"));
        assert!(
            !unscoped.contains("$repo_names"),
            "unscoped must not reference the repo filter"
        );

        let scoped = caller_links_depth2_query(true);
        assert!(scoped.contains("caller.repo_name IN $repo_names"));
    }

    #[test]
    fn test_get_file_entities_query_single_repo() {
        let query_str = get_file_entities_query(&["repo-a".to_string()]);
        assert!(
            query_str.contains("MATCH (e:Entity {file_path: $file_path, repo_name: $repo_name})")
        );
    }

    #[test]
    fn test_get_file_entities_query_multi_repo() {
        let query_str = get_file_entities_query(&["repo-a".to_string(), "repo-b".to_string()]);
        assert!(
            query_str.contains("WHERE e.file_path = $file_path AND e.repo_name IN $repo_names")
        );
    }

    #[test]
    fn test_get_file_outgoing_references_query_unscoped() {
        let query_str = get_file_outgoing_references_query(&[]);
        assert!(query_str.contains("WHERE dst.file_path <> $file_path"));
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_get_file_outgoing_references_query_repo_scoped() {
        let query_str = get_file_outgoing_references_query(&["repo-a".to_string()]);
        assert!(query_str.contains("NOT dst.repo_name IN $repo_names"));
    }

    #[test]
    fn test_find_files_by_suffix_query_unscoped() {
        let query_str = find_files_by_suffix_query("ENDS WITH '/Cargo.toml'", &[]);
        assert!(!query_str.contains("$repo_names"));
    }

    #[test]
    fn test_find_files_by_suffix_query_repo_scoped() {
        let query_str =
            find_files_by_suffix_query("ENDS WITH '/Cargo.toml'", &["repo-a".to_string()]);
        assert!(query_str.contains("e.repo_name IN $repo_names"));
    }

    // ---- §5.1 root_kind_rank ----

    #[test]
    fn test_root_kind_rank_prefers_type_declarations_over_callables() {
        // `csharp_class` (rank 0) beats `csharp_constructor` (rank 1).
        assert!(root_kind_rank(Some("csharp_class")) < root_kind_rank(Some("csharp_constructor")));
        // And the plain generic forms too.
        assert!(root_kind_rank(Some("class")) < root_kind_rank(Some("method")));
        assert!(root_kind_rank(Some("class")) < root_kind_rank(Some("function")));
    }

    #[test]
    fn test_root_kind_rank_containers_rank_below_types() {
        // Namespaces are containers, not type declarations.
        assert!(root_kind_rank(Some("csharp_class")) < root_kind_rank(Some("csharp_namespace")));
        assert!(root_kind_rank(Some("rust_struct")) < root_kind_rank(Some("rust_module")));
        assert!(root_kind_rank(Some("python_class")) < root_kind_rank(Some("python_module")));
        assert!(root_kind_rank(Some("cpp_class")) < root_kind_rank(Some("cpp_namespace")));
    }

    #[test]
    fn test_root_kind_rank_handles_missing_kind() {
        assert_eq!(root_kind_rank(None), 4);
    }

    #[test]
    fn test_root_kind_rank_is_total_over_known_kinds() {
        // Iterate every variant of EntityKind via its Display impl. None
        // should panic and every result must be <= 4.
        use crate::models::EntityKind;
        let kinds = [
            EntityKind::Class,
            EntityKind::Interface,
            EntityKind::Method,
            EntityKind::Function,
            EntityKind::Constant,
            EntityKind::Enum,
            EntityKind::KotlinClass,
            EntityKind::KotlinInterface,
            EntityKind::KotlinObject,
            EntityKind::KotlinCompanionObject,
            EntityKind::KotlinFunction,
            EntityKind::KotlinMethod,
            EntityKind::KotlinProperty,
            EntityKind::KotlinEnum,
            EntityKind::RustStruct,
            EntityKind::RustEnum,
            EntityKind::RustUnion,
            EntityKind::RustTrait,
            EntityKind::RustImpl,
            EntityKind::RustFunction,
            EntityKind::RustMethod,
            EntityKind::RustMacroDef,
            EntityKind::RustTypeAlias,
            EntityKind::RustConstant,
            EntityKind::RustStatic,
            EntityKind::RustModule,
            EntityKind::PythonClass,
            EntityKind::PythonFunction,
            EntityKind::PythonMethod,
            EntityKind::PythonModule,
            EntityKind::PythonConstant,
            EntityKind::CStruct,
            EntityKind::CFunction,
            EntityKind::CppClass,
            EntityKind::CppMethod,
            EntityKind::CppNamespace,
            EntityKind::MacroDefinition,
            EntityKind::CSharpClass,
            EntityKind::CSharpInterface,
            EntityKind::CSharpStruct,
            EntityKind::CSharpRecord,
            EntityKind::CSharpEnum,
            EntityKind::CSharpMethod,
            EntityKind::CSharpConstructor,
            EntityKind::CSharpProperty,
            EntityKind::CSharpField,
            EntityKind::CSharpConstant,
            EntityKind::CSharpDelegate,
            EntityKind::CSharpEvent,
            EntityKind::CSharpIndexer,
            EntityKind::CSharpOperator,
            EntityKind::CSharpNamespace,
            EntityKind::CSharpLocalFunction,
            EntityKind::GroovyClass,
            EntityKind::GroovyInterface,
            EntityKind::GroovyTrait,
            EntityKind::GroovyMethod,
            EntityKind::GroovyFunction,
            EntityKind::GroovyEnum,
            EntityKind::GroovyProperty,
            EntityKind::BuildDependency,
            EntityKind::BuildPlugin,
            EntityKind::ProjectIdentity,
            EntityKind::MarkdownDocument,
            EntityKind::MarkdownSection,
            EntityKind::ConfigProperty,
        ];
        for k in kinds {
            let s = k.to_string();
            let rank = root_kind_rank(Some(&s));
            assert!(rank <= 4, "rank for {s} should be <= 4, got {rank}");
        }
    }

    // ---- §5.2 rank_root_candidates ----

    #[test]
    fn test_rank_root_candidates_prefers_type_over_homonym() {
        // Mirrors the UserService.cs fixture: `csharp_class` at line 12 and
        // `csharp_constructor` at line 18 share the name `UserService`.
        let candidates = vec![
            RootCandidate {
                uuid: "uuid-constructor".to_string(),
                name: "UserService".to_string(),
                fqn: Some("CodeMap.Services.UserService.UserService".to_string()),
                kind: Some("csharp_constructor".to_string()),
                signature: None,
                docstring: None,
                file_path: Some("Services/UserService.cs".to_string()),
                start_line: Some(18),
            },
            RootCandidate {
                uuid: "uuid-class".to_string(),
                name: "UserService".to_string(),
                fqn: Some("CodeMap.Services.UserService".to_string()),
                kind: Some("csharp_class".to_string()),
                signature: None,
                docstring: None,
                file_path: Some("Services/UserService.cs".to_string()),
                start_line: Some(12),
            },
        ];
        let ranked = rank_root_candidates(candidates);
        assert_eq!(ranked.len(), 2);
        assert_eq!(ranked[0].kind.as_deref(), Some("csharp_class"));
        assert_eq!(ranked[1].kind.as_deref(), Some("csharp_constructor"));
    }

    #[test]
    fn test_rank_root_candidates_tie_breaks_by_file_then_line_then_uuid() {
        // Two classes with the same name and kind: file_path breaks the tie.
        let a = RootCandidate {
            uuid: "uuid-a".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/z/config.cs".to_string()),
            start_line: Some(10),
        };
        let b = RootCandidate {
            uuid: "uuid-b".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/a/config.cs".to_string()),
            start_line: Some(50),
        };
        let ranked = rank_root_candidates(vec![a, b]);
        assert_eq!(ranked[0].file_path.as_deref(), Some("src/a/config.cs"));
        assert_eq!(ranked[1].file_path.as_deref(), Some("src/z/config.cs"));

        // Now same path, different lines: lower line wins.
        let c = RootCandidate {
            uuid: "uuid-c".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/a/config.cs".to_string()),
            start_line: Some(100),
        };
        let d = RootCandidate {
            uuid: "uuid-d".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/a/config.cs".to_string()),
            start_line: Some(20),
        };
        let ranked = rank_root_candidates(vec![c, d]);
        assert_eq!(ranked[0].start_line, Some(20));
        assert_eq!(ranked[1].start_line, Some(100));

        // Same path, same line, different uuid: lexicographic uuid wins.
        let e = RootCandidate {
            uuid: "uuid-zzz".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/a/config.cs".to_string()),
            start_line: Some(20),
        };
        let f = RootCandidate {
            uuid: "uuid-aaa".to_string(),
            name: "Config".to_string(),
            fqn: Some("a.Config".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("src/a/config.cs".to_string()),
            start_line: Some(20),
        };
        let ranked = rank_root_candidates(vec![e, f]);
        assert_eq!(ranked[0].uuid, "uuid-aaa");
        assert_eq!(ranked[1].uuid, "uuid-zzz");
    }

    #[test]
    fn test_rank_root_candidates_is_stable_for_equal_keys() {
        // Equal (rank, file_path, start_line, uuid) must preserve input order
        // (Vec::sort_by is stable).
        let make = |uuid: &str| RootCandidate {
            uuid: uuid.to_string(),
            name: "Same".to_string(),
            fqn: Some("x.Same".to_string()),
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("file.cs".to_string()),
            start_line: Some(1),
        };
        let input = vec![make("uuid-1"), make("uuid-2"), make("uuid-3")];
        let ranked = rank_root_candidates(input);
        assert_eq!(
            ranked.iter().map(|c| c.uuid.as_str()).collect::<Vec<_>>(),
            vec!["uuid-1", "uuid-2", "uuid-3"],
            "stable sort must preserve input order for equal keys"
        );
    }

    #[test]
    fn test_rank_root_candidates_handles_missing_fields() {
        // Missing kind → rank 4 (treated as a tail catch-all).
        // Missing file_path / start_line defaults to "" / 0.
        let a = RootCandidate {
            uuid: "uuid-no-kind".to_string(),
            name: "M".to_string(),
            fqn: None,
            kind: None,
            signature: None,
            docstring: None,
            file_path: Some("a/x.cs".to_string()),
            start_line: Some(10),
        };
        let b = RootCandidate {
            uuid: "uuid-class".to_string(),
            name: "M".to_string(),
            fqn: None,
            kind: Some("csharp_class".to_string()),
            signature: None,
            docstring: None,
            file_path: Some("a/x.cs".to_string()),
            start_line: Some(10),
        };
        let ranked = rank_root_candidates(vec![a, b]);
        assert_eq!(ranked[0].kind.as_deref(), Some("csharp_class"));
        assert_eq!(ranked[1].kind, None);
    }

    // ---- §Truncation quantification (v1.10.0) ----------------------------

    fn dummy_targets(n: usize) -> Vec<TargetRow> {
        (0..n)
            .map(|i| TargetRow {
                uuid: format!("uuid-{}", i),
                name: "delete".to_string(),
                fqn: format!("repo::module::delete_{}", i),
                kind: "method".to_string(),
                file_path: format!("src/file_{}.rs", i),
                start_line: i as i64,
                repo_name: String::new(),
            })
            .collect()
    }

    #[test]
    fn finalize_targets_total_is_pre_truncation_count() {
        // 40 rows capped at 25: `total` must report the real 40, not the
        // sample size 25. This is the regression pinned by the v1.10.0 fix —
        // measuring after `truncate` made the truncation notice read
        // "25 targets matched; showing the first 25".
        let resolved =
            finalize_targets(dummy_targets(40), MatchTier::ExactName, DEFAULT_MAX_TARGETS);
        assert_eq!(resolved.total, 40);
        assert_eq!(resolved.targets.len(), DEFAULT_MAX_TARGETS);
        assert!(resolved.truncated);
        assert!(!resolved.targets.is_empty());
    }

    #[test]
    fn finalize_targets_not_truncated_when_under_cap() {
        let resolved =
            finalize_targets(dummy_targets(10), MatchTier::ExactName, DEFAULT_MAX_TARGETS);
        assert_eq!(resolved.total, 10);
        assert_eq!(resolved.targets.len(), 10);
        assert!(!resolved.truncated);
    }

    #[test]
    fn finalize_targets_keeps_everything_when_cap_exceeds_total() {
        let resolved = finalize_targets(dummy_targets(40), MatchTier::ExactName, 100);
        assert_eq!(resolved.total, 40);
        assert_eq!(resolved.targets.len(), 40);
        assert!(!resolved.truncated);
    }

    #[test]
    fn finalize_targets_tier_is_carried_through() {
        let resolved =
            finalize_targets(dummy_targets(5), MatchTier::FqnSuffix, DEFAULT_MAX_TARGETS);
        assert!(matches!(resolved.tier, MatchTier::FqnSuffix));
    }

    #[test]
    fn find_references_resolution_clamps_ceiling() {
        // Pure assertion on the clamp expression used by find_references:
        // requested caps above MAX_TARGETS_CEILING are bounded, and 0 / tiny
        // values are bounded from below so the cap is always >= 1.
        assert_eq!(600usize.clamp(1, MAX_TARGETS_CEILING), MAX_TARGETS_CEILING);
        assert_eq!(0usize.clamp(1, MAX_TARGETS_CEILING), 1);
        assert_eq!(25usize.clamp(1, MAX_TARGETS_CEILING), 25);
    }
}