pathfinder-mcp 0.17.1

Pathfinder — The Headless IDE MCP Server for AI Coding Agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
//! `find_callers_callees` tool handler (formerly `analyze_impact`).
//!
//! LSP-powered call-hierarchy BFS with grep-based fallback when no language
//! server is available. Tool responses include `"degraded": true` and
//! `"degraded_reason"` fields to signal the fallback mode to agents.

use crate::server::helpers::{
    format_degraded_notice, millis_to_u64, parse_semantic_path, pathfinder_to_error_data,
    require_symbol_target, serialize_metadata,
};
use crate::server::types::FindCallersCalleesParams;
use crate::server::PathfinderServer;
use pathfinder_common::types::DegradedReason;
use pathfinder_lsp::LspError;
use rmcp::model::{CallToolResult, ErrorData};

/// Wall-clock timeout for BFS traversal in `find_callers_callees`.
/// Prevents infinite loops if the LSP keeps returning more references.
const BFS_TIMEOUT_SECS: u64 = 30;

/// Maximum consecutive LSP failures before aborting BFS traversal.
/// When the LSP is non-responsive, this provides a fast exit path
/// without waiting for the full wall-clock timeout on each step.
/// A responsive LSP may occasionally fail once (e.g., transient error),
/// but 2 consecutive failures strongly indicate a hung/stuck LSP.
const BFS_CONSECUTIVE_FAILURE_LIMIT: u32 = 2;

/// Direction for call hierarchy BFS traversal in `find_callers_callees`.
///
/// `Incoming` traverses callers (who calls this symbol).
/// `Outgoing` traverses callees (what this symbol calls).
#[derive(Debug)]
enum CallDirection {
    Incoming,
    Outgoing,
}

impl PathfinderServer {
    /// SPEC 001 + SPEC 008: Grep-based reference search fallback for `find_callers_callees`.
    ///
    /// When LSP is unavailable, warming up, or timed out, use this helper to find
    /// symbol references using ripgrep with Tree-sitter enrichment (SPEC 008).
    ///
    /// SPEC 008: Uses `search_codebase_impl` with `filter_mode=CodeOnly` to exclude
    /// matches in comments and string literals.
    ///
    /// Returns `Some(refs)` if references found, `None` if none found.
    /// Updates `files_referenced` with the files containing matches.
    async fn grep_reference_fallback(
        &self,
        symbol_name: &str,
        definition_path: &std::path::Path,
        files_referenced: &mut std::collections::HashSet<String>,
    ) -> Option<Vec<crate::server::types::ImpactReference>> {
        let search_params = crate::server::types::SearchCodebaseParams {
            query: symbol_name.to_string(),
            is_regex: false,
            path_glob: "**/*".to_string(),
            filter_mode: pathfinder_common::types::FilterMode::CodeOnly,
            max_results: 20,
            context_lines: 0,
            known_files: vec![],
            group_by_file: false,
            exclude_glob: String::new(),
            offset: 0,
        };

        let result = match self.search_codebase_impl(search_params).await {
            Ok(r) => r,
            Err(e) => {
                tracing::warn!(
                    tool = "grep_reference_fallback",
                    symbol = %symbol_name,
                    error = %e,
                    "search_codebase_impl failed during grep fallback"
                );
                return None;
            }
        };

        if result.0.matches.is_empty() {
            return None;
        }

        let refs: Vec<crate::server::types::ImpactReference> = result
            .0
            .matches
            .into_iter()
            .filter(|m| {
                let m_path = std::path::Path::new(&m.file);
                super::is_source_file(&m.file) && m_path != definition_path
            })
            .take(10)
            .map(|m| {
                files_referenced.insert(m.file.clone());
                let semantic_path = m
                    .enclosing_semantic_path
                    .clone()
                    .unwrap_or_else(|| format!("{}::{symbol_name}", m.file));
                crate::server::types::ImpactReference {
                    semantic_path,
                    file: m.file,
                    line: usize::try_from(m.line).unwrap_or(usize::MAX),
                    snippet: m.content,
                    direction: "incoming_heuristic".to_string(),
                    depth: 0,
                    confidence: Some("heuristic".to_owned()),
                }
            })
            .collect();

        if refs.is_empty() {
            None
        } else {
            Some(refs)
        }
    }

    /// DELIVERABLE F: Grep-based outgoing dependency discovery for `find_callers_callees`.
    ///
    /// When LSP is unavailable, extract call candidates from the symbol's source code
    /// and resolve each candidate to its definition using grep search.
    ///
    /// Returns `Some(refs)` if outgoing dependencies found, `None` if none found.
    /// Updates `files_referenced` with the files containing matches.
    async fn grep_outgoing_fallback(
        &self,
        scope_content: &str,
        scope_language: &str,
        definition_path: &std::path::Path,
        max_results: u32,
        project_only: bool,
        files_referenced: &mut std::collections::HashSet<String>,
    ) -> Option<Vec<crate::server::types::ImpactReference>> {
        let candidates = super::extract_call_candidates(scope_content, scope_language);

        if candidates.is_empty() {
            tracing::info!(
                tool = "grep_outgoing_fallback",
                language = %scope_language,
                "no call candidates found in symbol body"
            );
            return None;
        }

        tracing::info!(
            tool = "grep_outgoing_fallback",
            candidate_count = candidates.len(),
            language = %scope_language,
            "resolving {} outgoing candidates",
            candidates.len()
        );

        let max_deps = max_results as usize;
        let mut refs = Vec::new();
        let mut seen = std::collections::HashSet::new();

        for candidate in candidates {
            if refs.len() >= max_deps {
                break;
            }

            let pattern = super::candidate_definition_pattern(scope_language, &candidate);
            let path_glob = super::language_to_file_glob(scope_language);

            let result = self
                .scout
                .search(&pathfinder_search::SearchParams {
                    workspace_root: self.workspace_root.path().to_path_buf(),
                    query: pattern,
                    is_regex: true,
                    max_results: 4,
                    path_glob: path_glob.to_string(),
                    exclude_glob: String::default(),
                    context_lines: 0,
                    offset: 0,
                })
                .await;

            match result {
                Ok(search_result) => {
                    let mut found = false;
                    for m in &search_result.matches {
                        if found {
                            break;
                        }
                        if project_only
                            && (!super::is_source_file(&m.file)
                                || !super::is_workspace_file(&m.file))
                        {
                            continue;
                        }

                        let m_path = std::path::Path::new(&m.file);
                        if m_path == definition_path {
                            continue;
                        }

                        let semantic_path = format!("{}::{}", m.file, candidate);

                        if seen.contains(&semantic_path) {
                            continue;
                        }
                        seen.insert(semantic_path.clone());

                        files_referenced.insert(m.file.clone());

                        refs.push(crate::server::types::ImpactReference {
                            semantic_path,
                            file: m.file.clone(),
                            line: usize::try_from(m.line).unwrap_or(usize::MAX),
                            snippet: m.content.clone(),
                            direction: "outgoing_heuristic".to_string(),
                            depth: 0,
                            confidence: Some("heuristic".to_owned()),
                        });
                        found = true;
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        tool = "grep_outgoing_fallback",
                        candidate = %candidate,
                        error = %e,
                        "search failed for candidate"
                    );
                }
            }
        }

        if refs.is_empty() {
            None
        } else {
            tracing::info!(
                tool = "grep_outgoing_fallback",
                resolved_count = refs.len(),
                "resolved {} outgoing dependencies",
                refs.len()
            );
            Some(refs)
        }
    }

    /// Performs BFS traversal of the call hierarchy in the specified direction.
    ///
    /// Added wall-clock timeout to prevent infinite loops when LSP keeps returning references.
    ///
    /// Returns the collected references and the maximum depth reached during traversal.
    #[allow(clippy::too_many_lines)]
    async fn bfs_call_hierarchy(
        &self,
        initial_item: &pathfinder_lsp::types::CallHierarchyItem,
        direction: CallDirection,
        max_depth: u32,
        files_referenced: &mut std::collections::HashSet<String>,
        project_only: bool,
        remaining_references: &mut u32,
    ) -> (Vec<crate::server::types::ImpactReference>, u32) {
        let timeout = tokio::time::Duration::from_secs(BFS_TIMEOUT_SECS);
        let deadline = tokio::time::Instant::now() + timeout;

        let mut queue = std::collections::VecDeque::new();
        queue.push_back((initial_item.clone(), 0));
        let mut seen = std::collections::HashSet::new();
        seen.insert((
            initial_item.file.clone(),
            initial_item.line,
            initial_item.name.clone(),
        ));
        files_referenced.insert(initial_item.file.clone());

        let mut references = Vec::new();
        let mut max_depth_reached = 0;
        let mut consecutive_failures: u32 = 0;

        while let Some((item, current_depth)) = queue.pop_front() {
            max_depth_reached = std::cmp::max(max_depth_reached, current_depth);
            if current_depth >= max_depth {
                continue;
            }
            if *remaining_references == 0 {
                break;
            }

            // Check wall-clock timeout
            if tokio::time::Instant::now() >= deadline {
                tracing::warn!(
                    direction = ?direction,
                    timeout_secs = BFS_TIMEOUT_SECS,
                    "BFS traversal exceeded wall-clock timeout, returning partial results"
                );
                break;
            }

            // Check consecutive failure limit — fast exit when LSP is hung
            if consecutive_failures >= BFS_CONSECUTIVE_FAILURE_LIMIT {
                tracing::warn!(
                    direction = ?direction,
                    consecutive_failures,
                    limit = BFS_CONSECUTIVE_FAILURE_LIMIT,
                    "BFS aborted: too many consecutive LSP failures, returning partial results"
                );
                break;
            }

            let hierarchy_result = match direction {
                CallDirection::Incoming => {
                    self.lawyer
                        .call_hierarchy_incoming(self.workspace_root.path(), &item)
                        .await
                }
                CallDirection::Outgoing => {
                    self.lawyer
                        .call_hierarchy_outgoing(self.workspace_root.path(), &item)
                        .await
                }
            };

            match hierarchy_result {
                Ok(calls) => {
                    consecutive_failures = 0;
                    for call in calls {
                        if *remaining_references == 0 {
                            break;
                        }

                        let referenced_item = call.item;

                        // Filter out non-workspace files when project_only:
                        // - Must have a source code extension
                        // - Must be a relative path (not absolute like stdlib/SDK paths)
                        // - Must not be in node_modules/ or vendor/
                        if project_only
                            && (!super::is_source_file(&referenced_item.file)
                                || !super::is_workspace_file(&referenced_item.file))
                        {
                            continue;
                        }

                        files_referenced.insert(referenced_item.file.clone());

                        let key = (
                            referenced_item.file.clone(),
                            referenced_item.line,
                            referenced_item.name.clone(),
                        );
                        if seen.insert(key) {
                            queue.push_back((referenced_item.clone(), current_depth + 1));

                            references.push(crate::server::types::ImpactReference {
                                semantic_path: format!(
                                    "{}::{}",
                                    referenced_item.file, referenced_item.name
                                ),
                                file: referenced_item.file.clone(),
                                line: referenced_item.line as usize,
                                snippet: referenced_item
                                    .detail
                                    .unwrap_or_else(|| referenced_item.name.clone()),
                                direction: match direction {
                                    CallDirection::Incoming => "incoming".to_owned(),
                                    CallDirection::Outgoing => "outgoing".to_owned(),
                                },
                                depth: current_depth as usize,
                                confidence: Some("lsp".to_owned()),
                            });
                            *remaining_references -= 1;
                        }
                    }
                }
                Err(e) => {
                    consecutive_failures += 1;
                    let direction_name = match direction {
                        CallDirection::Incoming => "call_hierarchy_incoming",
                        CallDirection::Outgoing => "call_hierarchy_outgoing",
                    };
                    tracing::warn!(
                        tool = "find_callers_callees",
                        error = %e,
                        file = %item.file,
                        line = item.line,
                        depth = current_depth,
                        "{direction_name} failed during BFS (partial impact graph)"
                    );
                }
            }
        }

        (references, max_depth_reached)
    }

    /// Core logic for the `find_callers_callees` tool.
    ///
    /// Returns callers (incoming) and callees (outgoing) for the target symbol.
    /// Degrades gracefully to empty results when no LSP is configured.
    #[expect(
        clippy::too_many_lines,
        reason = "Sequential pipeline (parse→sandbox→tree-sitter→LSP→BFS→version hash)."
    )]
    pub(crate) async fn find_callers_callees_impl(
        &self,
        params: FindCallersCalleesParams,
    ) -> Result<CallToolResult, ErrorData> {
        let start = std::time::Instant::now();

        // Cap max_depth to prevent unbounded BFS traversal (PRD §5.1 maximum).
        // Also floor at 1 to guarantee at least one level of traversal.
        let max_depth = params.max_depth.clamp(1, 5);
        let project_only = params.project_only.unwrap_or(true);
        // Clamp max_references to minimum 1 to prevent silently empty results.
        let max_references = params.max_references.max(1);
        // Split budget between incoming and outgoing. Give any odd slot to incoming.
        let half = max_references / 2;
        let mut remaining_incoming = half + max_references % 2;
        let mut remaining_outgoing = half;

        tracing::info!(
            tool = "find_callers_callees",
            semantic_path = %params.semantic_path,
            max_depth = max_depth,
            "find_callers_callees: start"
        );

        // Parse and validate the semantic path
        let semantic_path = parse_semantic_path(&params.semantic_path)?;
        require_symbol_target(&semantic_path, &params.semantic_path)?;

        // Sandbox check
        if let Err(e) = self.sandbox.check(&semantic_path.file_path) {
            let duration_ms = start.elapsed().as_millis();
            tracing::warn!(
                tool = "find_callers_callees",
                error_code = e.error_code(),
                duration_ms,
                "sandbox check failed"
            );
            return Err(pathfinder_to_error_data(&e));
        }

        // Early file existence check — avoid tree-sitter parse on nonexistent files
        let abs_file = self.workspace_root.path().join(&semantic_path.file_path);
        if !abs_file.exists() {
            let err = pathfinder_common::error::PathfinderError::FileNotFound {
                path: abs_file.clone(),
            };
            tracing::warn!(
                tool = "find_callers_callees",
                path = %abs_file.display(),
                "file not found"
            );
            return Err(pathfinder_to_error_data(&err));
        }

        // 1. Fetch the symbol scope (Tree-sitter) to get start line
        let ts_start = std::time::Instant::now();
        let scope = match self
            .read_symbol_scope_enriched(&semantic_path, &params.semantic_path)
            .await
        {
            Ok(s) => s,
            Err(e) => {
                let duration_ms = start.elapsed().as_millis();
                tracing::warn!(
                    tool = "find_callers_callees",
                    error = %e,
                    duration_ms,
                    "tree-sitter read failed"
                );
                return Err(e);
            }
        };
        let tree_sitter_ms = ts_start.elapsed().as_millis();

        // IW-3 (DS-1 gap fix): RAII document lifecycle — did_close fires on all exits.
        let file_path = self.workspace_root.path().join(&semantic_path.file_path);
        let file_content = match tokio::fs::read_to_string(&file_path).await {
            Ok(content) => content,
            Err(e) => {
                tracing::warn!(
                    tool = "find_callers_callees",
                    path = %file_path.display(),
                    error = %e,
                    "file read failed — LSP will receive empty content"
                );
                String::new()
            }
        };
        // `_doc_guard` fires did_close automatically when this function returns.
        let _doc_guard = match self
            .lawyer
            .open_document(
                self.workspace_root.path(),
                &semantic_path.file_path,
                &file_content,
            )
            .await
        {
            Ok(guard) => Some(guard),
            Err(e) => {
                tracing::warn!(
                    tool = "find_callers_callees",
                    semantic_path = %semantic_path,
                    error = %e,
                    "open_document failed — LSP queries may return degraded results"
                );
                None
            }
        };

        let lsp_start = std::time::Instant::now();
        // Use Option<Vec> to distinguish "unknown" (LSP unavailable) from "verified empty" (LSP confirmed zero).
        // None = degraded (LSP was down — callers are unknown, do NOT treat as zero)
        // Some([]) = LSP responded with confirmed zero callers/callees
        let mut incoming: Option<Vec<crate::server::types::ImpactReference>> = None;
        let mut outgoing: Option<Vec<crate::server::types::ImpactReference>> = None;
        let mut degraded = true;
        let mut degraded_reason = Some(DegradedReason::NoLsp);
        let mut engines = vec!["tree-sitter"];
        let mut files_referenced = std::collections::HashSet::new();
        let mut max_depth_reached = 0;

        let lsp_result = self
            .lawyer
            .call_hierarchy_prepare(
                self.workspace_root.path(),
                &semantic_path.file_path,
                u32::try_from(scope.start_line + 1).unwrap_or(1),
                // Position cursor on the symbol's name identifier (e.g., the 'd' in 'dedent'),
                // not the 'pub' keyword. rust-analyzer requires this for symbol resolution.
                u32::try_from(scope.name_column + 1).unwrap_or(1),
            )
            .await;

        match lsp_result {
            Ok(items) if !items.is_empty() => {
                engines.push("lsp");
                degraded = false;
                degraded_reason = None;

                let initial_item = &items[0];
                files_referenced.insert(initial_item.file.clone());

                // --- INCOMING BFS ---
                let (incoming_refs, depth_in) = self
                    .bfs_call_hierarchy(
                        initial_item,
                        CallDirection::Incoming,
                        max_depth,
                        &mut files_referenced,
                        project_only,
                        &mut remaining_incoming,
                    )
                    .await;
                incoming = Some(incoming_refs);
                max_depth_reached = std::cmp::max(max_depth_reached, depth_in);

                // --- OUTGOING BFS ---
                let (outgoing_refs, depth_out) = self
                    .bfs_call_hierarchy(
                        initial_item,
                        CallDirection::Outgoing,
                        max_depth,
                        &mut files_referenced,
                        project_only,
                        &mut remaining_outgoing,
                    )
                    .await;
                outgoing = Some(outgoing_refs);
                max_depth_reached = std::cmp::max(max_depth_reached, depth_out);

                // Check for false negatives when BFS call hierarchy traversal returns 0 callers/callees
                if incoming.as_ref().is_none_or(Vec::is_empty)
                    && outgoing.as_ref().is_none_or(Vec::is_empty)
                {
                    let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();
                    let mut grep_incoming = None;
                    let mut grep_outgoing = None;

                    if let Some(refs) = self
                        .grep_reference_fallback(
                            &symbol_name,
                            &semantic_path.file_path,
                            &mut files_referenced,
                        )
                        .await
                    {
                        if !refs.is_empty() {
                            grep_incoming = Some(refs);
                        }
                    }

                    if let Some(refs) = self
                        .grep_outgoing_fallback(
                            &scope.content,
                            &scope.language,
                            &semantic_path.file_path,
                            remaining_outgoing,
                            project_only,
                            &mut files_referenced,
                        )
                        .await
                    {
                        if !refs.is_empty() {
                            grep_outgoing = Some(refs);
                        }
                    }

                    degraded = true;
                    degraded_reason = Some(DegradedReason::LspWarmupGrepFallback);
                    if grep_incoming.is_some() {
                        incoming = grep_incoming;
                    }
                    if grep_outgoing.is_some() {
                        outgoing = grep_outgoing;
                    }
                }
            }
            Ok(_) => {
                // LSP responded with empty items — but this is ambiguous:
                //   - Genuine "zero callers": LSP is warm and the symbol truly has no references.
                //   - LSP warmup: LSP hasn't finished indexing and returned [] for everything.
                //
                // Probe goto_definition at the same position. A warm LSP can resolve a symbol
                // to its definition; a cold LSP returns None even for well-known symbols.
                // If the probe returns Ok(Some(_)) the LSP is warm → confirmed zero callers.
                // If the probe returns Ok(None) or Err, we degrade rather than lying to the agent.
                let probe = self
                    .lawyer
                    .goto_definition(
                        self.workspace_root.path(),
                        &semantic_path.file_path,
                        u32::try_from(scope.start_line + 1).unwrap_or(1),
                        u32::try_from(scope.name_column + 1).unwrap_or(1),
                    )
                    .await;

                if matches!(probe, Ok(Some(_))) {
                    // LSP is warm — definition resolved. But let's check for false negatives (indexing incomplete, etc.)
                    // by running grep fallback.
                    let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();
                    let mut grep_incoming = None;
                    let mut grep_outgoing = None;

                    if let Some(refs) = self
                        .grep_reference_fallback(
                            &symbol_name,
                            &semantic_path.file_path,
                            &mut files_referenced,
                        )
                        .await
                    {
                        if !refs.is_empty() {
                            grep_incoming = Some(refs);
                        }
                    }

                    if let Some(refs) = self
                        .grep_outgoing_fallback(
                            &scope.content,
                            &scope.language,
                            &semantic_path.file_path,
                            remaining_outgoing,
                            project_only,
                            &mut files_referenced,
                        )
                        .await
                    {
                        if !refs.is_empty() {
                            grep_outgoing = Some(refs);
                        }
                    }

                    engines.push("lsp");
                    degraded = true;
                    degraded_reason = Some(DegradedReason::LspWarmupGrepFallback);
                    incoming = grep_incoming.or(Some(Vec::new()));
                    outgoing = grep_outgoing.or(Some(Vec::new()));
                } else {
                    // LSP likely still warming up — empty call hierarchy is not reliable.
                    // Degrade so agents know to verify before acting on "zero references".
                    tracing::info!(
                        tool = "find_callers_callees",
                        symbol = %semantic_path,
                        "find_callers_callees: call_hierarchy_prepare returned [] but goto_definition \
                         probe returned no result — LSP likely warming up, attempting grep-based reference fallback"
                    );
                    engines.push("lsp");
                    degraded = true;
                    degraded_reason = Some(DegradedReason::LspWarmupEmptyUnverified);

                    let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();

                    let mut grep_fallback_found = false;

                    if let Some(refs) = self
                        .grep_reference_fallback(
                            &symbol_name,
                            &semantic_path.file_path,
                            &mut files_referenced,
                        )
                        .await
                    {
                        incoming = Some(refs);
                        grep_fallback_found = true;
                        tracing::info!(
                            tool = "find_callers_callees",
                            references_found = incoming.as_ref().map_or(0, Vec::len),
                            "find_callers_callees: grep-based fallback references found during LSP warmup"
                        );
                    }

                    if let Some(refs) = self
                        .grep_outgoing_fallback(
                            &scope.content,
                            &scope.language,
                            &semantic_path.file_path,
                            remaining_outgoing,
                            project_only,
                            &mut files_referenced,
                        )
                        .await
                    {
                        outgoing = Some(refs);
                        grep_fallback_found = true;
                        tracing::info!(
                            tool = "find_callers_callees",
                            outgoing_found = outgoing.as_ref().map_or(0, Vec::len),
                            "find_callers_callees: grep-based outgoing deps found during LSP warmup"
                        );
                    }

                    if grep_fallback_found {
                        degraded_reason = Some(DegradedReason::LspWarmupGrepFallback);
                    }
                }
            }
            Err(LspError::NoLspAvailable | LspError::UnsupportedCapability { .. }) => {
                // Degraded mode — LSP not available. Use grep-based reference search
                // as a heuristic fallback. Results may over-count (string references)
                // or under-count (indirect calls), but give the agent a starting point.
                tracing::info!(
                    tool = "find_callers_callees",
                    symbol = %semantic_path,
                    "find_callers_callees: no LSP — attempting grep-based reference fallback"
                );

                let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();
                let mut grep_fallback_found = false;

                if let Some(refs) = self
                    .grep_reference_fallback(
                        &symbol_name,
                        &semantic_path.file_path,
                        &mut files_referenced,
                    )
                    .await
                {
                    incoming = Some(refs);
                    grep_fallback_found = true;
                    tracing::info!(
                        tool = "find_callers_callees",
                        references_found = incoming.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based fallback references found"
                    );
                }

                if let Some(refs) = self
                    .grep_outgoing_fallback(
                        &scope.content,
                        &scope.language,
                        &semantic_path.file_path,
                        remaining_outgoing,
                        project_only,
                        &mut files_referenced,
                    )
                    .await
                {
                    outgoing = Some(refs);
                    grep_fallback_found = true;
                    tracing::info!(
                        tool = "find_callers_callees",
                        outgoing_found = outgoing.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based outgoing deps found"
                    );
                }

                if grep_fallback_found {
                    degraded_reason = Some(DegradedReason::NoLspGrepFallback);
                }
            }
            Err(LspError::Timeout { .. }) => {
                // LSP timed out — attempt grep-based reference fallback.
                // Set reason unconditionally: timeout is always the cause, whether or not
                // grep succeeds. Without this, empty grep results would fall through to the
                // initial NoLsp reason, misleading agents into thinking no LSP exists.
                degraded_reason = Some(DegradedReason::LspTimeoutGrepFallback);

                tracing::info!(
                    tool = "find_callers_callees",
                    symbol = %semantic_path,
                    "find_callers_callees: LSP timed out — attempting grep-based reference fallback"
                );

                let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();

                if let Some(refs) = self
                    .grep_reference_fallback(
                        &symbol_name,
                        &semantic_path.file_path,
                        &mut files_referenced,
                    )
                    .await
                {
                    incoming = Some(refs);
                    tracing::info!(
                        tool = "find_callers_callees",
                        references_found = incoming.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based fallback references found after timeout"
                    );
                }

                if let Some(refs) = self
                    .grep_outgoing_fallback(
                        &scope.content,
                        &scope.language,
                        &semantic_path.file_path,
                        remaining_outgoing,
                        project_only,
                        &mut files_referenced,
                    )
                    .await
                {
                    outgoing = Some(refs);
                    tracing::info!(
                        tool = "find_callers_callees",
                        outgoing_found = outgoing.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based outgoing deps found after timeout"
                    );
                }
            }
            Err(e) => {
                // LSP returned an unexpected error — not "no LSP" but an operational failure.
                // Set reason unconditionally: LspErrorGrepFallback describes the cause whether
                // or not grep finds anything. NoLsp would be misleading — the LSP exists but
                // failed, which is a different agent guidance scenario (retry vs. install).
                degraded = true;
                degraded_reason = Some(DegradedReason::LspErrorGrepFallback);

                tracing::warn!(
                    tool = "find_callers_callees",
                    error = %e,
                    "call_hierarchy_prepare failed"
                );

                let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();

                if let Some(refs) = self
                    .grep_reference_fallback(
                        &symbol_name,
                        &semantic_path.file_path,
                        &mut files_referenced,
                    )
                    .await
                {
                    incoming = Some(refs);
                    tracing::info!(
                        tool = "find_callers_callees",
                        references_found = incoming.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based fallback references found after LSP error"
                    );
                }

                if let Some(refs) = self
                    .grep_outgoing_fallback(
                        &scope.content,
                        &scope.language,
                        &semantic_path.file_path,
                        remaining_outgoing,
                        project_only,
                        &mut files_referenced,
                    )
                    .await
                {
                    outgoing = Some(refs);
                    tracing::info!(
                        tool = "find_callers_callees",
                        outgoing_found = outgoing.as_ref().map_or(0, Vec::len),
                        "find_callers_callees: grep-based outgoing deps found after LSP error"
                    );
                }
            }
        }

        // Note: `_doc_guard` still alive here; did_close fires at function return.
        let lsp_ms = lsp_start.elapsed().as_millis();
        let duration_ms = start.elapsed().as_millis();

        let inc_count = incoming.as_ref().map_or(0, Vec::len);
        let out_count = outgoing.as_ref().map_or(0, Vec::len);
        let degraded_reason_cloned = degraded_reason;
        let degraded_reason_str = degraded_reason.as_ref().map(ToString::to_string);

        let lsp_readiness = if degraded {
            match degraded_reason_cloned {
                Some(
                    DegradedReason::LspWarmupEmptyUnverified
                    | DegradedReason::LspWarmupGrepFallback
                    | DegradedReason::LspTimeoutGrepFallback,
                ) => Some("warming_up".to_owned()),
                _ => Some("unavailable".to_owned()),
            }
        } else {
            Some("ready".to_owned())
        };
        let warm_start_in_progress = match lsp_readiness.as_deref() {
            Some("warming_up") => Some(true),
            Some("ready") => Some(false),
            _ => None,
        };

        tracing::info!(
            tool = "find_callers_callees",
            semantic_path = %params.semantic_path,
            tree_sitter_ms,
            lsp_ms,
            duration_ms,
            degraded,
            degraded_reason = ?degraded_reason_str,
            engines_used = ?engines,
            "find_callers_callees: complete"
        );
        // Item 2: Report truncation only when the total budget was actually exhausted,
        // not when a single direction hits its cap. Check total returned vs total budget.
        let total_returned = inc_count + out_count;
        let max_refs_usize = usize::try_from(max_references).unwrap_or(usize::MAX);
        let references_truncated = max_references > 0 && total_returned >= max_refs_usize;

        let resolution_strategy = if engines.contains(&"lsp") {
            Some("lsp_call_hierarchy".to_owned())
        } else if degraded {
            // Check which grep fallback was used based on degraded_reason
            match &degraded_reason {
                Some(
                    DegradedReason::LspWarmupGrepFallback
                    | DegradedReason::LspTimeoutGrepFallback
                    | DegradedReason::LspErrorGrepFallback
                    | DegradedReason::NoLspGrepFallback,
                ) => Some("grep_file_scoped".to_owned()),
                _ => Some("treesitter_fallback".to_owned()),
            }
        } else {
            Some("treesitter_direct".to_owned())
        };

        // Spec 4.2: Test coverage search
        let (test_callers, test_coverage_status) = if params.include_test_coverage {
            let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();

            if symbol_name.is_empty() {
                (None, Some("not_found".to_owned()))
            } else {
                let mut test_refs = Vec::new();
                let mut seen_test_positions = std::collections::HashSet::new();

                // 1. Extract from incoming callers
                if let Some(incoming_refs) = &incoming {
                    for r in incoming_refs {
                        if super::is_test_file(&r.file)
                            && seen_test_positions.insert((r.file.clone(), r.line))
                        {
                            test_refs.push(crate::server::types::ImpactReference {
                                semantic_path: r.semantic_path.clone(),
                                file: r.file.clone(),
                                line: r.line,
                                snippet: r.snippet.clone(),
                                direction: "test_coverage".to_owned(),
                                depth: 0,
                                // Inherit confidence from the source caller reference
                                confidence: r.confidence.clone(),
                            });
                        }
                    }
                }

                // 2. Search for the symbol name in test files.
                // Broad glob covers test, spec, __tests__ directories and
                // files like foo_test.rs, foo.test.ts, foo_spec.rb, test_foo.py.
                let search_params = pathfinder_search::SearchParams {
                    workspace_root: self.workspace_root.path().to_path_buf(),
                    query: symbol_name.clone(),
                    is_regex: false,
                    path_glob: "**/*{test,spec,Test,Spec,__tests__}*".to_owned(),
                    exclude_glob: String::new(),
                    max_results: 100,
                    offset: 0,
                    context_lines: 2,
                };

                match self.scout.search(&search_params).await {
                    Ok(results) => {
                        for m in results.matches {
                            if super::is_test_file(&m.file) {
                                let line = usize::try_from(m.line).unwrap_or(0);
                                if seen_test_positions.insert((m.file.clone(), line)) {
                                    let fallback_path = format!("{}:{}", m.file, m.line);
                                    test_refs.push(crate::server::types::ImpactReference {
                                        semantic_path: m
                                            .enclosing_semantic_path
                                            .unwrap_or(fallback_path),
                                        file: m.file,
                                        line,
                                        snippet: m.content,
                                        direction: "test_coverage".to_owned(),
                                        depth: 0,
                                        confidence: Some("heuristic".to_owned()),
                                    });
                                }
                            }
                        }

                        // Cap test references at 20 (just like original logic)
                        test_refs.truncate(20);

                        if test_refs.is_empty() {
                            (None, Some("not_found".to_owned()))
                        } else {
                            (Some(test_refs), Some("found".to_owned()))
                        }
                    }
                    Err(e) => {
                        tracing::warn!(
                            tool = "find_callers_callees",
                            error = %e,
                            "test coverage search failed"
                        );
                        if test_refs.is_empty() {
                            (None, Some("unknown_degraded".to_owned()))
                        } else {
                            test_refs.truncate(20);
                            (Some(test_refs), Some("found".to_owned()))
                        }
                    }
                }
            }
        } else {
            (None, None)
        };

        let metadata = crate::server::types::FindCallersCalleesMetadata {
            incoming,
            outgoing,
            depth_reached: max_depth_reached,
            files_referenced: files_referenced.len(),
            degraded,
            degraded_reason,
            actionable_guidance: degraded_reason.as_ref().map(DegradedReason::guidance),
            lsp_readiness,
            warm_start_in_progress,
            references_truncated,
            resolution_strategy,
            test_callers,
            test_coverage_status,
            duration_ms: Some(millis_to_u64(duration_ms)),
        };

        // Build honest text output based on actual results listing every
        // reference so agents can act without parsing structured_content.
        let mut text_parts = Vec::new();
        if degraded {
            let notice = degraded_reason_cloned
                .as_ref()
                .map_or_else(|| "DEGRADED (unknown)".to_owned(), format_degraded_notice);

            let symbol_name = super::last_symbol_name(&semantic_path).unwrap_or_default();

            text_parts.push(notice);
            text_parts.push(String::new());
            text_parts.push("   Common causes:".to_owned());
            text_parts.push("   - Interface types without concrete implementations in source (JPA repositories)".to_owned());
            text_parts.push(
                "   - Annotation-driven dependency injection (Spring proxies at runtime)"
                    .to_owned(),
            );
            text_parts.push("   - LSP still warming up (wait 30s, try again)".to_owned());
            text_parts.push(String::new());
            if symbol_name.is_empty() {
                text_parts
                    .push("   Workaround: Use search_codebase to find usages manually.".to_owned());
            } else {
                text_parts.push(format!(
                    "   Workaround: Use search_codebase(query=\"{symbol_name}\") to find usages manually."
                ));
            }
            text_parts.push("   Reference counts below are heuristic only:".to_owned());
            text_parts.push(String::new());
        } else if inc_count == 0 && out_count == 0 {
            text_parts.push("LSP confirmed: zero callers/callees for this symbol.".to_string());
        } else if inc_count == 0 {
            text_parts
                .push("LSP confirmed: zero incoming callers (callees found below).".to_string());
        } else if out_count == 0 {
            text_parts
                .push("LSP confirmed: zero outgoing callees (callers found below).".to_string());
        }
        // Incoming
        text_parts.push(format!("Incoming references: {inc_count}"));
        if let Some(refs) = &metadata.incoming {
            for r in refs {
                text_parts.push(format!(
                    "  [depth={}] {} ({}:L{})",
                    r.depth, r.semantic_path, r.file, r.line
                ));
                if !r.snippet.is_empty() {
                    text_parts.push(format!("    > {}", r.snippet.trim()));
                }
            }
        }
        // Outgoing
        text_parts.push(format!("Outgoing references: {out_count}"));
        if let Some(refs) = &metadata.outgoing {
            for r in refs {
                text_parts.push(format!(
                    "  [depth={}] {} ({}:L{})",
                    r.depth, r.semantic_path, r.file, r.line
                ));
                if !r.snippet.is_empty() {
                    text_parts.push(format!("    > {}", r.snippet.trim()));
                }
            }
        }

        // Spec 4.2: Test coverage section
        if let Some(test_refs) = &metadata.test_callers {
            if !test_refs.is_empty() {
                text_parts.push(String::new());
                text_parts.push(format!(
                    "TEST COVERAGE: {} test functions cover this symbol",
                    test_refs.len()
                ));
                for r in test_refs {
                    text_parts.push(format!(
                        "  - {}::{} ({}:L{})",
                        r.file, r.semantic_path, r.file, r.line
                    ));
                }
            }
        } else if let Some(status) = &metadata.test_coverage_status {
            if status == "not_found" {
                text_parts.push(String::new());
                text_parts
                    .push("TEST COVERAGE: no test functions found for this symbol".to_owned());
            } else if status == "unknown_degraded" {
                text_parts.push(String::new());
                text_parts.push("TEST COVERAGE: unknown (search degraded)".to_owned());
            }
        }

        text_parts.push(format!("[completed in {duration_ms}ms]"));
        let text = text_parts.join("\n");
        let mut res = CallToolResult::success(vec![rmcp::model::Content::text(text)]);
        res.structured_content = serialize_metadata(&metadata);
        Ok(res)
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::super::test_helpers::{make_scope, make_server_with_lawyer, make_temp_workspace};
    use super::*;
    use crate::server::types::FindCallersCalleesParams;
    use pathfinder_common::config::PathfinderConfig;
    use pathfinder_common::sandbox::Sandbox;
    use pathfinder_common::types::{DegradedReason, WorkspaceRoot};
    use pathfinder_lsp::types::{CallHierarchyCall, CallHierarchyItem};
    use pathfinder_lsp::{DefinitionLocation, MockLawyer};
    use pathfinder_search::MockScout;
    use pathfinder_treesitter::mock::MockSurgeon;
    use std::sync::Arc;

    // ── find_callers_callees ────────────────────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_returns_empty_degraded() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(pathfinder_lsp::NoOpLawyer);
        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);
        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            Arc::new(MockScout::default()),
            surgeon,
            lawyer,
        );

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(
            val.incoming.is_none(),
            "incoming must be null (not empty) when degraded"
        );
        assert!(
            val.outgoing.is_none(),
            "outgoing must be null (not empty) when degraded"
        );
        assert!(val.degraded);
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLsp));
    }

    #[tokio::test]
    async fn test_find_callers_callees_lsp_populates_incoming_and_outgoing() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "handle_request".into(),
                kind: "function".into(),
                detail: Some("fn handle_request()".into()),
                file: "src/server.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![25],
        }]));

        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "validate_token".into(),
                kind: "function".into(),
                detail: Some("fn validate_token() -> bool".into()),
                file: "src/token.rs".into(),
                line: 15,
                column: 4,
                data: None,
            },
            call_sites: vec![9],
        }]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        assert_eq!(val.degraded_reason, None);
        assert_eq!(val.depth_reached, 1); // BFS pops level 1, updates max_depth_reached, then continues
        assert_eq!(val.files_referenced, 3); // initial + caller + callee
        let incoming = val
            .incoming
            .as_ref()
            .expect("incoming must be Some when not degraded");
        let outgoing = val
            .outgoing
            .as_ref()
            .expect("outgoing must be Some when not degraded");
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].file, "src/server.rs");
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].file, "src/token.rs");
    }

    // ── find_callers_callees with empty hierarchy (confirmed zero callers) ───────

    #[tokio::test]
    async fn test_find_callers_callees_empty_hierarchy_confirmed_zero() {
        // call_hierarchy_prepare returns Ok([]) AND goto_definition probe returns Ok(Some(...))
        // → LSP is warm, confirmed zero callers. Must NOT be degraded.
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        // Empty call hierarchy — ambiguous on its own
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));
        // Probe: goto_definition succeeds → LSP is warm → confirmed zero
        lawyer.set_goto_definition_result(Ok(Some(DefinitionLocation {
            file: "src/auth.rs".into(),
            line: 10,
            column: 4,
            preview: "fn login() {}".into(),
        })));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // DEGRADED — LSP warm but call hierarchy empty
        assert!(
            val.degraded,
            "must be degraded when call hierarchy is empty"
        );
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspWarmupGrepFallback)
        );
        let incoming = val.incoming.as_ref().expect("must be Some when degraded");
        let outgoing = val.outgoing.as_ref().expect("must be Some when degraded");
        assert!(incoming.is_empty(), "confirmed zero callers");
        assert!(outgoing.is_empty(), "confirmed zero callees");
    }

    #[tokio::test]
    async fn test_find_callers_callees_empty_hierarchy_warmup_degrades() {
        // call_hierarchy_prepare returns Ok([]) AND goto_definition probe returns Ok(None)
        // → LSP is warming up. Must be degraded with "lsp_warmup_empty_unverified".
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        // Empty call hierarchy
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));
        // Probe: goto_definition returns Ok(None) → LSP is still warming up
        // MockLawyer::default() already returns Ok(None) for goto_definition, so no extra setup needed.

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // DEGRADED — LSP warmup detected
        assert!(
            val.degraded,
            "must be degraded when goto_definition probe also returns None"
        );
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspWarmupEmptyUnverified),
            "degraded_reason must indicate warmup ambiguity"
        );
        // incoming/outgoing must be None — do NOT mislead agent with Some([])
        assert!(
            val.incoming.is_none(),
            "incoming must be None (unknown) during warmup, not Some([]) (confirmed-zero)"
        );
        assert!(
            val.outgoing.is_none(),
            "outgoing must be None (unknown) during warmup, not Some([]) (confirmed-zero)"
        );
    }

    // ── find_callers_callees with LSP error on call_hierarchy_prepare ────────────

    #[tokio::test]
    async fn test_find_callers_callees_lsp_error_degrades() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        // Simulate LSP protocol error
        lawyer
            .push_prepare_call_hierarchy_result(Err(LspError::Protocol("LSP crashed".to_string())));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // Degraded due to LSP error — must report LspErrorGrepFallback, not NoLsp.
        // NoLsp would mislead agents into "install LSP" when the real cause is a transient error.
        assert!(val.degraded);
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspErrorGrepFallback)
        );
    }

    // ── find_callers_callees BFS depth limiting ────────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_bfs_respects_max_depth() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        // Incoming: one caller that itself has a caller (depth 2 chain)
        let caller_item = CallHierarchyItem {
            name: "caller".into(),
            kind: "function".into(),
            detail: None,
            file: "src/caller.rs".into(),
            line: 5,
            column: 4,
            data: None,
        };
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: caller_item.clone(),
            call_sites: vec![9],
        }]));
        // Second level incoming (would only be reached if max_depth > 1)
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "top_level".into(),
                kind: "function".into(),
                detail: None,
                file: "src/main.rs".into(),
                line: 1,
                column: 0,
                data: None,
            },
            call_sites: vec![5],
        }]));

        // Outgoing: empty
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1, // Should stop after first level
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let _incoming = val.incoming.as_ref().expect("must be Some");
        // With max_depth=1, BFS processes the initial item at depth 0, finds caller at depth 1,
        // but the second-level caller (depth 2) should NOT be included
        // However depth_reached should be 1
        assert_eq!(val.depth_reached, 1);
    }

    // ── CG-3: sandbox check error in find_callers_callees ──────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_rejects_sandbox_denied_path() {
        let surgeon = Arc::new(MockSurgeon::new());
        let lawyer = Arc::new(MockLawyer::default());
        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: ".git/objects/abc::def".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let Err(err) = result else {
            panic!("expected error but got Ok");
        };
        let code = err
            .data
            .as_ref()
            .and_then(|d| d.get("error"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        assert_eq!(code, "ACCESS_DENIED");
    }

    // ── CG-4: Tree-sitter error in find_callers_callees ──────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_tree_sitter_error() {
        let surgeon = Arc::new(MockSurgeon::new());
        // Push an error result
        surgeon.read_symbol_scope_results.lock().unwrap().push(Err(
            pathfinder_treesitter::SurgeonError::ParseError {
                path: std::path::PathBuf::from("src/auth.rs"),
                reason: "parse failed".to_string(),
            },
        ));

        let lawyer = Arc::new(MockLawyer::default());
        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        assert!(result.is_err(), "tree-sitter error should propagate");
    }

    // ── CG-5: LSP error during BFS traversal ───────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_bfs_lsp_error_graceful_partial_graph() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        // Incoming succeeds with one caller
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "caller".into(),
                kind: "function".into(),
                detail: None,
                file: "src/server.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![9],
        }]));
        // Outgoing fails with LSP error
        lawyer.push_outgoing_call_result(Err(LspError::Protocol(
            "LSP crashed during outgoing".to_string(),
        )));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed despite partial failure");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // NOT degraded — prepare succeeded, incoming succeeded, only outgoing had error
        assert!(!val.degraded);
        let incoming = val.incoming.as_ref().expect("incoming must be Some");
        assert_eq!(incoming.len(), 1, "incoming caller should be present");
        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        assert!(outgoing.is_empty(), "outgoing should be empty due to error");
    }

    // ── CG-1: Grep fallback path in find_callers_callees ─────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_grep_fallback_with_mock_scout() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        // SPEC 008: search_codebase_impl calls enclosing_symbol_detail for each match
        // We have 1 match, so push 1 enclosing_symbol_detail_result
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        // Create a file so the version hash computation has something to read
        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/auth.rs"),
            "fn login() -> bool { true }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());
        // Create a caller file (different from the definition file)
        std::fs::write(
            ws_dir.path().join("src/caller.rs"),
            "fn handle_request() { login(); }",
        )
        .unwrap();
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![pathfinder_search::SearchMatch {
                file: "src/caller.rs".to_string(),
                line: 1,
                column: 1,
                content: "fn handle_request() { login(); }".to_string(),
                context_before: vec![],
                context_after: vec![],
                enclosing_semantic_path: None,
                is_definition: None,
                version_hash: "sha256:abc".to_string(),
                known: Some(false),
            }],
            total_matches: 1,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLspGrepFallback));
        let incoming = val.incoming.as_ref().expect("must be Some from grep");
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].file, "src/caller.rs");
        assert_eq!(incoming[0].direction, "incoming_heuristic");
    }

    // ── PATCH-002: Non-source file filtering in grep fallback ───────────

    #[tokio::test]
    #[allow(clippy::too_many_lines)]
    async fn test_find_callers_callees_grep_fallback_filters_non_source_files() {
        // Issue: grep fallback was returning matches from .md, .json, .txt, etc.
        // causing false positives. This test verifies that non-source files
        // are filtered out of the results.
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        // SPEC 008: search_codebase_impl calls enclosing_symbol_detail for each match
        // We have 4 matches, so push 4 results
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .extend([Ok(None), Ok(None), Ok(None), Ok(None)]);

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        // Create the definition file
        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/auth.rs"),
            "fn login() -> bool { true }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());
        // Return a mix of source and non-source files that match the symbol name
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![
                // Legitimate source file caller
                pathfinder_search::SearchMatch {
                    file: "src/caller.rs".to_string(),
                    line: 1,
                    column: 1,
                    content: "fn call() { login(); }".to_string(),
                    context_before: vec![],
                    context_after: vec![],
                    enclosing_semantic_path: None,
                    is_definition: None,
                    version_hash: "sha256:a".to_string(),
                    known: Some(false),
                },
                // Documentation file - should be filtered OUT
                pathfinder_search::SearchMatch {
                    file: "docs/README.md".to_string(),
                    line: 10,
                    column: 1,
                    content: "call login() to authenticate".to_string(),
                    context_before: vec![],
                    context_after: vec![],
                    enclosing_semantic_path: None,
                    is_definition: None,
                    version_hash: "sha256:b".to_string(),
                    known: Some(false),
                },
                // Config file - should be filtered OUT
                pathfinder_search::SearchMatch {
                    file: "config.json".to_string(),
                    line: 5,
                    column: 1,
                    content: "\"login\": \"/api/auth\"".to_string(),
                    context_before: vec![],
                    context_after: vec![],
                    enclosing_semantic_path: None,
                    is_definition: None,
                    version_hash: "sha256:c".to_string(),
                    known: Some(false),
                },
                // TypeScript source - should be KEPT
                pathfinder_search::SearchMatch {
                    file: "web/src/auth.ts".to_string(),
                    line: 20,
                    column: 1,
                    content: "import { login } from './api';".to_string(),
                    context_before: vec![],
                    context_after: vec![],
                    enclosing_semantic_path: None,
                    is_definition: None,
                    version_hash: "sha256:d".to_string(),
                    known: Some(false),
                },
            ],
            total_matches: 4,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLspGrepFallback));
        let incoming = val.incoming.as_ref().expect("must be Some from grep");

        // Only the 2 source files should remain (.rs and .ts)
        // .md and .json should be filtered out
        assert_eq!(
            incoming.len(),
            2,
            "non-source files should be filtered, got: {:?}",
            incoming.iter().map(|r| &r.file).collect::<Vec<_>>()
        );

        // Verify the correct files are kept
        let files: std::collections::HashSet<_> =
            incoming.iter().map(|r| r.file.as_str()).collect();
        assert!(files.contains("src/caller.rs"), "should keep .rs file");
        assert!(files.contains("web/src/auth.ts"), "should keep .ts file");
        assert!(!files.contains("docs/README.md"), "should filter .md file");
        assert!(!files.contains("config.json"), "should filter .json file");
    }

    // ── DS-1: DocumentGuard lifecycle tests ──────────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_closes_document_on_success() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer.clone());
        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            ..Default::default()
        };

        let _ = server.find_callers_callees_impl(params).await;

        tokio::task::yield_now().await;

        assert_eq!(
            lawyer.did_open_call_count(),
            lawyer.did_close_call_count(),
            "DS-1: did_open and did_close must be symmetric in find_callers_callees"
        );
    }

    // ── TASK-2: project_only filter ───────────────────────────────────────────

    /// With `project_only = false`, stdlib/absolute-path items should pass through
    /// the BFS filter and appear in the impact graph.
    #[tokio::test]
    async fn test_find_callers_callees_project_only_false_includes_external_refs() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        // Incoming: a project file (should be included regardless of project_only)
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "handle_request".into(),
                kind: "function".into(),
                detail: None,
                file: "src/server.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![25],
        }]));

        // Outgoing: an absolute stdlib path — should be EXCLUDED with project_only=true
        // but INCLUDED when project_only=false
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "write_all".into(),
                kind: "function".into(),
                detail: None,
                file: "/home/user/.rustup/toolchains/stable/lib/std/io.rs".into(),
                line: 100,
                column: 4,
                data: None,
            },
            call_sites: vec![10],
        }]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            project_only: Some(false), // key: include external
            ..Default::default()
        };
        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        assert_eq!(
            outgoing.len(),
            1,
            "project_only=false should include the stdlib absolute path ref"
        );
        assert!(
            outgoing[0].file.starts_with('/'),
            "outgoing ref should be the absolute stdlib path"
        );
    }

    /// With `project_only = true` (the default), absolute stdlib paths should be
    /// silently dropped from the BFS impact graph.
    #[tokio::test]
    async fn test_find_callers_callees_project_only_true_filters_stdlib_refs() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        // No incoming callers
        lawyer.push_incoming_call_result(Ok(vec![]));

        // Outgoing: an absolute stdlib path — should be filtered when project_only=true
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "write_all".into(),
                kind: "function".into(),
                detail: None,
                file: "/home/user/.rustup/toolchains/stable/lib/std/io.rs".into(),
                line: 100,
                column: 4,
                data: None,
            },
            call_sites: vec![10],
        }]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            // project_only defaults to true via Default::default()
            ..Default::default()
        };
        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        assert_eq!(
            outgoing.len(),
            0,
            "project_only=true (default) must filter out stdlib absolute paths"
        );
    }

    // ── TASK-6: max_references truncation ─────────────────────────────────────

    /// When the number of BFS-found references exceeds `max_references`, the
    /// result must be truncated and `references_truncated = true`.
    #[tokio::test]
    async fn test_find_callers_callees_max_references_truncates_results() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        // Push 5 incoming callers (each on a unique file to avoid dedup)
        let incoming_calls: Vec<CallHierarchyCall> = (1..=5)
            .map(|i| CallHierarchyCall {
                item: CallHierarchyItem {
                    name: format!("caller_{i}"),
                    kind: "function".into(),
                    detail: None,
                    file: format!("src/caller_{i}.rs"),
                    line: i * 10,
                    column: 4,
                    data: None,
                },
                call_sites: vec![i * 10],
            })
            .collect();
        lawyer.push_incoming_call_result(Ok(incoming_calls));

        // Push 3 outgoing callees to also exhaust outgoing budget
        let outgoing_calls: Vec<CallHierarchyCall> = (1..=3)
            .map(|i| CallHierarchyCall {
                item: CallHierarchyItem {
                    name: format!("callee_{i}"),
                    kind: "function".into(),
                    detail: None,
                    file: format!("src/callee_{i}.rs"),
                    line: i * 10,
                    column: 4,
                    data: None,
                },
                call_sites: vec![i * 10],
            })
            .collect();
        lawyer.push_outgoing_call_result(Ok(outgoing_calls));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            max_references: 2, // Budget split: incoming gets 1, outgoing gets 1. Total budget=2.
            ..Default::default()
        };
        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        let incoming = val.incoming.as_ref().expect("incoming must be Some");
        assert_eq!(
            incoming.len(),
            1,
            "incoming refs must be capped at max_references/2=1"
        );
        assert!(
            val.references_truncated,
            "references_truncated must be true when total budget is exhausted"
        );
    }

    /// Verify that the `default_max_references()` constant is 50.
    ///
    /// This ensures the plan's specified default wasn't accidentally changed.
    #[test]
    fn test_find_callers_callees_default_max_references_is_50() {
        use crate::server::types::default_max_references;
        assert_eq!(
            default_max_references(),
            50,
            "default_max_references must be 50 per the remediation plan spec"
        );
    }

    // ── find_callers_callees edge cases ─────────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_handles_empty_incoming_and_outgoing() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        // Empty call hierarchy results
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 3,
            max_references: 50,
            project_only: Some(true),
            include_test_coverage: false,
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.incoming.is_none() || val.incoming.as_ref().unwrap().is_empty());
        assert!(val.outgoing.is_none() || val.outgoing.as_ref().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_find_callers_callees_respects_max_depth() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        // Provide incoming calls at depth 1
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "main".into(),
                kind: "function".into(),
                detail: None,
                file: "src/main.rs".into(),
                line: 5,
                column: 4,
                data: None,
            },
            call_sites: vec![5],
        }]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1, // Limit depth to 1
            max_references: 50,
            project_only: Some(true),
            include_test_coverage: false,
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // Should have incoming call from main
        let incoming = val
            .incoming
            .as_ref()
            .expect("incoming must be Some when not degraded");
        assert!(!incoming.is_empty(), "should have incoming calls");
        assert!(
            incoming.iter().all(|r| r.depth <= 1),
            "all refs should be within max_depth"
        );
    }

    // ── Phase 4C: Navigation Residual Gaps ───────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_bfs_handles_cycle_in_call_graph() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        // Create a cycle: A -> B -> A using existing test files
        let item_a = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item_a.clone()]));

        // A calls validate_token
        let item_b = CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: None,
            file: "src/token.rs".into(),
            line: 20,
            column: 4,
            data: None,
        };
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: item_b.clone(),
            call_sites: vec![15],
        }]));

        // validate_token calls login (cycle back)
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: item_a.clone(),
            call_sites: vec![25],
        }]));

        lawyer.push_incoming_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 3,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // Should not hang or panic
        assert!(!val.degraded);
        let outgoing = val.outgoing.as_ref().expect("must be Some");
        // Should deduplicate: login should not appear in its own outgoing
        assert!(
            !outgoing
                .iter()
                .any(|r| r.file == "src/auth.rs" && r.semantic_path.contains("login")),
            "cycle should be deduplicated"
        );
    }

    #[tokio::test]
    async fn test_find_callers_callees_bfs_deduplicates_cross_referenced_symbols() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));

        // Create duplicate references: same symbol referenced twice
        let caller_item = CallHierarchyItem {
            name: "handler".into(),
            kind: "function".into(),
            detail: None,
            file: "src/handler.rs".into(),
            line: 10,
            column: 4,
            data: None,
        };
        // Push same item twice with different call sites
        lawyer.push_incoming_call_result(Ok(vec![
            CallHierarchyCall {
                item: caller_item.clone(),
                call_sites: vec![20],
            },
            CallHierarchyCall {
                item: caller_item.clone(),
                call_sites: vec![35],
            },
        ]));

        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let incoming = val.incoming.as_ref().expect("must be Some");
        // Should deduplicate based on item (not call sites)
        // Check by semantic path since name is not available in ImpactReference
        let handler_count = incoming
            .iter()
            .filter(|r| r.semantic_path.contains("handler") || r.file == "src/handler.rs")
            .count();
        assert_eq!(
            handler_count, 1,
            "cross-referenced symbol should be deduplicated"
        );
    }

    #[tokio::test]
    async fn test_find_callers_callees_grep_fallback_provides_incoming_heuristic() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        // SPEC 008: search_codebase_impl calls enclosing_symbol_detail for each match
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        // Create files
        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/auth.rs"),
            "fn login() -> bool { true }",
        )
        .unwrap();
        std::fs::write(
            ws_dir.path().join("src/caller.rs"),
            "fn handle_request() { login(); }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![pathfinder_search::SearchMatch {
                file: "src/caller.rs".to_string(),
                line: 1,
                column: 1,
                content: "fn handle_request() { login(); }".to_string(),
                context_before: vec![],
                context_after: vec![],
                enclosing_semantic_path: None,
                is_definition: None,
                version_hash: "sha256:abc".to_string(),
                known: Some(false),
            }],
            total_matches: 1,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        // Use NoOpLawyer to force grep fallback
        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = crate::server::types::FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLspGrepFallback));
        let incoming = val.incoming.as_ref().expect("must be Some from grep");
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].file, "src/caller.rs");
        assert_eq!(incoming[0].direction, "incoming_heuristic");
    }

    #[tokio::test]
    async fn test_find_callers_callees_grep_fallback_no_results_stays_none() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        // SPEC 008: search_codebase_impl calls enclosing_symbol_detail for each match
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        // Create files — login calls validate_token
        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/auth.rs"),
            "fn login() -> bool { validate_token() }",
        )
        .unwrap();
        std::fs::write(
            ws_dir.path().join("src/token.rs"),
            "fn validate_token() -> bool { true }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());
        // Search for "login" finds the definition in auth.rs (which is filtered out)
        // and no other references, so grep fallback returns None for incoming.
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![],
            total_matches: 0,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        // Use NoOpLawyer to force grep fallback
        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = crate::server::types::FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        // When grep fallback returns no results, degraded_reason stays at default NoLsp
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLsp));
        // make_scope() returns "fn login() { }" with empty body — no function calls
        // to extract. Grep outgoing fallback exists but finds zero candidates.
        assert!(
            val.outgoing.is_none(),
            "outgoing should be None — empty function body has no call candidates"
        );
        // No search results means no incoming either
        assert!(
            val.incoming.is_none(),
            "incoming should be None when search returns no matches"
        );
    }

    // ── GAP 3: method call extraction for Rust/Go/Java ──────────────────────

    #[tokio::test]
    async fn test_extract_call_candidates_captures_method_calls() {
        // Verify that call_pattern_full() now used for ALL languages captures
        // method calls like self.validate(), s.HandleRequest(), service.process().
        use super::super::extract_call_candidates;

        // Rust method call
        let rust_code = "fn login(&self) { self.validate_token(); self.hash_password(); }";
        let rust_candidates = extract_call_candidates(rust_code, "rust");
        assert!(
            rust_candidates.contains(&"validate_token".to_string()),
            "should capture self.validate_token() in Rust"
        );
        assert!(
            rust_candidates.contains(&"hash_password".to_string()),
            "should capture self.hash_password() in Rust"
        );

        // Go method call
        let go_code = "func (h *Handler) Login() { h.service.Validate(); }";
        let go_candidates = extract_call_candidates(go_code, "go");
        assert!(
            go_candidates.contains(&"Validate".to_string()),
            "should capture h.service.Validate() in Go"
        );

        // Java method call
        let java_code = "public void login() { this.service.process(); }";
        let java_candidates = extract_call_candidates(java_code, "java");
        assert!(
            java_candidates.contains(&"process".to_string()),
            "should capture this.service.process() in Java"
        );
    }

    // ── GAP 6: per-language method call extraction tests ──────────────────────

    #[tokio::test]
    async fn test_extract_call_candidates_rust_method_calls() {
        use super::super::extract_call_candidates;

        let code = "fn login(&self) { self.validate(); self.hash_password(); self.save(); }";
        let candidates = extract_call_candidates(code, "rust");
        assert!(
            candidates.contains(&"validate".to_string()),
            "should capture self.validate() in Rust"
        );
        assert!(
            candidates.contains(&"hash_password".to_string()),
            "should capture self.hash_password() in Rust"
        );
        assert!(
            candidates.contains(&"save".to_string()),
            "should capture self.save() in Rust"
        );
    }

    #[tokio::test]
    async fn test_extract_call_candidates_go_method_calls() {
        use super::super::extract_call_candidates;

        let code = "func (s *Server) Handle() { s.Validate(); s.Process(); }";
        let candidates = extract_call_candidates(code, "go");
        assert!(
            candidates.contains(&"Validate".to_string()),
            "should capture s.Validate() in Go"
        );
        assert!(
            candidates.contains(&"Process".to_string()),
            "should capture s.Process() in Go"
        );
    }

    #[tokio::test]
    async fn test_extract_call_candidates_java_method_calls() {
        use super::super::extract_call_candidates;

        let code = "public void login() { this.service.process(); this.dao.save(); }";
        let candidates = extract_call_candidates(code, "java");
        assert!(
            candidates.contains(&"process".to_string()),
            "should capture this.service.process() in Java"
        );
        assert!(
            candidates.contains(&"save".to_string()),
            "should capture this.dao.save() in Java"
        );
    }

    // ── GAP 7: outgoing fallback end-to-end tests ──────────────────────────
    //
    // Strategy for handling non-deterministic HashSet iteration:
    // extract_call_candidates extracts both the fn name from the signature and
    // body calls. With set_results, we queue enough results so that regardless
    // of candidate ordering, the correct matches are returned.
    //
    // For the happy-path test with scope "fn handle(&self) { self.validate(); }":
    //   Candidates: {"handle", "validate"} (HashSet, order varies)
    //   We queue results where EVERY search returns the "validate" match from
    //   token.rs. The "handle" candidate search gets a match in token.rs which
    //   won't form a valid fn definition but still gets added as outgoing_heuristic.
    //   We verify outgoing is Some with at least one entry having the right direction.

    #[tokio::test]
    async fn test_outgoing_fallback_happy_path() {
        // When LSP is unavailable and the function body has calls,
        // outgoing should be Some with direction "outgoing_heuristic".
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon.read_symbol_scope_results.lock().unwrap().push(Ok(
            pathfinder_common::types::SymbolScope {
                content: "fn handle(&self) { self.validate(); }".to_string(),
                start_line: 9,
                end_line: 9,
                name_column: 0,
                language: "rust".to_string(),
            },
        ));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/handler.rs"),
            "fn handle(&self) { self.validate(); }",
        )
        .unwrap();
        std::fs::write(
            ws_dir.path().join("src/validator.rs"),
            "fn validate() -> bool { true }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());

        let validate_match = pathfinder_search::SearchMatch {
            file: "src/validator.rs".to_string(),
            line: 1,
            column: 0,
            content: "fn validate() -> bool { true }".to_string(),
            context_before: vec![],
            context_after: vec![],
            enclosing_semantic_path: None,
            is_definition: None,
            version_hash: "sha256:abc".to_string(),
            known: Some(false),
        };
        let empty_result = Ok(pathfinder_search::SearchResult {
            matches: vec![],
            total_matches: 0,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });
        let validate_result = Ok(pathfinder_search::SearchResult {
            matches: vec![validate_match],
            total_matches: 1,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });

        // Queue: 1st = incoming search (empty), then enough for outgoing candidates
        // Candidates from HashSet: "handle" + "validate" in unknown order.
        // Both get validate_result so we don't depend on order.
        scout.set_results(vec![
            empty_result.clone(),    // incoming search
            validate_result.clone(), // 1st outgoing candidate (handle or validate)
            validate_result.clone(), // 2nd outgoing candidate (the other)
        ]);

        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = crate::server::types::FindCallersCalleesParams {
            semantic_path: "src/handler.rs::handle".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        assert_eq!(val.degraded_reason, Some(DegradedReason::NoLspGrepFallback));
        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        assert!(
            !outgoing.is_empty(),
            "should have at least one outgoing ref"
        );
        assert_eq!(
            outgoing[0].direction, "outgoing_heuristic",
            "direction must be outgoing_heuristic"
        );
    }

    #[tokio::test]
    async fn test_outgoing_fallback_dedup_by_semantic_path() {
        // Same function called multiple times should appear once in outgoing.
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon.read_symbol_scope_results.lock().unwrap().push(Ok(
            pathfinder_common::types::SymbolScope {
                content: "fn process(&self) { self.run(); self.run(); self.run(); }".to_string(),
                start_line: 5,
                end_line: 5,
                name_column: 0,
                language: "rust".to_string(),
            },
        ));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/worker.rs"),
            "fn process(&self) { self.run(); }",
        )
        .unwrap();
        std::fs::write(ws_dir.path().join("src/runner.rs"), "fn run() { }").unwrap();

        let scout = Arc::new(MockScout::default());

        let run_match = pathfinder_search::SearchMatch {
            file: "src/runner.rs".to_string(),
            line: 1,
            column: 0,
            content: "fn run() { }".to_string(),
            context_before: vec![],
            context_after: vec![],
            enclosing_semantic_path: None,
            is_definition: None,
            version_hash: "sha256:abc".to_string(),
            known: Some(false),
        };
        let empty_result = Ok(pathfinder_search::SearchResult {
            matches: vec![],
            total_matches: 0,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });
        let run_result = Ok(pathfinder_search::SearchResult {
            matches: vec![run_match],
            total_matches: 1,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });

        // Candidates: "process" + "run" (deduped by HashSet in extract_call_candidates)
        // But grep_outgoing_fallback also deduplicates by semantic_path.
        // Both candidates get run_result, but only the "run" match adds
        // "src/runner.rs::run" (the "process" candidate search also gets run_result
        // but forms "src/runner.rs::process" which is a different semantic_path).
        // The seen set ensures no dupes regardless.
        scout.set_results(vec![
            empty_result.clone(), // incoming
            run_result.clone(),   // 1st outgoing candidate
            run_result.clone(),   // 2nd outgoing candidate
        ]);

        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = crate::server::types::FindCallersCalleesParams {
            semantic_path: "src/worker.rs::process".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        // All outgoing refs should have unique semantic_paths
        let paths: std::collections::HashSet<&str> =
            outgoing.iter().map(|r| r.semantic_path.as_str()).collect();
        assert_eq!(
            paths.len(),
            outgoing.len(),
            "all outgoing refs must have unique semantic_paths"
        );
    }

    #[tokio::test]
    async fn test_outgoing_fallback_definition_file_exclusion() {
        // When a candidate resolves to the definition file, it should be excluded.
        // Test uses scope with only one candidate (validate) and sets up search
        // to return a match in the definition file, which gets skipped.
        // With GAP 5 fix, the 2nd match (in another file) should be used instead.
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon.read_symbol_scope_results.lock().unwrap().push(Ok(
            pathfinder_common::types::SymbolScope {
                content: "fn do_work() { validate(); }".to_string(),
                start_line: 10,
                end_line: 10,
                name_column: 0,
                language: "rust".to_string(),
            },
        ));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/worker.rs"),
            "fn do_work() { validate(); }\nfn validate() { }",
        )
        .unwrap();
        std::fs::write(ws_dir.path().join("src/lib.rs"), "fn validate() { }").unwrap();

        let scout = Arc::new(MockScout::default());

        // GAP 5 scenario: first match is in definition file (skipped),
        // second match is in another file (should be used).
        let local_match = pathfinder_search::SearchMatch {
            file: "src/worker.rs".to_string(),
            line: 2,
            column: 0,
            content: "fn validate() { }".to_string(),
            context_before: vec![],
            context_after: vec![],
            enclosing_semantic_path: None,
            is_definition: None,
            version_hash: "sha256:abc".to_string(),
            known: Some(false),
        };
        let external_match = pathfinder_search::SearchMatch {
            file: "src/lib.rs".to_string(),
            line: 1,
            column: 0,
            content: "fn validate() { }".to_string(),
            context_before: vec![],
            context_after: vec![],
            enclosing_semantic_path: None,
            is_definition: None,
            version_hash: "sha256:def".to_string(),
            known: Some(false),
        };
        let empty_result = Ok(pathfinder_search::SearchResult {
            matches: vec![],
            total_matches: 0,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });
        // Candidates: {"do_work", "validate"} — order unknown
        // For "do_work": search gets the two-match result (neither is a valid fn do_work)
        // For "validate": search gets the two-match result (first=definition, second=external)
        // With GAP 5 fix, the second match (src/lib.rs) is used.
        let two_match_result = Ok(pathfinder_search::SearchResult {
            matches: vec![local_match, external_match],
            total_matches: 2,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        });

        scout.set_results(vec![
            empty_result,             // incoming
            two_match_result.clone(), // 1st outgoing candidate
            two_match_result,         // 2nd outgoing candidate
        ]);

        let server = PathfinderServer::with_all_engines(
            ws,
            config,
            sandbox,
            scout,
            surgeon,
            Arc::new(pathfinder_lsp::NoOpLawyer),
        );

        let params = crate::server::types::FindCallersCalleesParams {
            semantic_path: "src/worker.rs::do_work".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        // No outgoing ref should be in the definition file (src/worker.rs)
        for reference in outgoing {
            assert_ne!(
                reference.file, "src/worker.rs",
                "outgoing refs should exclude the definition file"
            );
        }
        // Should have at least one outgoing ref (src/lib.rs::validate)
        assert!(
            outgoing.iter().any(|r| r.file == "src/lib.rs"),
            "should have resolved validate to src/lib.rs"
        );
    }

    // ── BFS multi-node continuation after error ──────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_bfs_continues_after_single_node_error() {
        // When queue has items A, B and querying A fails, B should still be processed.
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

        // Incoming: first call fails (error for initial item), second succeeds
        lawyer.push_incoming_call_result(Err(LspError::Protocol("transient error".to_string())));
        // Outgoing succeeds with one callee
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "validate_token".into(),
                kind: "function".into(),
                detail: Some("fn validate_token()".into()),
                file: "src/token.rs".into(),
                line: 15,
                column: 4,
                data: None,
            },
            call_sites: vec![9],
        }]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            max_references: 50,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed despite BFS error");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // Not degraded — the LSP prepare succeeded, BFS errors are partial failures
        assert!(!val.degraded);
        // Incoming errored → empty vec (not None)
        let incoming = val.incoming.as_ref().expect("incoming must be Some");
        assert!(incoming.is_empty(), "incoming should be empty after error");
        // Outgoing succeeded
        let outgoing = val.outgoing.as_ref().expect("outgoing must be Some");
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].file, "src/token.rs");
    }

    // ── BFS text output format ──────────────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_bfs_formats_response_correctly() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "handle_request".into(),
                kind: "function".into(),
                detail: Some("fn handle_request()".into()),
                file: "src/server.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![25],
        }]));

        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 1,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");

        // Verify text output format
        let text = match &call_res.content[0].raw {
            rmcp::model::RawContent::Text(t) => t.text.clone(),
            _ => panic!("expected text content"),
        };
        assert!(text.contains("Incoming references: 1"), "text: {text}");
        assert!(text.contains("Outgoing references: 0"), "text: {text}");
        assert!(text.contains("[depth="), "text: {text}");
        assert!(text.contains("src/server.rs:L20"), "text: {text}");
        assert!(text.contains("[completed in"), "text: {text}");
    }

    // ── include_test_coverage=true path ──────────────────────────────

    #[tokio::test]
    async fn test_find_callers_callees_with_test_coverage() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        lawyer.push_incoming_call_result(Ok(vec![]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        // Configure scout to return test file matches
        let scout = Arc::new(MockScout::default());
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![pathfinder_search::SearchMatch {
                file: "src/auth_test.rs".to_string(),
                line: 10,
                column: 4,
                content: "fn test_login() { login(); }".to_string(),
                context_before: vec![],
                context_after: vec![],
                enclosing_semantic_path: Some("src/auth_test.rs::test_login".to_string()),
                is_definition: Some(true),
                version_hash: "sha256:abc".to_string(),
                known: Some(false),
            }],
            total_matches: 1,
            truncated: false,
            files_searched: 1,
            files_in_scope: 1,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);
        let server =
            PathfinderServer::with_all_engines(ws, config, sandbox, scout, surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            include_test_coverage: true,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        // Verify test coverage results
        assert!(
            val.test_callers.is_some(),
            "test_callers should be populated"
        );
        let test_refs = val.test_callers.as_ref().unwrap();
        assert_eq!(test_refs.len(), 1);
        assert_eq!(test_refs[0].file, "src/auth_test.rs");
        assert_eq!(test_refs[0].direction, "test_coverage");
        assert_eq!(val.test_coverage_status, Some("found".to_owned()));
    }

    #[tokio::test]
    async fn test_find_callers_callees_test_coverage_not_found() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        lawyer.push_incoming_call_result(Ok(vec![]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        // Scout returns empty — no test files found
        let scout = Arc::new(MockScout::default());
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![],
            total_matches: 0,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);
        let server =
            PathfinderServer::with_all_engines(ws, config, sandbox, scout, surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            include_test_coverage: true,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(
            val.test_callers.is_none(),
            "test_callers should be None when not found"
        );
        assert_eq!(val.test_coverage_status, Some("not_found".to_owned()));
    }

    #[tokio::test]
    async fn test_find_callers_callees_bfs_aborts_on_consecutive_failures() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

        let caller_item = CallHierarchyItem {
            name: "caller".into(),
            kind: "function".into(),
            detail: None,
            file: "src/caller.rs".into(),
            line: 5,
            column: 4,
            data: None,
        };

        // Incoming: first call returns a caller (so BFS has something to traverse),
        // then every subsequent call for deeper levels fails.
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: caller_item.clone(),
            call_sites: vec![9],
        }]));
        // Next BFS step: incoming for caller fails
        lawyer.push_incoming_call_result(Err(LspError::Protocol("hung".to_string())));
        // Next BFS step: incoming fails again → 2 consecutive failures → abort
        lawyer.push_incoming_call_result(Err(LspError::Protocol("still hung".to_string())));

        // Outgoing: empty
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 4,
            max_references: 50,
            ..Default::default()
        };
        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed with partial results");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let incoming = val.incoming.as_ref().expect("must be Some");
        assert_eq!(incoming.len(), 1, "should have 1 caller before abort");
        assert_eq!(incoming[0].semantic_path, "src/caller.rs::caller");
    }

    #[tokio::test]
    async fn test_find_callers_callees_bfs_cycle_detection_incoming() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item_a = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item_a.clone()]));

        let item_b = CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: None,
            file: "src/token.rs".into(),
            line: 20,
            column: 4,
            data: None,
        };
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: item_b.clone(),
            call_sites: vec![15],
        }]));

        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: item_a.clone(),
            call_sites: vec![25],
        }]));

        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 3,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let incoming = val.incoming.as_ref().expect("must be Some");
        assert!(
            !incoming
                .iter()
                .any(|r| r.file == "src/auth.rs" && r.semantic_path.contains("login")),
            "cycle should be deduplicated"
        );
    }

    #[tokio::test]
    async fn test_find_callers_callees_empty_callee_intermediate() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item_a = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item_a.clone()]));

        let item_b = CallHierarchyItem {
            name: "validate_token".into(),
            kind: "function".into(),
            detail: None,
            file: "src/token.rs".into(),
            line: 20,
            column: 4,
            data: None,
        };
        lawyer.push_outgoing_call_result(Ok(vec![CallHierarchyCall {
            item: item_b.clone(),
            call_sites: vec![15],
        }]));

        lawyer.push_outgoing_call_result(Ok(vec![]));
        lawyer.push_incoming_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 3,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let outgoing = val.outgoing.as_ref().expect("must be Some");
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].file, "src/token.rs");
    }

    #[tokio::test]
    async fn test_find_callers_callees_bfs_partial_resolution_failure() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item_a = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item_a.clone()]));

        let item_b = CallHierarchyItem {
            name: "caller_b".into(),
            kind: "function".into(),
            detail: None,
            file: "src/caller_b.rs".into(),
            line: 10,
            column: 4,
            data: None,
        };
        let item_c = CallHierarchyItem {
            name: "caller_c".into(),
            kind: "function".into(),
            detail: None,
            file: "src/caller_c.rs".into(),
            line: 10,
            column: 4,
            data: None,
        };

        lawyer.push_incoming_call_result(Ok(vec![
            CallHierarchyCall {
                item: item_b.clone(),
                call_sites: vec![5],
            },
            CallHierarchyCall {
                item: item_c.clone(),
                call_sites: vec![6],
            },
        ]));

        lawyer.push_incoming_call_result(Ok(vec![]));
        lawyer.push_incoming_call_result(Err(LspError::Protocol("failed".to_string())));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 3,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(!val.degraded);
        let incoming = val.incoming.as_ref().expect("must be Some");
        assert_eq!(incoming.len(), 2);
    }

    #[tokio::test]
    async fn test_find_callers_callees_lsp_error_triggers_grep_fallback() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let ws_dir = make_temp_workspace();
        let ws = WorkspaceRoot::new(ws_dir.path()).expect("valid root");
        let config = PathfinderConfig::default();
        let sandbox = Sandbox::new(ws.path(), &config.sandbox);

        std::fs::create_dir_all(ws_dir.path().join("src")).unwrap();
        std::fs::write(
            ws_dir.path().join("src/auth.rs"),
            "fn login() -> bool { true }",
        )
        .unwrap();
        std::fs::write(
            ws_dir.path().join("src/caller.rs"),
            "fn handle_request() { login(); }",
        )
        .unwrap();

        let scout = Arc::new(MockScout::default());
        scout.set_result(Ok(pathfinder_search::SearchResult {
            matches: vec![pathfinder_search::SearchMatch {
                file: "src/caller.rs".to_string(),
                line: 1,
                column: 1,
                content: "fn handle_request() { login(); }".to_string(),
                context_before: vec![],
                context_after: vec![],
                enclosing_semantic_path: None,
                is_definition: None,
                version_hash: "sha256:abc".to_string(),
                known: Some(false),
            }],
            total_matches: 1,
            truncated: false,
            files_searched: 0,
            files_in_scope: 0,
            binary_skipped: 0,
            gitignored_skipped: 0,
            other_skipped: 0,
        }));

        let lawyer = Arc::new(MockLawyer::default());
        lawyer.push_prepare_call_hierarchy_result(Err(LspError::Protocol("LSP error".to_string())));

        let server =
            PathfinderServer::with_all_engines(ws, config, sandbox, scout, surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 2,
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let call_res = result.expect("should succeed despite LSP error");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(call_res.structured_content.unwrap()).unwrap();

        assert!(val.degraded);
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspErrorGrepFallback)
        );
        let incoming = val.incoming.as_ref().expect("must be Some from grep");
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].file, "src/caller.rs");
    }

    #[tokio::test]
    async fn test_find_callers_callees_invalid_semantic_path() {
        let surgeon = Arc::new(MockSurgeon::new());
        let lawyer = Arc::new(MockLawyer::default());
        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "invalid_path_format".to_owned(),
            ..Default::default()
        };

        let result = server.find_callers_callees_impl(params).await;
        let Err(err) = result else {
            panic!("expected error");
        };
        let code = err
            .data
            .as_ref()
            .and_then(|d| d.get("error"))
            .and_then(|v| v.as_str())
            .unwrap_or("");
        assert_eq!(code, "INVALID_SEMANTIC_PATH");
    }

    #[tokio::test]
    async fn test_find_callers_callees_max_depth_boundaries() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());

        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item.clone()]));
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "caller".into(),
                kind: "function".into(),
                detail: Some("fn caller()".into()),
                file: "src/caller.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![25],
        }]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon.clone(), lawyer.clone());

        let zero_depth_params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 0,
            ..Default::default()
        };
        let zero_depth_res = server
            .find_callers_callees_impl(zero_depth_params)
            .await
            .expect("success");
        let zero_depth_val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(zero_depth_res.structured_content.unwrap()).unwrap();
        assert!(!zero_depth_val.degraded);

        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        lawyer.push_incoming_call_result(Ok(vec![CallHierarchyCall {
            item: CallHierarchyItem {
                name: "caller".into(),
                kind: "function".into(),
                detail: Some("fn caller()".into()),
                file: "src/caller.rs".into(),
                line: 20,
                column: 4,
                data: None,
            },
            call_sites: vec![25],
        }]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let large_depth_params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_depth: 10,
            ..Default::default()
        };
        let large_depth_res = server
            .find_callers_callees_impl(large_depth_params)
            .await
            .expect("success");
        let large_depth_val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(large_depth_res.structured_content.unwrap()).unwrap();
        assert!(!large_depth_val.degraded);
    }

    #[tokio::test]
    async fn test_find_callers_callees_empty_results_text_formatting() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        lawyer.set_goto_definition_result(Ok(Some(DefinitionLocation {
            file: "src/auth.rs".into(),
            line: 10,
            column: 4,
            preview: "fn login() {}".into(),
        })));
        lawyer.push_incoming_call_result(Ok(vec![]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            ..Default::default()
        };

        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("success");
        let text = result.content[0].as_text().expect("must be text");
        assert!(
            text.text.contains("DEGRADED (lsp_warmup_grep_fallback)"),
            "Text output did not format zero results correctly: {}",
            text.text
        );
    }

    #[tokio::test]
    async fn test_find_callers_callees_references_truncated() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));

        lawyer.push_incoming_call_result(Ok(vec![
            CallHierarchyCall {
                item: CallHierarchyItem {
                    name: "caller_1".into(),
                    kind: "function".into(),
                    detail: None,
                    file: "src/caller_1.rs".into(),
                    line: 10,
                    column: 4,
                    data: None,
                },
                call_sites: vec![10],
            },
            CallHierarchyCall {
                item: CallHierarchyItem {
                    name: "caller_2".into(),
                    kind: "function".into(),
                    detail: None,
                    file: "src/caller_2.rs".into(),
                    line: 20,
                    column: 4,
                    data: None,
                },
                call_sites: vec![20],
            },
        ]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            max_references: 1,
            ..Default::default()
        };

        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("success");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        assert!(val.references_truncated);
    }

    #[tokio::test]
    async fn test_find_callers_callees_unusual_symbol_types() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));

        let lawyer = Arc::new(MockLawyer::default());
        let item = CallHierarchyItem {
            name: "login".into(),
            kind: "function".into(),
            detail: None,
            file: "src/auth.rs".into(),
            line: 9,
            column: 4,
            data: None,
        };
        lawyer.push_prepare_call_hierarchy_result(Ok(vec![item]));
        lawyer.push_incoming_call_result(Ok(vec![]));
        lawyer.push_outgoing_call_result(Ok(vec![]));

        let (server, _ws) = make_server_with_lawyer(surgeon.clone(), lawyer);

        let params_macro = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::my_macro!".to_owned(),
            ..Default::default()
        };
        let result_macro = server.find_callers_callees_impl(params_macro).await;
        assert!(result_macro.is_ok(), "Macro symbol type should succeed");

        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        let params_trait = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::<impl User>::login".to_owned(),
            ..Default::default()
        };
        let result_trait = server.find_callers_callees_impl(params_trait).await;
        assert!(
            result_trait.is_ok(),
            "Trait impl symbol type should succeed"
        );
    }

    // ── Regression: degraded_reason must reflect actual failure cause ────────

    /// Regression: LSP timeout with empty grep results must report `LspTimeoutGrepFallback`,
    /// NOT `NoLsp`. Previously the initial `degraded_reason` = `NoLsp` was never overridden when
    /// grep found nothing, causing agents to think no LSP existed instead of "retry later".
    #[tokio::test]
    async fn test_lsp_timeout_empty_grep_reports_timeout_reason() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        // empty enclosing so grep_outgoing_fallback finds nothing
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let lawyer = Arc::new(MockLawyer::default());
        // Simulate LSP timeout on prepare
        lawyer.push_prepare_call_hierarchy_result(Err(LspError::Timeout {
            operation: "callHierarchy/incomingCalls".to_string(),
            timeout_ms: 5000,
        }));

        // Use make_server_with_lawyer (workspace has no src/ files, so grep finds nothing)
        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            ..Default::default()
        };

        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("should succeed degraded");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        assert!(val.degraded, "must be degraded on timeout");
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspTimeoutGrepFallback),
            "timeout must report LspTimeoutGrepFallback even when grep finds nothing"
        );
    }

    /// Regression: LSP protocol error with empty grep results must report `LspErrorGrepFallback`,
    /// NOT `NoLsp`. Previously `degraded_reason` = `NoLsp` was set and never overridden when grep
    /// found nothing, misleading agents into "LSP not installed" guidance.
    #[tokio::test]
    async fn test_lsp_protocol_error_empty_grep_reports_error_reason() {
        let surgeon = Arc::new(MockSurgeon::new());
        surgeon
            .read_symbol_scope_results
            .lock()
            .unwrap()
            .push(Ok(make_scope()));
        surgeon
            .enclosing_symbol_detail_results
            .lock()
            .unwrap()
            .push(Ok(None));

        let lawyer = Arc::new(MockLawyer::default());
        lawyer.push_prepare_call_hierarchy_result(Err(LspError::Protocol(
            "internal server error".to_string(),
        )));

        let (server, _ws) = make_server_with_lawyer(surgeon, lawyer);

        let params = FindCallersCalleesParams {
            semantic_path: "src/auth.rs::login".to_owned(),
            ..Default::default()
        };

        let result = server
            .find_callers_callees_impl(params)
            .await
            .expect("should succeed degraded");
        let val: crate::server::types::FindCallersCalleesMetadata =
            serde_json::from_value(result.structured_content.unwrap()).unwrap();

        assert!(val.degraded, "must be degraded on LSP error");
        assert_eq!(
            val.degraded_reason,
            Some(DegradedReason::LspErrorGrepFallback),
            "LSP error must report LspErrorGrepFallback even when grep finds nothing"
        );
    }
}