codescout 0.15.0

High-performance coding agent toolkit MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
//! Unit tests for helper functions extracted from `mod.rs`.
//!
//! Moved wholesale during Phase 1b.4; imports made explicit in Phase 1b.5.

use super::display::{
    format_goto_definition, format_hover, format_overview_symbols, format_search_symbols,
};
use super::list_overview::{
    ast_class_names_for_dir, count_files_by_subdir, find_split_point, flat_symbol_count,
    LIST_SYMBOLS_SINGLE_FILE_FLAT_CAP,
};
use super::symbols::{build_by_file, make_search_symbols_hint};
use super::*;
use crate::agent::Agent;
#[cfg(unix)]
use crate::fs::uri_to_path;
use crate::fs::{
    classify_reference_path, format_library_path, resolve_library_roots, tag_external_path,
};
use crate::lsp::SymbolInfo;
use crate::symbol::edit::{
    apply_text_edits, clamp_range_to_parent, editing_end_line, editing_end_line_strict,
    editing_start_line, find_insert_before_line, text_sweep, write_lines,
};
use crate::symbol::query::{
    collect_matching, filter_variable_symbols, find_matching_symbol, find_symbol_by_name_path,
    find_unique_symbol_by_name_path, is_lead_in_line, matches_kind_filter, symbol_name_matches,
    symbol_to_json, validate_symbol_position, validate_symbol_range,
};
use crate::tools::{Tool, ToolContext};
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::tempdir;

fn lsp() -> Arc<dyn crate::lsp::LspProvider> {
    crate::lsp::LspManager::new_arc()
}

fn buf() -> Arc<crate::tools::output_buffer::OutputBuffer> {
    Arc::new(crate::tools::output_buffer::OutputBuffer::new(20))
}

/// Substring predicate for `collect_matching` tests: case-insensitive match on name or name_path.
fn substr_pred(pat: &'static str) -> impl Fn(&SymbolInfo) -> bool {
    move |sym: &SymbolInfo| {
        sym.name.to_lowercase().contains(pat) || sym.name_path.to_lowercase().contains(pat)
    }
}

/// Create a test Cargo project and return the context.
async fn rust_project_ctx() -> Option<(tempfile::TempDir, ToolContext)> {
    if !std::process::Command::new("rust-analyzer")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        return None;
    }

    let dir = tempdir().unwrap();
    std::fs::write(
        dir.path().join("Cargo.toml"),
        r#"[package]
name = "test-project"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    let codescout_dir = dir.path().join(".codescout");
    std::fs::create_dir_all(&codescout_dir).unwrap();
    // Opt out of mux so these unit tests use rust-analyzer directly,
    // without needing the codescout-mux binary on PATH.
    std::fs::write(
        codescout_dir.join("project.toml"),
        "[project]\nname = \"test-project\"\n\n[lsp.rust]\nmux = false\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/main.rs"),
        r#"fn main() {
println!("hello");
}

fn add(a: i32, b: i32) -> i32 {
a + b
}

struct Point {
x: f64,
y: f64,
}

impl Point {
fn new(x: f64, y: f64) -> Self {
    Self { x, y }
}
}
"#,
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    Some((
        dir,
        ToolContext {
            agent,
            lsp: lsp(),
            output_buffer: buf(),
            progress: None,
            peer: None,
            section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
                crate::tools::section_coverage::SectionCoverage::new(),
            )),
            guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
            workspace_override: None,
        },
    ))
}

#[tokio::test]
async fn get_symbols_overview_returns_symbols() {
    let Some((_dir, ctx)) = rust_project_ctx().await else {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    };

    let result = Symbols
        .call(
            json!({
                "path": "src/main.rs",
                "depth": 1
            }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(!symbols.is_empty(), "should find at least one symbol");

    // Should find main, add, Point
    let names: Vec<&str> = symbols
        .iter()
        .map(|s| s["name"].as_str().unwrap())
        .collect();
    assert!(
        names.contains(&"main"),
        "should find main function, got: {:?}",
        names
    );
    assert!(
        names.contains(&"add"),
        "should find add function, got: {:?}",
        names
    );

    ctx.lsp.shutdown_all().await;
}

#[tokio::test]
async fn symbols_project_wide_uses_workspace_symbol() {
    let Some((_dir, ctx)) = rust_project_ctx().await else {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    };

    // Trigger LSP startup and background indexing via a file-restricted call.
    let _ = Symbols
        .call(json!({ "query": "main", "path": "src/main.rs" }), &ctx)
        .await;

    // Retry project-wide search (no relative_path → workspace/symbol fast path)
    // until rust-analyzer finishes background indexing (typically < 3s).
    let mut found = false;
    for _ in 0..10 {
        let result = Symbols
            .call(json!({ "query": "Point" }), &ctx)
            .await
            .unwrap();
        let symbols = result["symbols"].as_array().unwrap();
        if symbols.iter().any(|s| s["name"].as_str() == Some("Point")) {
            found = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    }

    assert!(
        found,
        "should find 'Point' project-wide via workspace/symbol within 5s"
    );

    ctx.lsp.shutdown_all().await;
}

// ── validate_symbol_range tests ──────────────────────────────────────────

/// Degenerate range (start == end) where tree-sitter confirms multi-line →
/// validate_symbol_range must return Err with "suspicious range".
#[test]
fn validate_symbol_range_rejects_degenerate_range() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    // 3-line function (0-indexed lines 0..2)
    std::fs::write(&file, "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n").unwrap();

    let sym = SymbolInfo {
        name: "add".to_string(),
        name_path: "add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0, // degenerate — only the fn-name line
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(result.is_err(), "degenerate range should be rejected");
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("suspicious range"),
        "error should mention suspicious range; got: {msg}"
    );
}

/// Non-degenerate range (start != end) → validate_symbol_range accepts it.
#[test]
fn validate_symbol_range_accepts_good_range() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    std::fs::write(&file, "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n").unwrap();

    // When start != end (LSP returned a real range), accept it.
    let sym = SymbolInfo {
        name: "add".to_string(),
        name_path: "add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 5, // already a real range
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(result.is_ok(), "good range should be accepted");
}

/// Truncated end_line (end inside body, not at closing `}`) must be rejected.
/// This is the BUG-018 pattern: start != end but end < AST end.
#[test]
fn validate_symbol_range_rejects_truncated_end_line() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    // 3-line function (0-indexed lines 0..2)
    std::fs::write(&file, "fn target() {\n    old_body();\n}\n").unwrap();

    let sym = SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 1, // truncated — inside body, misses closing `}` at line 2
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "truncated end_line should be rejected; got Ok"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("suspicious range"),
        "error should mention suspicious range; got: {msg}"
    );
}

// ── validate_symbol_range: multi-language coverage ────────────────────────

#[test]
fn validate_symbol_range_rejects_degenerate_python() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.py");
    std::fs::write(
        &file,
        "def add(a, b):\n    result = a + b\n    return result\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "add".to_string(),
        name_path: "add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0, // degenerate
        start_col: 4,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "Python degenerate range should be rejected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[test]
fn validate_symbol_range_rejects_degenerate_typescript() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.ts");
    std::fs::write(
        &file,
        "function add(a: number, b: number): number {\n    const result = a + b;\n    return result;\n}\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "add".to_string(),
        name_path: "add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0, // degenerate
        start_col: 9,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "TypeScript degenerate range should be rejected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[test]
fn validate_symbol_range_rejects_degenerate_go() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.go");
    std::fs::write(
        &file,
        "package main\n\nfunc Add(a int, b int) int {\n\tresult := a + b\n\treturn result\n}\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "Add".to_string(),
        name_path: "Add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 2, // "func Add..." is line 2 (0-indexed)
        end_line: 2,   // degenerate
        start_col: 5,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(result.is_err(), "Go degenerate range should be rejected");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[test]
fn validate_symbol_range_rejects_degenerate_rust_with_doc() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    // Doc comment on line 0; fn keyword on line 1.
    std::fs::write(
        &file,
        "/// Adds two numbers.\nfn add(a: i32, b: i32) -> i32 {\n    let r = a + b;\n    r\n}\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "add".to_string(),
        name_path: "add".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 1, // fn keyword, not the doc comment
        end_line: 1,   // degenerate
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "Rust+doc comment degenerate range should be rejected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[test]
fn validate_symbol_range_picks_correct_function() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    // `add` at lines 0-2, `multiply` at lines 4-6.
    std::fs::write(
        &file,
        "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n\nfn multiply(a: i32, b: i32) -> i32 {\n    a * b\n}\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "multiply".to_string(),
        name_path: "multiply".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 4,
        end_line: 4, // degenerate
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "degenerate multiply range should be rejected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("multiply"),
        "error should name the symbol; got: {msg}"
    );
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[test]
fn validate_symbol_range_accepts_when_ast_unavailable() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    std::fs::write(&file, "fn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n").unwrap();

    let sym = SymbolInfo {
        name: "nonexistent_fn".to_string(),
        name_path: "nonexistent_fn".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0, // degenerate, but name not in AST
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    // Name not in file — AST can't confirm anything, so we accept the range
    let result = validate_symbol_range(&sym);
    assert!(
        result.is_ok(),
        "unknown name: range should be accepted (no AST confirmation to the contrary)"
    );
}

#[test]
fn validate_symbol_range_recurses_into_children() {
    use crate::lsp::SymbolKind;
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("lib.rs");
    // `distance` is a method inside `impl Point` — it will be a child symbol.
    std::fs::write(
        &file,
        "struct Point { x: f64, y: f64 }\nimpl Point {\n    fn distance(&self) -> f64 {\n        (self.x * self.x + self.y * self.y).sqrt()\n    }\n}\n",
    )
    .unwrap();

    let sym = SymbolInfo {
        name: "distance".to_string(),
        name_path: "Point/distance".to_string(),
        kind: SymbolKind::Method,
        file: file.clone(),
        start_line: 2, // fn distance line (0-indexed)
        end_line: 2,   // degenerate
        start_col: 7,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let result = validate_symbol_range(&sym);
    assert!(
        result.is_err(),
        "method in impl with degenerate range should be rejected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("suspicious range"), "got: {msg}");
}

#[tokio::test]
async fn symbols_by_name() {
    let Some((_dir, ctx)) = rust_project_ctx().await else {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    };

    let result = Symbols
        .call(
            json!({
                "query": "add",
                "path": "src/main.rs"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(!symbols.is_empty(), "should find 'add' symbol");
    assert!(symbols.iter().any(|s| s["name"].as_str() == Some("add")));

    ctx.lsp.shutdown_all().await;
}

#[tokio::test]
async fn get_symbols_overview_accepts_detail_level() {
    let ctx = ToolContext {
        agent: Agent::new(None).await.unwrap(),
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };
    // Should error because no project, but NOT because of unknown param
    let err = Symbols
        .call(json!({ "path": "x", "detail_level": "full" }), &ctx)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("project"),
        "should fail on project, not param: {}",
        err
    );
}

#[tokio::test]
async fn path_not_found_is_recoverable_error() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let err = Symbols
        .call(json!({ "path": "nonexistent/file.py" }), &ctx)
        .await
        .unwrap_err();

    assert!(
        err.downcast_ref::<crate::tools::RecoverableError>()
            .is_some(),
        "path not found must be RecoverableError, got: {}",
        err
    );
}

#[tokio::test]
async fn path_not_found_hint_mentions_list_dir() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let err = Symbols
        .call(json!({ "path": "missing.rs" }), &ctx)
        .await
        .unwrap_err();

    let rec = err
        .downcast_ref::<crate::tools::RecoverableError>()
        .expect("should be RecoverableError");
    assert!(
        rec.hint().unwrap_or("").contains("tree"),
        "hint should mention tree, got: {:?}",
        rec.hint()
    );
}

#[tokio::test]
async fn glob_no_match_is_recoverable_error() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let err = Symbols
        .call(json!({ "path": "src/**/*.nonexistent" }), &ctx)
        .await
        .unwrap_err();

    assert!(
        err.downcast_ref::<crate::tools::RecoverableError>()
            .is_some(),
        "empty glob must be RecoverableError, got: {}",
        err
    );
}

#[tokio::test]
async fn tools_error_without_project() {
    let ctx = ToolContext {
        agent: Agent::new(None).await.unwrap(),
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };
    assert!(Symbols.call(json!({"path": "x"}), &ctx).await.is_err());
    assert!(Symbols.call(json!({"query": "x"}), &ctx).await.is_err());
    assert!(References
        .call(json!({"symbol": "x", "path": "y"}), &ctx)
        .await
        .is_err());
}

#[test]
fn apply_text_edits_simple_replacement() {
    let content = "hello world\nfoo bar\nbaz\n";
    let edits = vec![lsp_types::TextEdit {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 0,
                character: 6,
            },
            end: lsp_types::Position {
                line: 0,
                character: 11,
            },
        },
        new_text: "rust".to_string(),
    }];
    let result = apply_text_edits(content, &edits);
    assert!(result.starts_with("hello rust"), "got: {}", result);
}

#[cfg(unix)]
#[test]
fn uri_to_path_parses_unix_uri() {
    let p = uri_to_path("file:///home/user/code.rs").unwrap();
    assert_eq!(p, PathBuf::from("/home/user/code.rs"));
}

#[tokio::test]
async fn symbols_project_wide_treesitter_fallback() {
    // No rust-analyzer needed — this test verifies the tree-sitter fallback
    // that kicks in when workspace/symbol returns empty.
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn unique_benchmark_fn() -> i32 { 42 }\n\npub struct UniqueTestStruct { x: i32 }\n",
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    // Project-wide search (no relative_path) — LSP will fail/return empty,
    // so tree-sitter fallback should find the symbol.
    let result = Symbols
        .call(json!({ "query": "unique_benchmark_fn" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "should find symbol via tree-sitter fallback: {:?}",
        result
    );
    assert!(symbols
        .iter()
        .any(|s| s["name"].as_str().unwrap() == "unique_benchmark_fn"));

    // Also check struct is findable
    let result2 = Symbols
        .call(json!({ "query": "UniqueTestStruct" }), &ctx)
        .await
        .unwrap();
    let symbols2 = result2["symbols"].as_array().unwrap();
    assert!(
        symbols2
            .iter()
            .any(|s| s["name"].as_str().unwrap() == "UniqueTestStruct"),
        "should find struct via tree-sitter fallback: {:?}",
        result2
    );
}

#[tokio::test]
async fn get_symbols_overview_finds_nested_files() {
    // No LSP needed — verifies recursive walk + tree-sitter fallback.
    // Source files ONLY in subdirectories (not at root).
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn nested_function() -> i32 { 42 }\n",
    )
    .unwrap();
    // Also one at root for comparison
    std::fs::write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    // Project-wide (no path) — should find both root and nested files
    let result = Symbols.call(json!({}), &ctx).await.unwrap();

    let files = result["files"].as_array().unwrap();
    // Normalize separators so the test reads the same on Windows (\) and Unix (/).
    let file_names: Vec<String> = files
        .iter()
        .map(|f| f["file"].as_str().unwrap().replace('\\', "/"))
        .collect();
    assert!(
        files.len() >= 2,
        "should find files in subdirectories, got: {:?}",
        file_names
    );
    assert!(
        file_names.iter().any(|f| f.contains("src/lib.rs")),
        "should find nested src/lib.rs, got: {:?}",
        file_names
    );
    assert!(
        file_names.iter().any(|f| f.contains("main.rs")),
        "should find root main.rs, got: {:?}",
        file_names
    );
}

#[tokio::test]
async fn symbols_overview_small_tree_recurses_fully() {
    // When targeting a specific subdirectory with a small file count (≤ RECURSE_SMALL),
    // the new three-mode dispatch recurses fully to give complete symbol output.
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("src/deep/nested")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(dir.path().join("src/top.rs"), "pub fn top_level() {}\n").unwrap();
    std::fs::write(
        dir.path().join("src/deep/nested/hidden.rs"),
        "pub fn deeply_nested() {}\n",
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    // Target "src" specifically — small tree (2 files) → full recursive symbol mode
    let result = Symbols.call(json!({ "path": "src" }), &ctx).await.unwrap();

    let files = result["files"].as_array().unwrap();
    let file_names: Vec<&str> = files.iter().map(|f| f["file"].as_str().unwrap()).collect();
    assert!(
        file_names.iter().any(|f| f.contains("top.rs")),
        "should find src/top.rs, got: {:?}",
        file_names
    );
    // Small tree (≤ RECURSE_SMALL) → full recursive walk includes deeply nested files
    assert!(
        file_names.iter().any(|f| f.contains("hidden.rs")),
        "small tree should recurse fully and find nested file, got: {:?}",
        file_names
    );
}

#[test]
fn symbols_in_tree() {
    let symbols = vec![SymbolInfo {
        name: "Foo".into(),
        name_path: "Foo".into(),
        kind: crate::lsp::SymbolKind::Struct,
        file: PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![SymbolInfo {
            name: "bar".into(),
            name_path: "Foo/bar".into(),
            kind: crate::lsp::SymbolKind::Method,
            file: PathBuf::from("test.rs"),
            start_line: 2,
            end_line: 4,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        }],
        range_start_line: None,
        detail: None,
    }];

    assert!(find_symbol_by_name_path(&symbols, "Foo").is_some());
    assert!(find_symbol_by_name_path(&symbols, "Foo/bar").is_some());
    assert!(find_symbol_by_name_path(&symbols, "nonexistent").is_none());
}

#[test]
fn find_symbol_by_name_path_exact_match() {
    let test_file = std::env::temp_dir().join("test.rs");
    let symbols = vec![SymbolInfo {
        name: "MyStruct".to_string(),
        name_path: "MyStruct".to_string(),
        kind: crate::lsp::SymbolKind::Struct,
        file: test_file.clone(),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![SymbolInfo {
            name: "my_method".to_string(),
            name_path: "MyStruct/my_method".to_string(),
            kind: crate::lsp::SymbolKind::Method,
            file: test_file,
            start_line: 2,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        }],
        range_start_line: None,
        detail: None,
    }];

    // Exact name_path match for nested symbol
    let found = find_symbol_by_name_path(&symbols, "MyStruct/my_method");
    assert!(found.is_some());
    assert_eq!(found.unwrap().name, "my_method");

    // Exact name_path match for top-level
    let found = find_symbol_by_name_path(&symbols, "MyStruct");
    assert!(found.is_some());
    assert_eq!(found.unwrap().name, "MyStruct");

    // Bare name match (fallback)
    let found = find_symbol_by_name_path(&symbols, "my_method");
    assert!(found.is_some());
    assert_eq!(found.unwrap().name, "my_method");

    // Miss
    let found = find_symbol_by_name_path(&symbols, "nonexistent");
    assert!(found.is_none());
}

#[test]
fn symbol_name_matches_generic_types() {
    let make_sym = |name: &str, name_path: &str| SymbolInfo {
        name: name.to_string(),
        name_path: name_path.to_string(),
        kind: crate::lsp::SymbolKind::Struct,
        file: std::env::temp_dir().join("test.ts"),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let sym = make_sym("IRepository<T, ID>", "IRepository<T, ID>");
    // Exact match
    assert!(symbol_name_matches(&sym, "IRepository<T, ID>"));
    // Generic prefix match
    assert!(symbol_name_matches(&sym, "IRepository"));
    // Partial prefix must NOT match (would be "IRepo" → 's' next, not '<'/'('/' ')
    assert!(!symbol_name_matches(&sym, "IRepo"));

    // Parenthesis suffix (callable generic)
    let sym2 = make_sym("createStore()", "createStore()");
    assert!(symbol_name_matches(&sym2, "createStore"));
    assert!(!symbol_name_matches(&sym2, "create"));

    // Space suffix (e.g. "impl Trait for Struct<T>")
    let sym3 = make_sym("impl Tool for MyStruct<T>", "impl Tool for MyStruct<T>");
    assert!(symbol_name_matches(&sym3, "impl Tool for MyStruct<T>"));

    // Exact name still works with no suffix
    let sym4 = make_sym("PlainStruct", "PlainStruct");
    assert!(symbol_name_matches(&sym4, "PlainStruct"));
    assert!(!symbol_name_matches(&sym4, "Plain"));
}

#[test]
fn symbol_name_matches_suffix_at_word_boundary() {
    let make_sym = |name: &str, name_path: &str| SymbolInfo {
        name: name.to_string(),
        name_path: name_path.to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::env::temp_dir().join("test.rs"),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    // Rust trait impl: space boundary
    let s = make_sym("call", "impl Tool for SemanticSearch/call");
    assert!(symbol_name_matches(&s, "SemanticSearch/call"));
    assert!(symbol_name_matches(&s, "call")); // exact name match still works

    // Rust trait impl with qualified path: colon boundary (from ::)
    let s = make_sym(
        "search_text",
        "impl Searchable for crate::models::book::Book/search_text",
    );
    assert!(symbol_name_matches(&s, "Book/search_text"));

    // Nested name_path: slash boundary
    let s = make_sym("method", "OuterClass/InnerClass/method");
    assert!(symbol_name_matches(&s, "InnerClass/method"));

    // Non-boundary: partial suffix must NOT match (letter before suffix)
    let s = make_sym("call", "FooSemanticSearch/call");
    assert!(!symbol_name_matches(&s, "SemanticSearch/call")); // 'o' is not a boundary

    // Partial suffix not at boundary: "ch/call" must NOT match
    let s = make_sym("call", "impl Tool for SemanticSearch/call");
    assert!(!symbol_name_matches(&s, "ch/call")); // 'r' is not a boundary

    // Rust inherent generic impl: generics break suffix — must NOT match
    let s = make_sym("add", "impl Catalog<T>/add");
    assert!(!symbol_name_matches(&s, "Catalog/add")); // <T> in between, no clean suffix
    assert!(symbol_name_matches(&s, "add")); // bare name still works

    // Java generic class: same — must NOT match partial
    let s = make_sym("add", "Catalog<T extends Searchable>/add");
    assert!(!symbol_name_matches(&s, "Catalog/add"));
    assert!(symbol_name_matches(&s, "add")); // bare name works
}

#[test]
fn symbol_name_matches_kotlin_backtick_normalization() {
    let make_sym = |name: &str, name_path: &str| SymbolInfo {
        name: name.to_string(),
        name_path: name_path.to_string(),
        kind: crate::lsp::SymbolKind::Method,
        file: std::env::temp_dir().join("Test.kt"),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    // LSP strips backticks: stored as "foo bar", queried with "`foo bar`"
    let sym = make_sym(
        "isStage is carried as a constructor value",
        "Stage2LessonTest/isStage is carried as a constructor value",
    );
    assert!(
        symbol_name_matches(&sym, "`isStage is carried as a constructor value`"),
        "bare name with backtick query must match"
    );
    assert!(
        symbol_name_matches(
            &sym,
            "Stage2LessonTest/`isStage is carried as a constructor value`"
        ),
        "name_path with backtick query must match"
    );

    // AST preserves backticks: stored as "`foo bar`", queried without (unusual but safe)
    let sym2 = make_sym("`has spaces and words`", "MyTest/`has spaces and words`");
    assert!(
        symbol_name_matches(&sym2, "has spaces and words"),
        "query without backticks must match backtick-stored name"
    );

    // Exact match (both have backticks) still works
    assert!(
        symbol_name_matches(&sym2, "`has spaces and words`"),
        "exact backtick match must still work"
    );

    // Must NOT match unrelated names just because they share letters
    let sym3 = make_sym("other function", "MyTest/other function");
    assert!(
        !symbol_name_matches(&sym3, "`isStage is carried as a constructor value`"),
        "must not match unrelated name"
    );
}

#[test]
fn find_symbol_by_name_path_generic_types() {
    let test_file = std::env::temp_dir().join("test.ts");
    let symbols = vec![
        SymbolInfo {
            name: "IRepository<T, ID>".to_string(),
            name_path: "IRepository<T, ID>".to_string(),
            kind: crate::lsp::SymbolKind::Interface,
            file: test_file.clone(),
            start_line: 0,
            end_line: 20,
            start_col: 0,
            children: vec![SymbolInfo {
                name: "findById".to_string(),
                name_path: "IRepository<T, ID>/findById".to_string(),
                kind: crate::lsp::SymbolKind::Method,
                file: test_file.clone(),
                start_line: 2,
                end_line: 3,
                start_col: 4,
                children: vec![],
                range_start_line: None,
                detail: None,
            }],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "IRepositoryExtended".to_string(),
            name_path: "IRepositoryExtended".to_string(),
            kind: crate::lsp::SymbolKind::Interface,
            file: test_file,
            start_line: 22,
            end_line: 30,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
    ];

    // Bare query matches the generic type, not the similarly-named one
    let found = find_symbol_by_name_path(&symbols, "IRepository");
    assert!(found.is_some());
    assert_eq!(found.unwrap().name, "IRepository<T, ID>");

    // "IRepositoryExtended" should NOT match query "IRepository" (different suffix char)
    let found_ext = find_symbol_by_name_path(&symbols, "IRepositoryExtended");
    assert!(found_ext.is_some());
    assert_eq!(found_ext.unwrap().name, "IRepositoryExtended");

    // Child method still reachable through generic parent
    let found_method = find_symbol_by_name_path(&symbols, "findById");
    assert!(found_method.is_some());
    assert_eq!(found_method.unwrap().name, "findById");
}

#[test]
fn find_unique_symbol_by_name_path_errors_on_ambiguous_name() {
    let test_file = std::env::temp_dir().join("test.rs");
    let make_method = |parent: &str, name: &str| SymbolInfo {
        name: name.to_string(),
        name_path: format!("{}/{}", parent, name),
        kind: crate::lsp::SymbolKind::Function,
        file: test_file.clone(),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let symbols = vec![
        SymbolInfo {
            name: "ToolA".to_string(),
            name_path: "ToolA".to_string(),
            kind: crate::lsp::SymbolKind::Struct,
            file: test_file.clone(),
            start_line: 0,
            end_line: 20,
            start_col: 0,
            children: vec![make_method("ToolA", "call")],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "ToolB".to_string(),
            name_path: "ToolB".to_string(),
            kind: crate::lsp::SymbolKind::Struct,
            file: test_file.clone(),
            start_line: 25,
            end_line: 45,
            start_col: 0,
            children: vec![make_method("ToolB", "call")],
            range_start_line: None,
            detail: None,
        },
    ];

    // Baseline (the bug): old find_symbol_by_name_path silently returns the first
    // depth-first match for a bare name — caller has no way to know it was ambiguous.
    let old_result = find_symbol_by_name_path(&symbols, "call");
    assert!(
        old_result.is_some(),
        "old function returns Some for ambiguous name — no error, caller is unaware"
    );
    assert_eq!(
        old_result.unwrap().name_path,
        "ToolA/call",
        "old function returns first depth-first match, silently ignoring ToolB/call"
    );

    // Stale → Fixed: find_unique_symbol_by_name_path detects ambiguity and errors,
    // listing all matching name_paths so the caller can supply a more specific query.
    let result = find_unique_symbol_by_name_path(&symbols, "call");
    assert!(result.is_err());
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("ToolA/call"),
        "expected ToolA/call in error, got: {err_str}"
    );
    assert!(
        err_str.contains("ToolB/call"),
        "expected ToolB/call in error, got: {err_str}"
    );

    // Fresh: supplying the full name_path resolves the ambiguity unambiguously
    let result = find_unique_symbol_by_name_path(&symbols, "ToolA/call");
    assert!(result.is_ok());
    assert_eq!(result.unwrap().name_path, "ToolA/call");

    // Not found → RecoverableError mentioning the query
    let result = find_unique_symbol_by_name_path(&symbols, "nonexistent");
    assert!(result.is_err());
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("nonexistent"),
        "expected symbol name in error, got: {err_str}"
    );
}

#[test]
fn find_unique_symbol_by_name_path_suggests_leaf_matches() {
    let test_file = std::env::temp_dir().join("test.rs");
    let make_child = |parent: &str, name: &str| SymbolInfo {
        name: name.to_string(),
        name_path: format!("{}/{}", parent, name),
        kind: crate::lsp::SymbolKind::Function,
        file: test_file.clone(),
        start_line: 1,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let symbols = vec![SymbolInfo {
        name: "impl Catalog<T>".to_string(),
        name_path: "impl Catalog<T>".to_string(),
        kind: crate::lsp::SymbolKind::Object,
        file: test_file.clone(),
        start_line: 0,
        end_line: 20,
        start_col: 0,
        children: vec![make_child("impl Catalog<T>", "add")],
        range_start_line: None,
        detail: None,
    }];

    // "Catalog/add" doesn't suffix-match "impl Catalog<T>/add" (generics break it)
    // but the leaf "add" does match, so the error hint should suggest the real name_path.
    let result = find_unique_symbol_by_name_path(&symbols, "Catalog/add");
    assert!(result.is_err());
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("impl Catalog<T>/add"),
        "hint should suggest the real name_path, got: {err_str}"
    );
    assert!(
        err_str.contains("did you mean"),
        "message should use 'did you mean' phrasing, got: {err_str}"
    );

    // Bare name with no '/' → no leaf search (would be identical), no suggestion
    let result = find_unique_symbol_by_name_path(&symbols, "nonexistent");
    assert!(result.is_err());
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("nonexistent"),
        "bare-name miss should name the query, got: {err_str}"
    );
    assert!(
        !err_str.contains("did you mean"),
        "bare-name miss should not suggest, got: {err_str}"
    );
}

#[test]
fn replace_symbol_with_ambiguous_name_path_returns_error() {
    // When name_path matches 2+ symbols, find_unique_symbol_by_name_path must
    // return a RecoverableError about ambiguity.
    let test_file = std::env::temp_dir().join("ambig_test.rs");
    let make_method = |parent: &str, name: &str| SymbolInfo {
        name: name.to_string(),
        name_path: format!("{}/{}", parent, name),
        kind: crate::lsp::SymbolKind::Function,
        file: test_file.clone(),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let symbols = vec![
        SymbolInfo {
            name: "ToolA".to_string(),
            name_path: "ToolA".to_string(),
            kind: crate::lsp::SymbolKind::Struct,
            file: test_file.clone(),
            start_line: 0,
            end_line: 20,
            start_col: 0,
            children: vec![make_method("ToolA", "call")],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "ToolB".to_string(),
            name_path: "ToolB".to_string(),
            kind: crate::lsp::SymbolKind::Struct,
            file: test_file.clone(),
            start_line: 25,
            end_line: 45,
            start_col: 0,
            children: vec![make_method("ToolB", "call")],
            range_start_line: None,
            detail: None,
        },
    ];

    // Current behavior: find_unique_symbol_by_name_path returns ambiguity error.
    let result = find_unique_symbol_by_name_path(&symbols, "call");
    assert!(result.is_err(), "expected error for ambiguous name_path");
    let err_str = result.unwrap_err().to_string();
    assert!(
        err_str.contains("ambiguous"),
        "expected 'ambiguous' in error, got: {err_str}"
    );
    assert!(
        err_str.contains("ToolA/call"),
        "expected ToolA/call in error, got: {err_str}"
    );
    assert!(
        err_str.contains("ToolB/call"),
        "expected ToolB/call in error, got: {err_str}"
    );
}

#[test]
fn find_unique_resolves_trait_impl_method_by_qualified_name_path() {
    // Two trait-impl methods on the same type share the bare name_path
    // "SensitiveString/fmt" but carry DISTINCT trait-qualified name_paths. The
    // resolver already disambiguates via the qualified form — relocating the
    // impl out of the file was never required to make edit_code target it. This
    // pins both halves: the bare form errors with an actionable hint that points
    // at the qualified form; the qualified form resolves to exactly one symbol.
    let f = std::env::temp_dir().join("sensitive_fmt_test.rs");
    let method = |np: &str, line: u32| SymbolInfo {
        name: "fmt".to_string(),
        name_path: np.to_string(),
        kind: crate::lsp::SymbolKind::Method,
        file: f.clone(),
        start_line: line,
        end_line: line + 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let symbols = vec![
        method("impl fmt::Debug for SensitiveString/fmt", 40),
        method("impl fmt::Display for SensitiveString/fmt", 50),
    ];

    // Bare form is ambiguous — the error must list the qualified alternatives to
    // copy AND hint toward the "impl Trait for Type/method" form (not the bare one).
    let err = find_unique_symbol_by_name_path(&symbols, "SensitiveString/fmt")
        .unwrap_err()
        .to_string();
    assert!(err.contains("ambiguous"), "ambiguity surfaced: {err}");
    assert!(
        err.contains("impl fmt::Display for SensitiveString/fmt"),
        "error lists the qualified paths to copy: {err}"
    );
    assert!(
        err.contains("impl Trait for Type/method"),
        "hint points at the qualified form, not the ambiguous bare form: {err}"
    );

    // Qualified form resolves to exactly the intended sibling — no code move needed.
    let display =
        find_unique_symbol_by_name_path(&symbols, "impl fmt::Display for SensitiveString/fmt")
            .expect("qualified name_path resolves uniquely");
    assert_eq!(
        display.start_line, 50,
        "resolved the Display impl, not Debug"
    );
    let debug =
        find_unique_symbol_by_name_path(&symbols, "impl fmt::Debug for SensitiveString/fmt")
            .expect("qualified name_path resolves uniquely");
    assert_eq!(debug.start_line, 40, "resolved the Debug impl");
}

#[tokio::test]
async fn find_referencing_symbols_returns_references() {
    if !std::process::Command::new("rust-analyzer")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    }

    let dir = tempdir().unwrap();
    std::fs::write(
        dir.path().join("Cargo.toml"),
        r#"[package]
name = "test-refs"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    // Write a file where `add` is defined and called twice
    std::fs::write(
        dir.path().join("src/main.rs"),
        r#"fn add(a: i32, b: i32) -> i32 {
a + b
}

fn main() {
let x = add(1, 2);
let y = add(3, 4);
println!("{} {}", x, y);
}
"#,
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    // rust-analyzer needs time to load the Cargo project and build its index
    // before textDocument/references returns results. Retry with back-off.
    let mut result_value: Option<Value> = None;
    for attempt in 0..10 {
        if attempt > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(500 * attempt)).await;
        }

        let result = References
            .call(
                json!({
                    "symbol": "add",
                    "path": "src/main.rs"
                }),
                &ctx,
            )
            .await;

        // If LSP startup fails (e.g. cargo not in PATH), skip gracefully
        let value = match result {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Skipping: LSP error: {}", e);
                return;
            }
        };

        let total = value["total"].as_u64().unwrap_or(0);
        if total >= 3 {
            result_value = Some(value);
            break;
        }
        eprintln!(
            "Attempt {}: got {} references, retrying...",
            attempt + 1,
            total
        );
    }

    let result = match result_value {
        Some(v) => v,
        None => {
            eprintln!("Skipping: rust-analyzer did not index in time");
            return;
        }
    };

    let file_groups = result["file_groups"].as_array().unwrap();
    let total = result["total"].as_u64().unwrap();

    // Should find at least 3 references: definition + 2 call sites
    assert!(
        total >= 3,
        "Expected >= 3 references (def + 2 calls), got {}. groups: {:?}",
        total,
        file_groups
    );

    // All references should be in src/main.rs — the single group's file should match
    for group in file_groups {
        let file = group["file"].as_str().unwrap();
        assert!(
            file.contains("main.rs"),
            "Reference group in unexpected file: {}",
            file
        );
        // Each item should have context
        for r in group["items"].as_array().unwrap() {
            let ctx_line = r["context"].as_str().unwrap();
            assert!(!ctx_line.is_empty(), "Context line should not be empty");
        }
    }
}

#[tokio::test]
async fn symbols_schema_includes_scope() {
    let tool = Symbols;
    let schema = tool.input_schema();
    assert!(schema["properties"]["scope"].is_object());
}

#[tokio::test]
async fn get_symbols_overview_schema_includes_scope() {
    let tool = Symbols;
    let schema = tool.input_schema();
    assert!(schema["properties"]["scope"].is_object());
}

#[tokio::test]
async fn find_referencing_symbols_schema_includes_scope() {
    let tool = References;
    let schema = tool.input_schema();
    assert!(schema["properties"]["scope"].is_object());
}

#[tokio::test]
async fn tag_external_path_returns_project_for_internal() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let root = agent.require_project_root().await.unwrap();
    let internal = root.join("src/main.rs");
    let tag = tag_external_path(&internal, &root, &agent).await;
    assert_eq!(tag, "project");
}

#[tokio::test]
async fn tag_external_path_discovers_and_registers() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let root = agent.require_project_root().await.unwrap();

    // Create a fake library directory with Cargo.toml
    let lib_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        lib_dir.path().join("Cargo.toml"),
        "[package]\nname = \"fake_lib\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    let lib_src = lib_dir.path().join("src");
    std::fs::create_dir_all(&lib_src).unwrap();
    let lib_file = lib_src.join("lib.rs");
    std::fs::write(&lib_file, "pub fn hello() {}").unwrap();

    let tag = tag_external_path(&lib_file, &root, &agent).await;
    assert_eq!(tag, "lib:fake_lib");

    // Verify it was registered
    let registry = agent.library_registry().await.unwrap();
    assert!(registry.lookup("fake_lib").is_some());
}

#[tokio::test]
async fn symbols_directory_relative_path() {
    let Some((_dir, ctx)) = rust_project_ctx().await else {
        return; // skip if rust-analyzer not available
    };

    // "src" is a directory — should walk it and find symbols inside
    let result = Symbols
        .call(json!({ "query": "add", "path": "src" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with directory relative_path should find symbols"
    );
    assert!(symbols.iter().any(|s| s["name"] == "add"));
}

#[test]
fn collect_matching_matches_name_path() {
    let symbols = vec![SymbolInfo {
        name: "MyStruct".into(),
        name_path: "MyStruct".into(),
        kind: crate::lsp::SymbolKind::Struct,
        file: PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![SymbolInfo {
            name: "my_method".into(),
            name_path: "MyStruct/my_method".into(),
            kind: crate::lsp::SymbolKind::Method,
            file: PathBuf::from("test.rs"),
            start_line: 2,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        }],
        range_start_line: None,
        detail: None,
    }];

    // Pattern with "/" should match via name_path
    let mut results = vec![];
    collect_matching(
        &symbols,
        &substr_pred("mystruct/my_method"),
        false,
        None,
        0,
        true,
        &mut results,
        None,
    );
    assert!(
        !results.is_empty(),
        "pattern with '/' should match against name_path"
    );
    assert_eq!(results[0]["name"], "my_method");

    // Pattern without "/" should still match via name as before
    let mut results2 = vec![];
    collect_matching(
        &symbols,
        &substr_pred("my_method"),
        false,
        None,
        0,
        true,
        &mut results2,
        None,
    );
    assert!(
        !results2.is_empty(),
        "pattern without '/' should still match via name"
    );
}

async fn rich_project_ctx() -> (tempfile::TempDir, ToolContext) {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("src/utils")).unwrap();
    std::fs::create_dir_all(dir.path().join("src/empty")).unwrap();
    let codescout_dir = dir.path().join(".codescout");
    std::fs::create_dir_all(&codescout_dir).unwrap();
    // Opt out of mux so these unit tests use rust-analyzer directly,
    // without needing the codescout-mux binary on PATH.
    std::fs::write(
        codescout_dir.join("project.toml"),
        "[project]\nname = \"test-project\"\n\n[lsp.rust]\nmux = false\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"test-project\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/main.rs"),
        "fn main() {}\n\nfn add(a: i32, b: i32) -> i32 {\n    a + b\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn helper() -> bool { true }\n\npub struct Calculator;\n\nimpl Calculator {\n    pub fn compute() -> i32 { 42 }\n}\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/utils/math.rs"),
        "pub fn multiply(a: i32, b: i32) -> i32 { a * b }\n",
    )
    .unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    (
        dir,
        ToolContext {
            agent,
            lsp: lsp(),
            output_buffer: buf(),
            progress: None,
            peer: None,
            section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
                crate::tools::section_coverage::SectionCoverage::new(),
            )),
            guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
            workspace_override: None,
        },
    )
}

#[tokio::test]
async fn symbols_path_type_file() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(json!({ "query": "add", "path": "src/main.rs" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with file relative_path should find symbols"
    );
    assert!(symbols.iter().any(|s| s["name"] == "add"));
}

#[tokio::test]
async fn symbols_path_type_directory() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(json!({ "query": "helper", "path": "src" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with directory relative_path should find symbols: {:?}",
        result
    );
    assert!(symbols.iter().any(|s| s["name"] == "helper"));
}

#[tokio::test]
async fn symbols_path_type_nested_directory() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(json!({ "query": "multiply", "path": "src/utils" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with nested directory relative_path should find symbols: {:?}",
        result
    );
    assert!(symbols.iter().any(|s| s["name"] == "multiply"));
}

#[tokio::test]
async fn symbols_path_type_glob() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(json!({ "query": "add", "path": "src/**/*.rs" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with glob relative_path should find symbols: {:?}",
        result
    );
}

#[tokio::test]
async fn symbols_empty_directory_returns_empty() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(json!({ "query": "anything", "path": "src/empty" }), &ctx)
        .await
        .unwrap();

    let total = result["total"].as_u64().unwrap();
    assert_eq!(total, 0, "empty directory should return 0 results");
}

#[tokio::test]
async fn symbols_name_path_pattern_in_directory() {
    let (_dir, ctx) = rich_project_ctx().await;

    let result = Symbols
        .call(
            json!({ "query": "impl Calculator/compute", "path": "src" }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with name_path pattern in directory should find symbols: {:?}",
        result
    );
    assert!(symbols.iter().any(|s| s["name"] == "compute"));
}

#[tokio::test]
async fn symbols_name_path_pattern_project_wide() {
    let (_dir, ctx) = rich_project_ctx().await;

    // tree-sitter merges impl methods under the type name directly
    // (no "impl" prefix), so name_path is "Calculator/compute"
    let result = Symbols
        .call(json!({ "query": "Calculator/compute" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(
        !symbols.is_empty(),
        "symbols with name_path pattern project-wide should find symbols via tree-sitter: {:?}",
        result
    );
    assert!(symbols.iter().any(|s| s["name"] == "compute"));
}

#[test]
fn collect_matching_slash_pattern_precision() {
    let symbols = vec![SymbolInfo {
        name: "MyStruct".into(),
        name_path: "MyStruct".into(),
        kind: crate::lsp::SymbolKind::Struct,
        file: PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 10,
        start_col: 0,
        children: vec![SymbolInfo {
            name: "my_method".into(),
            name_path: "MyStruct/my_method".into(),
            kind: crate::lsp::SymbolKind::Method,
            file: PathBuf::from("test.rs"),
            start_line: 2,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        }],
        range_start_line: None,
        detail: None,
    }];

    let mut results = vec![];
    collect_matching(
        &symbols,
        &substr_pred("mystruct/my_method"),
        false,
        None,
        0,
        true,
        &mut results,
        None,
    );
    assert_eq!(
        results.len(),
        1,
        "slash pattern should match exactly 1 result (the method), not the parent struct"
    );
    assert_eq!(results[0]["name"], "my_method");
}

#[test]
fn matches_kind_filter_function_group() {
    use crate::lsp::SymbolKind;
    assert!(matches_kind_filter(&SymbolKind::Function, "function"));
    assert!(matches_kind_filter(&SymbolKind::Method, "function"));
    assert!(matches_kind_filter(&SymbolKind::Constructor, "function"));
    assert!(!matches_kind_filter(&SymbolKind::Variable, "function"));
    assert!(!matches_kind_filter(&SymbolKind::Class, "function"));
}

#[test]
fn filter_variable_symbols_removes_variables_at_all_levels() {
    let input = json!([
        { "name": "PASS", "kind": "Variable", "start_line": 1, "end_line": 1 },
        {
            "name": "call",
            "kind": "Function",
            "start_line": 5,
            "end_line": 10,
            "children": [
                { "name": "tool", "kind": "Variable", "start_line": 6, "end_line": 6 },
                { "name": "params", "kind": "Variable", "start_line": 6, "end_line": 6 }
            ]
        },
        { "name": "assert_contains", "kind": "Function", "start_line": 12, "end_line": 14 }
    ]);
    let result = filter_variable_symbols(input.as_array().unwrap().to_vec());
    assert_eq!(result.len(), 2, "top-level Variable removed");
    assert_eq!(result[0]["name"], "call");
    assert!(
        !result[0].as_object().unwrap().contains_key("children"),
        "empty children stripped"
    );
    assert_eq!(result[1]["name"], "assert_contains");
}

#[test]
fn filter_variable_symbols_preserves_non_variable_children() {
    let input = json!([
        {
            "name": "outer",
            "kind": "Function",
            "start_line": 1,
            "end_line": 10,
            "children": [
                { "name": "inner", "kind": "Function", "start_line": 3, "end_line": 5 },
                { "name": "local_var", "kind": "Variable", "start_line": 6, "end_line": 6 }
            ]
        }
    ]);
    let result = filter_variable_symbols(input.as_array().unwrap().to_vec());
    assert_eq!(result.len(), 1);
    let children = result[0]["children"].as_array().unwrap();
    assert_eq!(children.len(), 1);
    assert_eq!(children[0]["name"], "inner");
}

#[test]
fn matches_kind_filter_struct_vs_class() {
    use crate::lsp::SymbolKind;
    assert!(matches_kind_filter(&SymbolKind::Class, "class"));
    assert!(!matches_kind_filter(&SymbolKind::Struct, "class"));
    assert!(matches_kind_filter(&SymbolKind::Struct, "struct"));
    assert!(!matches_kind_filter(&SymbolKind::Class, "struct"));
}

#[test]
fn matches_kind_filter_module_group() {
    use crate::lsp::SymbolKind;
    assert!(matches_kind_filter(&SymbolKind::Module, "module"));
    assert!(matches_kind_filter(&SymbolKind::Namespace, "module"));
    assert!(matches_kind_filter(&SymbolKind::Package, "module"));
    assert!(!matches_kind_filter(&SymbolKind::Function, "module"));
}

#[test]
fn collect_matching_with_kind_filter_class_only() {
    use crate::lsp::SymbolKind;
    let symbols = vec![
        SymbolInfo {
            name: "WeeklyGrid".into(),
            name_path: "WeeklyGrid".into(),
            kind: SymbolKind::Class,
            file: PathBuf::from("test.ts"),
            start_line: 0,
            end_line: 10,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "weeklyGrid".into(),
            name_path: "weeklyGrid".into(),
            kind: SymbolKind::Variable,
            file: PathBuf::from("test.ts"),
            start_line: 12,
            end_line: 12,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "renderWeeklyGrid".into(),
            name_path: "renderWeeklyGrid".into(),
            kind: SymbolKind::Function,
            file: PathBuf::from("test.ts"),
            start_line: 14,
            end_line: 20,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
    ];

    let mut out = vec![];
    collect_matching(
        &symbols,
        &substr_pred("weeklygrid"),
        false,
        None,
        0,
        true,
        &mut out,
        Some("class"),
    );
    assert_eq!(out.len(), 1);
    assert_eq!(out[0]["name"], "WeeklyGrid");
}

#[test]
fn collect_matching_kind_filter_none_returns_all_matching() {
    use crate::lsp::SymbolKind;
    let symbols = vec![
        SymbolInfo {
            name: "foo".into(),
            name_path: "foo".into(),
            kind: SymbolKind::Function,
            file: PathBuf::from("test.rs"),
            start_line: 0,
            end_line: 5,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
        SymbolInfo {
            name: "FOO".into(),
            name_path: "FOO".into(),
            kind: SymbolKind::Constant,
            file: PathBuf::from("test.rs"),
            start_line: 7,
            end_line: 7,
            start_col: 0,
            children: vec![],
            range_start_line: None,
            detail: None,
        },
    ];

    let mut out = vec![];
    collect_matching(
        &symbols,
        &substr_pred("foo"),
        false,
        None,
        0,
        true,
        &mut out,
        None,
    );
    assert_eq!(
        out.len(),
        2,
        "no filter → all name-matching symbols returned"
    );
}

#[test]
fn build_by_file_sorts_desc_and_caps_at_15() {
    // 20 distinct files, file_i has (20 - i) matches
    let mut matches: Vec<Value> = vec![];
    for i in 0usize..20 {
        for _ in 0..(20 - i) {
            matches.push(json!({ "file": format!("src/file{i}.rs") }));
        }
    }
    let (by_file, overflow) = build_by_file(&matches);
    assert_eq!(by_file.len(), 15, "cap at 15");
    assert_eq!(overflow, 5, "20 files - 15 = 5 overflow");
    // First entry has highest count
    assert_eq!(by_file[0].0, "src/file0.rs");
    assert_eq!(by_file[0].1, 20);
    // Sorted descending
    for w in by_file.windows(2) {
        assert!(w[0].1 >= w[1].1);
    }
}

#[test]
fn build_by_file_no_overflow_under_cap() {
    let matches: Vec<Value> = (0..3)
        .flat_map(|i| vec![json!({ "file": format!("src/f{i}.rs") }); 5])
        .collect();
    let (by_file, overflow) = build_by_file(&matches);
    assert_eq!(by_file.len(), 3);
    assert_eq!(overflow, 0);
}

#[test]
fn make_search_symbols_hint_contains_top_file_and_kind_and_offset() {
    let by_file = vec![
        ("src/components/WeeklyGrid.tsx".to_string(), 12usize),
        ("src/screens/Home.tsx".to_string(), 3),
    ];
    let hint = make_search_symbols_hint(50, &by_file);
    assert!(
        hint.contains("src/components/WeeklyGrid.tsx"),
        "should show top file path"
    );
    assert!(hint.contains("kind="), "should mention kind filter");
    assert!(
        hint.contains("offset=50"),
        "should show next pagination offset"
    );
}

#[test]
fn kind_filter_skipped_when_using_name_path() {
    // Verify the logic: if name_path is set, kind_filter is None.
    let input = json!({ "symbol": "Foo", "kind": "function" });
    let is_name_path = input["symbol"].is_string();
    let kind_filter: Option<&str> = if is_name_path {
        None
    } else {
        input["kind"].as_str()
    };
    assert!(kind_filter.is_none());
}

// ── symbol_to_json field contract ────────────────────────────────────────

fn make_test_sym(name: &str, detail: Option<&str>) -> crate::lsp::SymbolInfo {
    crate::lsp::SymbolInfo {
        name: name.to_string(),
        name_path: name.to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/foo.rs"),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: detail.map(|s| s.to_string()),
    }
}

#[test]
fn symbol_to_json_omits_file_when_show_file_false() {
    let sym = make_test_sym("foo", None);
    let result = symbol_to_json(&sym, false, None, 0, false);
    assert!(
        result.get("file").is_none(),
        "file must be absent when show_file=false, got: {result}"
    );
    assert_eq!(result["name"], "foo");
}

#[test]
fn symbol_to_json_field_order_name_kind_before_line_numbers() {
    // Regression: without preserve_order, serde_json used BTreeMap and sorted keys
    // alphabetically, putting end_line before kind/name. Line numbers must come last
    // as positional metadata, with identity fields (name, kind) first.
    let sym = make_test_sym("my_fn", Some("fn my_fn() -> u32"));
    let result = symbol_to_json(&sym, false, None, 0, false);

    let keys: Vec<&str> = result
        .as_object()
        .unwrap()
        .keys()
        .map(|s| s.as_str())
        .collect();

    // name and name_path come before start_line / end_line
    let name_pos = keys.iter().position(|k| *k == "name").unwrap();
    let start_pos = keys.iter().position(|k| *k == "start_line").unwrap();
    let end_pos = keys.iter().position(|k| *k == "end_line").unwrap();
    assert!(
        name_pos < start_pos,
        "name must appear before start_line, got key order: {keys:?}"
    );
    // start_line comes immediately before end_line
    assert_eq!(
        start_pos + 1,
        end_pos,
        "start_line must immediately precede end_line, got key order: {keys:?}"
    );
    // end_line is the final field
    assert_eq!(
        end_pos,
        keys.len() - 1,
        "end_line must be the last field, got key order: {keys:?}"
    );
}

#[test]
fn symbol_to_json_includes_file_when_show_file_true() {
    let sym = make_test_sym("foo", None);
    let result = symbol_to_json(&sym, false, None, 0, true);
    assert_eq!(result["file"], "src/foo.rs");
}

#[test]
fn symbol_to_json_includes_signature_when_detail_present() {
    let sym = make_test_sym("foo", Some("(x: i32) -> bool"));
    let result = symbol_to_json(&sym, false, None, 0, false);
    assert_eq!(result["signature"], "(x: i32) -> bool");
}

#[test]
fn symbol_to_json_omits_signature_when_detail_absent() {
    let sym = make_test_sym("foo", None);
    let result = symbol_to_json(&sym, false, None, 0, false);
    assert!(
        result.get("signature").is_none(),
        "signature must be absent when detail=None"
    );
}

#[test]
fn symbol_to_json_never_includes_source_field() {
    let sym = make_test_sym("foo", None);
    for show_file in [false, true] {
        let result = symbol_to_json(&sym, false, None, 0, show_file);
        assert!(
            result.get("source").is_none(),
            "source field must never appear (show_file={show_file})"
        );
    }
}

#[test]
fn symbols_overview_flat_cap_triggers_on_symbol_with_many_children() {
    // 20 top-level symbols each with 10 children = 220 flat entries > FLAT_CAP(150).
    // Greedy take: each symbol costs 11 flat entries; 150/11 = 13 symbols fit.
    let symbols: Vec<Value> = (0..20)
        .map(|i| {
            let children: Vec<Value> = (0..10)
                .map(|j| json!({ "name": format!("child_{i}_{j}") }))
                .collect();
            json!({ "name": format!("sym{i}"), "children": children })
        })
        .collect();

    let flat = flat_symbol_count(&symbols);
    assert_eq!(flat, 220); // 20 * (1 + 10)

    // Greedy capping within FLAT_CAP=150
    let budget = LIST_SYMBOLS_SINGLE_FILE_FLAT_CAP;
    let mut remaining = budget;
    let mut capped: Vec<Value> = Vec::new();
    for sym in symbols {
        let cost = 1 + sym["children"].as_array().map(|c| c.len()).unwrap_or(0);
        if cost <= remaining {
            remaining -= cost;
            capped.push(sym);
        } else {
            break;
        }
    }
    // Each symbol costs 11; 13 symbols = 143 flat entries ≤ 150; 14th would be 154.
    assert_eq!(capped.len(), 13);
}

#[test]
fn symbols_overview_flat_cap_not_triggered_for_leaf_heavy_symbols() {
    // 50 top-level leaf symbols (no children) = 50 flat entries — under FLAT_CAP.
    let symbols: Vec<Value> = (0..50)
        .map(|i| json!({ "name": format!("fn{i}") }))
        .collect();
    let flat = flat_symbol_count(&symbols);
    assert_eq!(flat, 50);
    assert!(flat <= LIST_SYMBOLS_SINGLE_FILE_FLAT_CAP);
}

#[test]
fn symbols_overview_single_file_cap_unit() {
    // Unit test: simulate the cap logic on a Vec<Value> of 150 symbol entries.
    use crate::tools::output::OutputGuard;
    let symbols: Vec<Value> = (0..150)
        .map(|i| json!({ "name": format!("sym{i}"), "start_line": i + 1 }))
        .collect();

    const SINGLE_FILE_CAP: usize = 100;
    let total = symbols.len();
    let hint = format!(
        "File has {total} symbols. Use depth=1 for top-level overview, \
         or symbols(name_path='ClassName/methodName', include_body=true) for a specific symbol."
    );
    let g = OutputGuard {
        max_results: SINGLE_FILE_CAP,
        ..OutputGuard::default()
    };
    let (kept, overflow) = g.cap_items(symbols, &hint);

    assert_eq!(kept.len(), 100);
    let ov = overflow.expect("overflow must be present");
    assert_eq!(ov.total, 150);
    assert_eq!(ov.shown, 100);
    assert!(ov.hint.contains("symbols"));
    assert!(ov.hint.contains("symbol"));
    assert!(
        ov.by_file.is_none(),
        "single-file overflow must not include by_file"
    );
}

#[test]
fn symbols_overview_single_file_no_overflow_under_cap_unit() {
    use crate::tools::output::OutputGuard;
    let symbols: Vec<Value> = (0..40)
        .map(|i| json!({ "name": format!("sym{i}") }))
        .collect();

    let g = OutputGuard {
        max_results: 100,
        ..OutputGuard::default()
    };
    let (kept, overflow) = g.cap_items(symbols, "hint");

    assert_eq!(kept.len(), 40);
    assert!(
        overflow.is_none(),
        "no overflow for 40 symbols under cap of 100"
    );
}

#[test]
fn text_sweep_finds_matches_in_comments_and_docs() {
    let dir = tempfile::tempdir().unwrap();

    // Source file with a comment mentioning the old name
    std::fs::write(
        dir.path().join("main.rs"),
        "fn bar() {}\n// FooHandler manages connections\n",
    )
    .unwrap();

    // Documentation file
    std::fs::write(
        dir.path().join("README.md"),
        "# Project\nThe FooHandler struct is the entry point.\nSee FooHandler::new() for details.\n",
    )
    .unwrap();

    // Config file
    std::fs::write(
        dir.path().join("config.toml"),
        "[server]\nhandler = \"FooHandler\"\n",
    )
    .unwrap();

    let lsp_files = std::collections::HashSet::new();
    let matches = text_sweep(dir.path(), "FooHandler", &lsp_files, 20, 2).unwrap();

    // Should find matches in all 3 files
    assert_eq!(matches.len(), 3);

    // Documentation first, then config, then source
    assert_eq!(matches[0].kind, "documentation");
    assert_eq!(matches[1].kind, "config");
    assert_eq!(matches[2].kind, "source");

    // README has 2 occurrences, both shown as previews
    assert_eq!(matches[0].occurrence_count, 2);
    assert_eq!(matches[0].previews.len(), 2);

    // Config has 1 occurrence
    assert_eq!(matches[1].occurrence_count, 1);

    // Source has 1 occurrence (comment line)
    assert_eq!(matches[2].occurrence_count, 1);
}

#[test]
fn text_sweep_skips_lsp_modified_files() {
    let dir = tempfile::tempdir().unwrap();

    let modified_file = dir.path().join("already.rs");
    std::fs::write(&modified_file, "// FooHandler was here\n").unwrap();
    std::fs::write(dir.path().join("untouched.md"), "FooHandler docs\n").unwrap();

    let mut lsp_files = std::collections::HashSet::new();
    lsp_files.insert(modified_file);

    let matches = text_sweep(dir.path(), "FooHandler", &lsp_files, 20, 2).unwrap();

    assert_eq!(matches.len(), 1);
    assert!(matches[0].file.contains("untouched.md"));
}

#[test]
fn text_sweep_respects_max_matches_cap() {
    let dir = tempfile::tempdir().unwrap();

    // Create 30 markdown files, each with one match
    for i in 0..30 {
        std::fs::write(
            dir.path().join(format!("doc{i:02}.md")),
            format!("FooHandler reference in doc {i}\n"),
        )
        .unwrap();
    }

    let lsp_files = std::collections::HashSet::new();
    let matches = text_sweep(dir.path(), "FooHandler", &lsp_files, 20, 2).unwrap();

    assert_eq!(matches.len(), 20);
}

#[test]
fn text_sweep_limits_previews_per_file() {
    let dir = tempfile::tempdir().unwrap();

    // File with 10 occurrences
    let content = (0..10)
        .map(|i| format!("line {i}: FooHandler usage"))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(dir.path().join("many.rs"), &content).unwrap();

    let lsp_files = std::collections::HashSet::new();
    let matches = text_sweep(dir.path(), "FooHandler", &lsp_files, 20, 2).unwrap();

    assert_eq!(matches.len(), 1);
    assert_eq!(matches[0].occurrence_count, 10);
    assert_eq!(matches[0].previews.len(), 2); // capped at 2
    assert_eq!(matches[0].lines.len(), 10); // all line numbers kept
}

#[test]
fn text_sweep_uses_word_boundary() {
    let dir = tempfile::tempdir().unwrap();

    std::fs::write(
        dir.path().join("test.rs"),
        "let foo_handler = 1;\n// FooHandler docs\nlet FooHandlerConfig = 2;\n",
    )
    .unwrap();

    let lsp_files = std::collections::HashSet::new();
    let matches = text_sweep(dir.path(), "FooHandler", &lsp_files, 20, 2).unwrap();

    assert_eq!(matches.len(), 1);
    // \bFooHandler\b does NOT match inside FooHandlerConfig because
    // there's no word boundary between 'r' and 'C' (both are word chars).
    // So only 1 match: the comment line.
    assert_eq!(matches[0].occurrence_count, 1);
    assert!(matches[0].previews[0].contains("// FooHandler docs"));
}

// ── write_lines / splice edge cases ────────────────────────────────────

#[test]
fn write_lines_no_trailing_newline() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.txt");
    let lines: Vec<&str> = vec!["line1", "line2", "line3"];
    write_lines(&file, &lines, false).unwrap();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        "line1\nline2\nline3"
    );
}

#[test]
fn write_lines_with_trailing_newline() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.txt");
    let lines: Vec<&str> = vec!["line1", "line2", "line3"];
    write_lines(&file, &lines, true).unwrap();
    assert_eq!(
        std::fs::read_to_string(&file).unwrap(),
        "line1\nline2\nline3\n"
    );
}

#[test]
fn write_lines_empty_with_trailing_newline() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.txt");
    let lines: Vec<&str> = vec![];
    write_lines(&file, &lines, true).unwrap();
    // Empty content should not become "\n"
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "");
}

/// Simulates the replace_symbol pattern: lines before + multi-line body + lines after.
/// The body should be split into individual lines before inserting.
#[test]
fn splice_multiline_body_no_trailing_newline() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");

    let original = "// before\nfn foo() {\n    old();\n}\n// after\n";
    std::fs::write(&file, original).unwrap();

    let content = std::fs::read_to_string(&file).unwrap();
    let lines: Vec<&str> = content.lines().collect();

    // Simulate replace_symbol: replace lines 1-3 (0-indexed) with new body
    let new_body = "fn foo() {\n    new();\n}";
    let start = 1usize;
    let end = 4usize; // exclusive

    let mut new_lines = Vec::new();
    new_lines.extend_from_slice(&lines[..start]);
    // FIX: split body into lines, don't push as single element
    new_lines.extend(new_body.lines());
    new_lines.extend_from_slice(&lines[end..]);

    write_lines(&file, &new_lines, content.ends_with('\n')).unwrap();

    let result = std::fs::read_to_string(&file).unwrap();
    assert_eq!(result, "// before\nfn foo() {\n    new();\n}\n// after\n");
}

/// When body has trailing newline, the extra \n must NOT create a blank line.
#[test]
fn splice_multiline_body_with_trailing_newline_no_blank_line() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");

    let original = "// before\nfn foo() {\n    old();\n}\n// after\n";
    std::fs::write(&file, original).unwrap();

    let content = std::fs::read_to_string(&file).unwrap();
    let lines: Vec<&str> = content.lines().collect();

    // LLM passes body WITH trailing newline (common)
    let new_body = "fn foo() {\n    new();\n}\n";
    let start = 1usize;
    let end = 4usize;

    let mut new_lines = Vec::new();
    new_lines.extend_from_slice(&lines[..start]);
    new_lines.extend(new_body.lines()); // .lines() strips the trailing \n — correct!
    new_lines.extend_from_slice(&lines[end..]);

    write_lines(&file, &new_lines, content.ends_with('\n')).unwrap();

    let result = std::fs::read_to_string(&file).unwrap();
    // Must NOT have blank line between "}" and "// after"
    assert_eq!(result, "// before\nfn foo() {\n    new();\n}\n// after\n");
}

/// Demonstrates the BUG: pushing multi-line body as single element creates extra blank line
/// when body has trailing newline. This test documents the broken behavior.
#[test]
fn splice_push_single_element_creates_blank_line_bug() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");

    let original = "// before\nfn foo() {\n    old();\n}\n// after\n";
    std::fs::write(&file, original).unwrap();

    let content = std::fs::read_to_string(&file).unwrap();
    let lines: Vec<&str> = content.lines().collect();

    let new_body = "fn foo() {\n    new();\n}\n"; // trailing newline
    let start = 1usize;
    let end = 4usize;

    let mut new_lines = Vec::new();
    new_lines.extend_from_slice(&lines[..start]);
    new_lines.push(new_body); // THE BUG: push as single element
    new_lines.extend_from_slice(&lines[end..]);

    write_lines(&file, &new_lines, content.ends_with('\n')).unwrap();

    let result = std::fs::read_to_string(&file).unwrap();
    // BUG: extra blank line between "}" and "// after"
    assert!(
        result.contains("}\n\n// after"),
        "Expected blank line bug, got: {:?}",
        result
    );
}

#[test]
fn apply_text_edits_preserves_trailing_newline() {
    let content = "hello world\nfoo bar\nbaz\n";
    let edits = vec![lsp_types::TextEdit {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 1,
                character: 0,
            },
            end: lsp_types::Position {
                line: 1,
                character: 7,
            },
        },
        new_text: "replaced".to_string(),
    }];
    let result = apply_text_edits(content, &edits);
    assert_eq!(result, "hello world\nreplaced\nbaz\n");
}

#[test]
fn apply_text_edits_multiline_replacement() {
    let content = "aaa\nbbb\nccc\n";
    let edits = vec![lsp_types::TextEdit {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 1,
                character: 0,
            },
            end: lsp_types::Position {
                line: 1,
                character: 3,
            },
        },
        new_text: "xxx\nyyy".to_string(),
    }];
    let result = apply_text_edits(content, &edits);
    assert_eq!(result, "aaa\nxxx\nyyy\nccc\n");
}

// ── BUG-002: apply_text_edits uses UTF-16 offsets correctly ─────────────

/// LSP character positions are UTF-16 code units.  A line like
/// `// α foo` has `α` (U+03B1) at byte 3, but at UTF-16 offset 3.
/// `foo` starts at byte 6 but UTF-16 offset 5.
/// The old byte-index code would slice at byte 5, landing mid-codepoint
/// and either panicking or producing garbled text.
#[test]
fn apply_text_edits_utf16_offset() {
    // Line 0: "// α: foo"
    //   byte offsets:  0='/', 1='/', 2=' ', 3..5='α'(2 bytes), 5=':', 6=' ', 7='f', 8='o', 9='o'
    //   UTF-16 offsets: 0='/', 1='/', 2=' ', 3='α'(1 unit),    4=':', 5=' ', 6='f', 7='o', 8='o'
    // Replace "foo" (UTF-16 chars 6..9) with "bar"
    let content = "// \u{03B1}: foo\n";
    let edits = vec![lsp_types::TextEdit {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 0,
                character: 6,
            },
            end: lsp_types::Position {
                line: 0,
                character: 9,
            },
        },
        new_text: "bar".to_string(),
    }];
    let result = apply_text_edits(content, &edits);
    assert_eq!(result, "// \u{03B1}: bar\n");
}

/// Surrogate pair: emoji (U+1F600) is 4 UTF-8 bytes but 2 UTF-16 code units.
/// Text after the emoji has a higher UTF-16 offset than byte offset.
#[test]
fn apply_text_edits_utf16_surrogate_pair() {
    // Line: "😀 foo"
    //   bytes: 0..3=😀(4 bytes), 4=' ', 5='f', 6='o', 7='o'
    //   UTF-16: 0..1=😀(2 units), 2=' ', 3='f', 4='o', 5='o'
    // Replace "foo" (UTF-16 3..6) with "bar"
    let content = "\u{1F600} foo\n";
    let edits = vec![lsp_types::TextEdit {
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 0,
                character: 3,
            },
            end: lsp_types::Position {
                line: 0,
                character: 6,
            },
        },
        new_text: "bar".to_string(),
    }];
    let result = apply_text_edits(content, &edits);
    assert_eq!(result, "\u{1F600} bar\n");
}

// ── find_insert_before_line tests ──────────────────────────────────────

#[test]
fn find_insert_before_line_walks_past_doc_comments() {
    // Blank line between code and docs is NOT consumed (stops at blank line)
    let lines = vec![
        "other code",
        "",
        "/// Doc line 1",
        "/// Doc line 2",
        "fn foo() {}",
    ];
    assert_eq!(find_insert_before_line(&lines, 4), 2);
}

#[test]
fn find_insert_before_line_walks_past_attributes() {
    let lines = vec!["other code", "#[test]", "#[ignore]", "fn foo() {}"];
    assert_eq!(find_insert_before_line(&lines, 3), 1);
}

#[test]
fn find_insert_before_line_stops_at_code() {
    let lines = vec!["let x = 1;", "fn foo() {}"];
    assert_eq!(find_insert_before_line(&lines, 1), 1);
}

#[test]
fn find_insert_before_line_walks_past_kdoc_bare_asterisk_line() {
    // A bare `*` continuation line (KDoc/JSDoc blank doc line) must not stop the walk.
    // Reproduces the root cause of BUG-027: kotlin-language-server reports range.start
    // mid-docstring; the heuristic must walk past bare `*` lines to reach `/**`.
    let lines = vec![
        "other code",             // 0
        "",                       // 1 — blank line: stops the walk
        "    /**",                // 2 — doc opener: expected editing start
        "     * Description.",    // 3
        "     *",                 // 4 — bare asterisk (blank doc continuation)
        "     * @param x ...",    // 5
        "     */",                // 6
        "    fun foo(x: Int) {}", // 7 — symbol_start
    ];
    assert_eq!(find_insert_before_line(&lines, 7), 2);
}

#[test]
fn find_insert_before_line_at_start_of_file() {
    let lines = vec!["/// Doc", "fn foo() {}"];
    assert_eq!(find_insert_before_line(&lines, 1), 0);
}

#[test]
fn editing_start_line_uses_range_start_line_when_present() {
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 8,
        end_line: 12,
        start_col: 0,
        children: vec![],
        range_start_line: Some(5),
        detail: None,
    };
    let lines = vec![
        "other code",
        "",
        "/// doc1",
        "/// doc2",
        "#[test]",
        "#[ignore]", // line 5 — range_start_line
        "// between",
        "// gap",
        "fn foo() {", // line 8 — start_line (selectionRange)
        "    body",
        "}",
    ];
    // Should use range_start_line (5), NOT heuristic or start_line
    assert_eq!(editing_start_line(&sym, &lines), 5);
}

#[test]
fn editing_start_line_falls_back_to_heuristic_when_none() {
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 3,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let lines = vec![
        "other code",
        "#[test]",
        "#[ignore]",
        "fn foo() {", // line 3
        "    body",
        "}",
    ];
    // No range_start_line → heuristic walks back past #[test] #[ignore]
    assert_eq!(editing_start_line(&sym, &lines), 1);
}

#[test]
fn editing_start_line_walks_back_to_block_comment_opener_when_lsp_range_is_mid_comment() {
    // Reproduces BUG-027: kotlin-language-server sets range.start at the first @param
    // line inside a KDoc block, not at the `/**` opener. If editing_start_line trusts
    // this blindly, replace_symbol leaves `/**\n * preamble\n *\n` behind — an unclosed
    // block comment that cascades into Kotlin "Unresolved reference" compile errors.
    let sym = crate::lsp::SymbolInfo {
        name: "createSolver".to_string(),
        name_path: "Stage1SolverConfigFactory/createSolver".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("Stage1SolverConfigFactory.kt"),
        start_line: 6, // "fun createSolver("
        end_line: 9,
        start_col: 4,
        children: vec![],
        range_start_line: Some(3), // Kotlin LSP lands here: "* @param lessonCount"
        detail: None,
    };
    let lines = vec![
        "    /**",                                 // 0 ← correct editing start
        "     * Create a configured solver.",      // 1
        "     *",                                  // 2 — bare asterisk
        "     * @param lessonCount Number of ...", // 3 ← range_start_line (Kotlin LSP bug)
        "     * @param moveThreadCount Threads",   // 4
        "     */",                                 // 5
        "    fun createSolver(",                   // 6 ← start_line
        "        lessonCount: Int,",               // 7
        "        moveThreadCount: Int = 4,",       // 8
        "    ): Solver<Stage1Solution> { }",       // 9
    ];
    // Must return 0 (the `/**` opener), not 3 (the Kotlin LSP's wrong range.start)
    assert_eq!(editing_start_line(&sym, &lines), 0);
}

#[test]
fn editing_start_line_does_not_walk_back_from_attribute_even_if_lsp_range_set() {
    // Regression: attributes (#[attr]) must NOT trigger the block-comment walk-back.
    // range_start_line = Some(5) pointing to `#[ignore]` must be used as-is.
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 8,
        end_line: 12,
        start_col: 0,
        children: vec![],
        range_start_line: Some(5), // `#[ignore]` — NOT inside a block comment
        detail: None,
    };
    let lines = vec![
        "other code", // 0
        "",           // 1
        "/// doc1",   // 2
        "/// doc2",   // 3
        "#[test]",    // 4
        "#[ignore]",  // 5 ← range_start_line — correctly at attribute start
        "// between", // 6
        "// gap",     // 7
        "fn foo() {", // 8 ← start_line
        "    body",   // 9
        "}",          // 10
    ];
    // Must return 5 unchanged — not walk back further into the doc comments
    assert_eq!(editing_start_line(&sym, &lines), 5);
}
/// BUG-031 reproduction: rust-analyzer sets range_start_line to the `pub fn`
/// line, skipping `///` doc comments above. editing_start_line must detect
/// this and walk back to include the doc comments — otherwise replace_symbol
/// leaves the old doc comments orphaned and duplicates them.
#[test]
fn editing_start_line_walks_back_past_doc_comments_when_range_misses_them() {
    let sym = crate::lsp::SymbolInfo {
        name: "is_source_path".to_string(),
        name_path: "is_source_path".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 5, // `pub fn is_source_path(...)` — selectionRange
        end_line: 9,
        start_col: 0,
        children: vec![],
        range_start_line: Some(5), // LSP range.start = fn line, missed doc comments
        detail: None,
    };
    let lines = vec![
        "use regex::Regex;",                                          // 0
        "",                                                           // 1
        "/// Returns true if the path refers to a source code file.", // 2
        "/// Used to gate `edit_file` multi-line source edits.",      // 3
        "#[inline]",                                                  // 4
        "pub fn is_source_path(path: &str) -> bool {",                // 5 ← range_start_line
        "    Regex::new(SOURCE_EXTENSIONS)",                          // 6
        "        .map(|re| re.is_match(path))",                       // 7
        "        .unwrap_or(false)",                                  // 8
        "}",                                                          // 9
    ];
    // Must return 2 (first `///` doc comment), not 5 (range_start_line)
    assert_eq!(editing_start_line(&sym, &lines), 2);
}

/// BUG-031 variant: range_start_line correctly includes doc comments (points
/// to first `///` line). editing_start_line should trust it and NOT walk back
/// further past a blank line into unrelated code.
#[test]
fn editing_start_line_trusts_range_when_it_already_covers_docs() {
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 5,
        end_line: 7,
        start_col: 0,
        children: vec![],
        range_start_line: Some(3), // Points to first `///` — correct!
        detail: None,
    };
    let lines = vec![
        "fn unrelated() {}", // 0
        "// random comment", // 1
        "",                  // 2 — blank line separates
        "/// Doc for foo",   // 3 ← range_start_line (correct)
        "#[test]",           // 4
        "fn foo() {",        // 5
        "    body",          // 6
        "}",                 // 7
    ];
    // Should stay at 3, not walk back past blank line to 1
    assert_eq!(editing_start_line(&sym, &lines), 3);
}

/// BUG-037 regression: rust-analyzer starts `impl Trait for Type` range at
/// the `impl` keyword, excluding the outer `#[async_trait]` attribute.
/// `editing_start_line` must return the `impl` line unchanged — walking back
/// to include the attribute in the editing range would silently drop it, since
/// the LLM's `new_body` starts at `impl` (matching what `symbols` shows).
#[test]
fn editing_start_line_does_not_walk_back_to_outer_attribute_on_impl_block() {
    let sym = crate::lsp::SymbolInfo {
        name: "impl SomeTrait for SomeType".to_string(),
        name_path: "impl SomeTrait for SomeType".to_string(),
        kind: crate::lsp::SymbolKind::Object,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 2,
        end_line: 6,
        start_col: 0,
        children: vec![],
        range_start_line: Some(2), // rust-analyzer starts at `impl`, not `#[async_trait]`
        detail: None,
    };
    let lines = vec![
        "}",                             // 0 ← end of a previous impl block
        "#[async_trait::async_trait]",   // 1 ← attribute NOT in LSP range
        "impl SomeTrait for SomeType {", // 2 ← range_start_line
        "    async fn foo(&self) {",     // 3
        "    }",                         // 4
        "}",                             // 5
    ];
    // Must return 2 (the `impl` line) — not 1 (the attribute).
    // Walking back to 1 would include `#[async_trait]` in the deletion range
    // while the LLM's new_body starts at `impl`, silently dropping the attribute.
    assert_eq!(editing_start_line(&sym, &lines), 2);
}

/// BUG-037 corollary: when doc comments ARE present above the attribute+impl,
/// walk-back is still triggered (BUG-031 behaviour) because the LLM is expected
/// to include docs in new_body.
#[test]
fn editing_start_line_walks_back_when_docs_exist_above_attribute_on_impl() {
    let sym = crate::lsp::SymbolInfo {
        name: "impl SomeTrait for SomeType".to_string(),
        name_path: "impl SomeTrait for SomeType".to_string(),
        kind: crate::lsp::SymbolKind::Object,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 3,
        end_line: 6,
        start_col: 0,
        children: vec![],
        range_start_line: Some(3), // range starts at `impl`
        detail: None,
    };
    let lines = vec![
        "}",                             // 0 ← end of a previous block
        "/// Implements SomeTrait.",     // 1 ← doc comment above the attribute
        "#[async_trait::async_trait]",   // 2
        "impl SomeTrait for SomeType {", // 3 ← range_start_line
        "    async fn foo(&self) {}",    // 4
        "}",                             // 5
    ];
    // Doc comment at line 1 triggers walk-back — returns 1.
    assert_eq!(editing_start_line(&sym, &lines), 1);
}

/// BUG-029 reproduction: editing_end_line uses AST to cap LSP end_line.
/// For async nested functions inside `mod tests`, AST may return a different
/// end_line, causing insert_code "after" to misplace code.
#[test]
fn editing_end_line_nested_fn_returns_closing_brace_line() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    // Reproduce the actual BUG-029 scenario: async fn inside mod tests
    let source = "\
use serde_json::json;

pub async fn write_message(writer: &mut Vec<u8>, msg: &str) -> Result<(), std::io::Error> {
writer.extend_from_slice(msg.as_bytes());
Ok(())
}

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

#[tokio::test]
async fn write_produces_valid_framing() {
    let msg = json!({\"test\": true});
    let mut buf = Vec::new();
    write_message(&mut buf, &msg.to_string()).await.unwrap();
    assert!(!buf.is_empty());
}

#[tokio::test]
async fn another_test() {
    let x = 42;
    assert_eq!(x, 42);
}
}
";
    std::fs::write(&file, source).unwrap();

    // Simulate what LSP returns for `write_produces_valid_framing`
    let sym = crate::lsp::SymbolInfo {
        name: "write_produces_valid_framing".to_string(),
        name_path: "tests/write_produces_valid_framing".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 12, // `async fn write_produces_valid_framing` (0-indexed)
        end_line: 17,   // closing `}` of write_produces_valid_framing
        start_col: 4,
        children: vec![],
        range_start_line: Some(11), // `#[tokio::test]`
        detail: None,
    };

    let end = editing_end_line(&sym);
    // Must return 17 (the `}` line), NOT something smaller
    assert_eq!(
        end, 17,
        "editing_end_line should return closing brace line (17), got {end}"
    );

    // Verify the insertion point is correct
    let lines: Vec<&str> = source.lines().collect();
    let insert_at = (end as usize + 1).min(lines.len());
    assert!(
        insert_at <= lines.len(),
        "insert point should be within file bounds"
    );
    // Line after closing brace should be empty or start of next function
    if insert_at < lines.len() {
        let next_line = lines[insert_at].trim();
        assert!(
            next_line.is_empty()
                || next_line.starts_with('#')
                || next_line.starts_with("async")
                || next_line.starts_with("fn"),
            "line after insert should be blank or next function start, got: '{next_line}'"
        );
    }
}
/// BUG-029 scenario: LSP reports end_line inside the function body (at last
/// statement, not closing `}`). AST should correct this upward.
#[test]
fn editing_end_line_corrects_lsp_short_end_line_via_ast() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    let source = "\
fn foo() {
let x = 1;
let y = 2;
println!(\"{}\", x + y);
}
";
    std::fs::write(&file, source).unwrap();

    // Simulate LSP returning end_line at the last statement (line 3) instead of `}` (line 4)
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 3, // WRONG — points to last statement, not `}`
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };

    let end = editing_end_line(&sym);
    // AST should find end_line=4 (the `}`) which is > 3, so it won't cap.
    // Current code only caps when ast_end < sym.end_line.
    // This means a short LSP end_line is NOT corrected upward — this IS the bug.
    // We need editing_end_line to also correct UPWARD when AST shows more.
    assert_eq!(
        end, 4,
        "editing_end_line should correct short LSP end to AST end (4), got {end}"
    );
}

/// BUG-051 regression: when the file has syntax errors (common mid-session),
/// `editing_end_line` must still use AST rather than falling back to LSP's
/// `end_line` — which often points to the last *statement*, not the closing `}`.
/// Insertion anchored on LSP's short end_line splits multi-line expressions.
#[test]
fn editing_end_line_with_syntax_errors_uses_ast_not_lsp_fallback() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    // File has a syntax error (incomplete macro in `broken`) but `target` is valid.
    // LSP reports target's end_line=3 (last statement), real `}` is at line 5 (0-indexed).
    let source = "\
fn target() {\n\
let x = 1;\n\
let y = 2;\n\
println!(\"{}\", x + y);\n\
let z = x + y;\n\
}\n\
\n\
fn broken() {\n\
    vec![1, 2,\n\
";
    std::fs::write(&file, source).unwrap();

    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 3, // LSP short-reports: last statement, not `}`
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };

    let end = editing_end_line(&sym);
    // AST (tree-sitter) correctly identifies `}` at line 5 (0-indexed) even
    // though `broken` has a syntax error. Must NOT return lsp end_line=3.
    assert_eq!(
        end, 5,
        "editing_end_line must return AST's closing brace line (5), not LSP short-report (3), got {end}"
    );
}

/// BUG-029 + syntax errors: when the file has syntax errors AND LSP over-extends
/// by one line (e.g. rust-analyzer reporting the first line of the next function),
/// `editing_end_line` must still trust AST — not `max(ast, lsp)`, which would
/// return the inflated LSP value and insert after the next symbol's opening line.
#[test]
fn editing_end_line_syntax_errors_do_not_regress_lsp_overextend() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    // `target` closes at line 3 (`}`). `broken` has a syntax error.
    // LSP over-reports target's end_line=4 (the `fn broken` line).
    let source = "\
fn target() {\n\
let x = 1;\n\
}\n\
fn broken() {\n\
    vec![1, 2,\n\
";
    std::fs::write(&file, source).unwrap();

    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 4, // LSP over-reports: includes `fn broken()` line
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };

    let end = editing_end_line(&sym);
    // AST should return 2 (`}` of target, 0-indexed). We must NOT take
    // max(2, 4)=4, which would anchor insertion inside `broken`.
    assert_eq!(
        end, 2,
        "editing_end_line must trust AST (2) not max with over-extended LSP (4), got {end}"
    );
}

/// BUG-051 residual coverage: `editing_end_line_strict` must return `None`
/// when AST cannot pinpoint the symbol's end line. Callers (notably
/// `do_insert` "after") use this to refuse the operation rather than fall
/// back to LSP's possibly-wrong end_line and silently splice new code
/// mid-function.
#[test]
fn editing_end_line_strict_returns_none_when_ast_cannot_find_symbol() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    std::fs::write(&file, "fn other_fn() {\n    do_thing();\n}\n").unwrap();

    // Pretend LSP reported a symbol that the AST cannot find — the dangerous
    // pre-fix path returned `sym.end_line` (LSP's bogus value) silently.
    let sym = crate::lsp::SymbolInfo {
        name: "ghost_fn".to_string(),
        name_path: "ghost_fn".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 1,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };

    let result = editing_end_line_strict(&sym);
    assert!(
        result.is_none(),
        "strict variant must refuse when AST cannot find the symbol, got {result:?}"
    );
}

/// Happy path: a clean file with a real symbol — strict and lenient agree.
#[test]
fn editing_end_line_strict_returns_some_when_ast_finds_symbol() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("test.rs");
    std::fs::write(&file, "fn target() {\n    let x = 1;\n    let y = 2;\n}\n").unwrap();

    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };

    assert_eq!(
        editing_end_line_strict(&sym),
        Some(3),
        "strict variant must return AST-confirmed end line on a clean file"
    );
}

// ── clamp_range_to_parent: T1 unit tests ─────────────────────────────
// These are pure-logic tests (no LSP, no filesystem) that pin down the
// symmetric parent clamp added for BUG-030/034/037/044.

#[test]
fn clamp_range_to_parent_caps_end_at_parent_closer() {
    // Child range overshoots into parent's closer (or beyond).
    // parent body occupies lines 1..20 (exclusive end = 20, the `}` line).
    let (s, e) = clamp_range_to_parent(5, 26, 1, 20);
    assert_eq!((s, e), (5, 20), "end must be capped at parent closer line");
}

#[test]
fn clamp_range_to_parent_lifts_start_to_parent_body_start() {
    // Child range starts above parent body (e.g. stale LSP points at parent's
    // attribute line).
    let (s, e) = clamp_range_to_parent(0, 10, 1, 20);
    assert_eq!((s, e), (1, 10), "start must be lifted to parent body start");
}

#[test]
fn clamp_range_to_parent_passthrough_when_within_bounds() {
    let (s, e) = clamp_range_to_parent(5, 10, 1, 20);
    assert_eq!((s, e), (5, 10), "well-formed ranges must pass through");
}

#[test]
fn clamp_range_to_parent_preserves_start_le_end_invariant_on_collapse() {
    // Pathological input: start > parent body end. Clamp must not produce
    // end < start (would panic on `lines[start..end]`).
    let (s, e) = clamp_range_to_parent(25, 30, 1, 20);
    assert!(s <= e, "start must remain <= end after clamp, got {s}..{e}");
}

#[test]
fn clamp_range_to_parent_exact_fit_is_identity() {
    // Child exactly fills parent body.
    let (s, e) = clamp_range_to_parent(1, 20, 1, 20);
    assert_eq!((s, e), (1, 20));
}

#[test]
fn clamp_range_to_parent_simulates_bug_044_impl_method_overshoot() {
    // BUG-044 repro at the pure-logic layer:
    //   impl LeafOp {        // line 0
    //       fn parse(...)    // lines 1–9
    //       fn sql(...)      // lines 10–18
    //   }                    // line 19 (parent closer)
    //
    // Suppose LSP reports `parse` with range end_line = 18 (overshooting
    // into `sql`). Without the clamp the replacement eats `sql`. With the
    // clamp we stop at the method's own `}` — but that requires an AST
    // correction too. The clamp's role here is to make sure we never
    // *exceed* the parent closer even if AST also misfires.
    //
    // Simulating the worst case: end overshoots past the parent closer.
    let parent_body_start = 1;
    let parent_body_end_exclusive = 19; // `}` of impl LeafOp
    let (s, e) = clamp_range_to_parent(1, 22, parent_body_start, parent_body_end_exclusive);
    assert_eq!(
        e, 19,
        "must not extend past parent closer even under extreme overshoot"
    );
    assert_eq!(s, 1);
}

/// BUG-030 reproduction: replace_symbol on `mod tests` eats the preceding
/// function. editing_start_line with range_start_line pointing to `#[cfg(test)]`
/// should NOT walk back past the blank line into `write_message`'s closing `}`.
#[test]
fn editing_start_line_mod_tests_does_not_eat_preceding_function() {
    let sym = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 7, // `mod tests {`
        end_line: 15,
        start_col: 0,
        children: vec![],
        range_start_line: Some(6), // `#[cfg(test)]`
        detail: None,
    };
    let lines = vec![
        "pub async fn write_message() -> Result<()> {", // 0
        "    let body = serde_json::to_string(msg)?;",  // 1
        "    let header = format!(\"Content-Length: {}\\r\\n\\r\\n\", body.len());", // 2
        "    writer.write_all(header.as_bytes()).await?;", // 3
        "}",                                            // 4
        "",                                             // 5 — blank line
        "#[cfg(test)]",                                 // 6 ← range_start_line
        "mod tests {",                                  // 7 ← start_line
        "    use super::*;",                            // 8
        "    #[test]",                                  // 9
        "    fn test_foo() {}",                         // 10
        "}",                                            // 11
    ];
    // Must return 6 (#[cfg(test)]), NOT walk back past blank line to 4 or earlier
    let result = editing_start_line(&sym, &lines);
    assert_eq!(
        result, 6,
        "editing_start_line should stop at #[cfg(test)] (6), got {result}"
    );
}
/// BUG-030 variant: range_start_line is None (workspace/symbol or tree-sitter).
/// find_insert_before_line must stop at the blank line and not consume
/// the preceding function's closing `}`.
#[test]
fn editing_start_line_mod_tests_no_range_stops_at_blank_line() {
    let sym = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 5, // `mod tests {` (0-indexed)
        end_line: 8,
        start_col: 0,
        children: vec![],
        range_start_line: None, // No range info
        detail: None,
    };
    let lines = vec![
        "pub async fn write_message() -> Result<()> {", // 0
        "    let body = \"hello\";",                    // 1
        "}",                                            // 2
        "",                                             // 3 — blank line
        "#[cfg(test)]",                                 // 4
        "mod tests {",                                  // 5 ← start_line
        "    #[test]",                                  // 6
        "    fn test_foo() {}",                         // 7
        "}",                                            // 8
    ];
    // Heuristic walks back from line 5 past #[cfg(test)] to line 4,
    // stops at blank line 3. Must return 4, NOT 2 or earlier.
    let result = editing_start_line(&sym, &lines);
    assert_eq!(result, 4, "should stop at #[cfg(test)] (4), got {result}");
}

/// BUG-030 variant: NO blank line between preceding function and #[cfg(test)].
/// This is the dangerous case — find_insert_before_line might walk into the
/// preceding function's closing `}`.
#[test]
fn editing_start_line_mod_tests_no_blank_line_between_functions() {
    let sym = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 4, // `mod tests {`
        end_line: 8,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let lines = vec![
        "pub fn write_message() -> Result<()> {", // 0
        "    let body = \"hello\";",              // 1
        "}",                                      // 2
        "#[cfg(test)]",                           // 3 — NO blank line before this
        "mod tests {",                            // 4 ← start_line
        "    #[test]",                            // 5
        "    fn test_foo() {}",                   // 6
        "}",                                      // 7
    ];
    // Walk back from 4 past #[cfg(test)] to 3. Line 2 is `}` — code, must stop.
    let result = editing_start_line(&sym, &lines);
    assert_eq!(
        result, 3,
        "should stop at #[cfg(test)] (3), not eat into write_message; got {result}"
    );
}
/// BUG-032: validate_symbol_position detects stale LSP positions.
/// After removing lines from a file, LSP may return positions from the
/// pre-removal state. The validation catches this mismatch.
#[test]
fn validate_symbol_position_detects_stale_positions() {
    // Original file: enum SourceFilter at lines 0-4, impl SourceFilter at lines 6-11
    let original_lines = vec![
        "pub enum SourceFilter {",                                   // 0
        "    All,",                                                  // 1
        "    SourceOnly,",                                           // 2
        "    NonSourceOnly,",                                        // 3
        "}",                                                         // 4
        "",                                                          // 5
        "impl SourceFilter {",                                       // 6
        "    pub fn as_sql_filter(&self) -> Option<&'static str> {", // 7
        "        None",                                              // 8
        "    }",                                                     // 9
        "}",                                                         // 10
        "",                                                          // 11
        "pub fn project_db_path() {}",                               // 12
    ];

    // Symbol for impl SourceFilter — correct in original file
    let sym_impl = crate::lsp::SymbolInfo {
        name: "SourceFilter".to_string(),
        name_path: "impl SourceFilter".to_string(),
        kind: crate::lsp::SymbolKind::Struct,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 6, // `impl SourceFilter {` in ORIGINAL file
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: Some(6),
        detail: None,
    };

    // Validates fine against original file
    assert!(
        validate_symbol_position(&sym_impl, &original_lines).is_ok(),
        "should be valid against original file"
    );

    // Now simulate removing enum (lines 0-5): file shifts up by 6 lines
    let after_removal = vec![
        "impl SourceFilter {",                                       // 0 (was 6)
        "    pub fn as_sql_filter(&self) -> Option<&'static str> {", // 1
        "        None",                                              // 2
        "    }",                                                     // 3
        "}",                                                         // 4
        "",                                                          // 5
        "pub fn project_db_path() {}",                               // 6 (was 12)
    ];

    // LSP still reports start_line=6 (stale) — but line 6 is now project_db_path
    let result = validate_symbol_position(&sym_impl, &after_removal);
    assert!(
        result.is_err(),
        "should detect stale position: 'SourceFilter' not at line 6 in modified file"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("stale"),
        "error should mention stale; got: {msg}"
    );
}
/// BUG-036: validate_symbol_position catches stale start_line inside preceding function.
/// insert_code before: mod tests can land inside the preceding function when the LSP
/// returns a start_line that points inside that function's body (stale after a large
/// insertion above). The old check (name anywhere in [range_start..end_line]) missed
/// this because the name still appeared at the true declaration line later in the window.
/// The tighter [start_line..start_line+3] window catches it.
#[test]
fn validate_symbol_position_catches_start_line_inside_preceding_function() {
    let lines = vec![
        "pub fn read(&self) -> Result<Summary> {", // 0
        "    let data = self.load()?;",            // 1
        "    Ok(Summary { data })",                // 2
        "}",                                       // 3
        "",                                        // 4
        "#[cfg(test)]",                            // 5
        "mod tests {",                             // 6
        "    use super::*;",                       // 7
        "    #[test]",                             // 8
        "    fn test_read() {}",                   // 9
        "}",                                       // 10
    ];

    // Correct position: start_line=6, range_start_line=5
    let sym_correct = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 6,
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: Some(5),
        detail: None,
    };
    assert!(
        validate_symbol_position(&sym_correct, &lines).is_ok(),
        "correct position should validate"
    );

    // Stale position: start_line=2 (inside preceding function body).
    // Old check: "tests" appears at line 6 which is within [min(5,2)..11] → passes WRONGLY.
    // New check: [2..5] does not contain "tests" → correctly detected as stale.
    let sym_stale = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 2, // stale — points inside `read` method body
        end_line: 10,
        start_col: 0,
        children: vec![],
        range_start_line: Some(2),
        detail: None,
    };
    let result = validate_symbol_position(&sym_stale, &lines);
    assert!(
        result.is_err(),
        "stale start_line inside preceding function should be detected"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("stale"),
        "error should mention stale; got: {msg}"
    );
}
/// Lead-in case: LSP returns start_line at a closing `})` of preceding macro,
/// real symbol is 3 lines below. Must accept (matches existing
/// `replace_symbol_trusts_lsp_start_with_paren_close` expectation).
#[test]
fn validate_symbol_position_accepts_lead_in_paren_close() {
    let lines = vec![
        "        })",          // 0 — start_line (lead-in: closing paren of preceding macro)
        "    }",               // 1 — closing brace of preceding method
        "",                    // 2 — blank line
        "    fn target() {",   // 3 — actual declaration
        "        old_body();", // 4
        "    }",               // 5
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    assert!(
        validate_symbol_position(&sym, &lines).is_ok(),
        "lead-in `}})` at start_line should be accepted"
    );
}

/// Lead-in case: start_line on a blank line, name a few lines below.
#[test]
fn validate_symbol_position_accepts_lead_in_blank_line() {
    let lines = vec![
        "",              // 0 — start_line (blank)
        "fn target() {", // 1
        "    body();",   // 2
        "}",             // 3
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

/// Lead-in case: start_line on a `#[cfg(test)]` attribute, name below.
#[test]
fn validate_symbol_position_accepts_lead_in_rust_attribute() {
    let lines = vec![
        "#[cfg(test)]", // 0 — start_line (attribute)
        "mod tests {",  // 1
        "}",            // 2
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "tests".to_string(),
        name_path: "tests".to_string(),
        kind: crate::lsp::SymbolKind::Module,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 2,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

/// Lead-in case: start_line on a Python `@decorator`, name on def line below.
#[test]
fn validate_symbol_position_accepts_lead_in_python_decorator() {
    let lines = vec![
        "@decorator",     // 0 — start_line (decorator)
        "def my_func():", // 1
        "    pass",       // 2
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "my_func".to_string(),
        name_path: "my_func".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.py"),
        start_line: 0,
        end_line: 2,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

/// Lead-in case: KDoc continuation line (Kotlin LSP BUG-027 quirk where
/// range.start lands on a `* @param` line inside a `/** */` block).
/// `start_line` could land on a `*` continuation line — name on the actual
/// `fun` declaration a few lines below.
#[test]
fn validate_symbol_position_accepts_lead_in_kdoc_continuation() {
    let lines = vec![
        "/**",                   // 0
        " * @param x the param", // 1 — start_line (KDoc continuation)
        " */",                   // 2
        "fun target() {}",       // 3
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.kt"),
        start_line: 1,
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: Some(1),
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

/// BUG-036 variant: lead-in claim but name not within window — still stale.
/// start_line on a blank line, but the actual symbol is 10+ lines below
/// (way beyond the lead-in window).
#[test]
fn validate_symbol_position_catches_lead_in_with_distant_name() {
    let lines = vec![
        "",                     // 0 — start_line (lead-in)
        "fn unrelated_one() {", // 1
        "    do_thing();",      // 2
        "}",                    // 3
        "",                     // 4
        "fn unrelated_two() {", // 5
        "    do_other();",      // 6
        "}",                    // 7
        "",                     // 8
        "fn target() {}",       // 9 — too far for the 6-line window
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "target".to_string(),
        name_path: "target".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 9,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let result = validate_symbol_position(&sym, &lines);
    assert!(
        result.is_err(),
        "name 9 lines below lead-in should be detected as stale"
    );
    assert!(result.unwrap_err().to_string().contains("stale"));
}

/// Multi-line Rust signature: name on start_line, args wrapped below.
#[test]
fn validate_symbol_position_accepts_multiline_signature() {
    let lines = vec![
        "pub fn long_name(", // 0 — start_line, name here
        "    arg1: T,",      // 1
        "    arg2: U,",      // 2
        ") -> R {",          // 3
        "    body()",        // 4
        "}",                 // 5
    ];
    let sym = crate::lsp::SymbolInfo {
        name: "long_name".to_string(),
        name_path: "long_name".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 0,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

/// `is_lead_in_line` unit cases — boundary behaviour.
#[test]
fn is_lead_in_line_classification() {
    // True (lead-in)
    assert!(is_lead_in_line(""));
    assert!(is_lead_in_line("    "));
    assert!(is_lead_in_line("}"));
    assert!(is_lead_in_line("    }"));
    assert!(is_lead_in_line("})"));
    assert!(is_lead_in_line("        })"));
    assert!(is_lead_in_line("});"));
    assert!(is_lead_in_line("})?;"));
    assert!(is_lead_in_line("},"));
    assert!(is_lead_in_line("// a comment"));
    assert!(is_lead_in_line("/// doc comment"));
    assert!(is_lead_in_line("/* block */"));
    assert!(is_lead_in_line(" * KDoc continuation"));
    assert!(is_lead_in_line("*/"));
    assert!(is_lead_in_line("@decorator"));
    assert!(is_lead_in_line("@Override"));
    assert!(is_lead_in_line("#[cfg(test)]"));
    assert!(is_lead_in_line("#![allow(unused)]"));

    // False (real code)
    assert!(!is_lead_in_line("fn foo() {"));
    assert!(!is_lead_in_line("    let x = 1;"));
    assert!(!is_lead_in_line("class Foo {"));
    assert!(!is_lead_in_line("def bar():"));
    assert!(!is_lead_in_line("    return value"));
    assert!(!is_lead_in_line("pub mod tests;"));
}

/// validate_symbol_position accepts valid positions within ±2 line window.
#[test]
fn validate_symbol_position_accepts_valid_position() {
    let lines = vec!["/// doc comment", "pub fn my_function() {", "    body", "}"];
    let sym = crate::lsp::SymbolInfo {
        name: "my_function".to_string(),
        name_path: "my_function".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 1,
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    assert!(validate_symbol_position(&sym, &lines).is_ok());
}

#[test]
fn editing_start_line_discards_walkback_when_no_block_comment_opener() {
    // Validate the safety net: if range_start_line points to a `*`-prefixed line
    // that is NOT inside a /** */ block (e.g. a Rust dereference or raw pointer),
    // the walk-back should be discarded and the original range_start_line returned.
    let sym = crate::lsp::SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("test.rs"),
        start_line: 3,
        end_line: 5,
        start_col: 0,
        children: vec![],
        range_start_line: Some(2), // points to `*mut u8` — NOT a doc comment
        detail: None,
    };
    let lines = vec![
        "use std::ptr;", // 0
        "",              // 1 — blank line stops heuristic walk-back
        "*mut u8",       // 2 ← range_start_line (hypothetical: `*`-prefixed non-comment)
        "fn foo() {",    // 3 ← start_line
        "    body",      // 4
        "}",             // 5
    ];
    // Walk-back reaches line 2, doesn't find /** or /*, so discards and returns 2
    assert_eq!(editing_start_line(&sym, &lines), 2);
}

// ── symbol_to_json body extraction: full-range (includes attributes) ─────

#[test]
fn symbol_to_json_body_includes_attributes_when_range_start_line_set() {
    let source = "#[test]\n/// A doc comment\nfn foo() {\n    body();\n}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 2, // fn keyword (0-indexed)
        end_line: 4,   // closing }
        start_col: 0,
        children: vec![],
        range_start_line: Some(0), // #[test] line
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    let body = json["body"].as_str().unwrap();
    assert!(
        body.contains("#[test]"),
        "body should include #[test] attribute; got:\n{body}"
    );
    assert!(
        body.contains("/// A doc comment"),
        "body should include doc comment; got:\n{body}"
    );
    assert!(
        body.contains("fn foo()"),
        "body should include fn declaration; got:\n{body}"
    );
}

#[test]
fn symbol_to_json_includes_body_start_line() {
    let source = "#[test]\nfn foo() {}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 1,
        end_line: 1,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    // body_start_line should be 1 (1-indexed, the #[test] line)
    assert_eq!(
        json["body_start_line"].as_u64(),
        Some(1),
        "body_start_line should be 1-indexed line where body begins (the attribute line)"
    );
}

#[test]
fn symbol_to_json_body_uses_heuristic_when_range_start_line_none() {
    let source = "#[test]\nfn foo() {\n    body();\n}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 1, // fn keyword
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: None, // tree-sitter / workspace/symbol path
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    let body = json["body"].as_str().unwrap();
    assert!(
        body.contains("#[test]"),
        "body should include #[test] via heuristic fallback; got:\n{body}"
    );
}

#[test]
fn symbol_to_json_body_start_line_equals_start_line_when_no_attributes() {
    let source = "fn foo() {\n    body();\n}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 0,
        end_line: 2,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0), // same as start_line — no attributes
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    assert_eq!(
        json["body_start_line"].as_u64(),
        Some(1),
        "body_start_line should equal start_line when no attributes"
    );
    assert_eq!(
        json["start_line"].as_u64(),
        Some(1),
        "start_line should be 1 (1-indexed)"
    );
}

#[test]
fn symbol_to_json_no_body_start_line_when_include_body_false() {
    let source = "#[test]\nfn foo() {}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 1,
        end_line: 1,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0),
        detail: None,
    };
    let json = symbol_to_json(&sym, false, Some(source), 0, false);
    assert!(
        json.get("body").is_none(),
        "body should not be present when include_body=false"
    );
    assert!(
        json.get("body_start_line").is_none(),
        "body_start_line should not be present when include_body=false"
    );
}

#[test]
fn symbol_to_json_body_includes_only_doc_comments() {
    // Symbol with only doc comments (no attributes)
    let source = "/// Doc line 1\n/// Doc line 2\nfn foo() {}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 2, // fn keyword
        end_line: 2,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0), // includes doc comments
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    let body = json["body"].as_str().unwrap();
    assert!(
        body.contains("/// Doc line 1"),
        "body should include first doc line; got:\n{body}"
    );
    assert!(
        body.contains("/// Doc line 2"),
        "body should include second doc line; got:\n{body}"
    );
    assert!(
        body.contains("fn foo()"),
        "body should include fn declaration; got:\n{body}"
    );
    assert_eq!(json["body_start_line"].as_u64(), Some(1));
    assert_eq!(json["start_line"].as_u64(), Some(3)); // fn keyword is line 3 (1-indexed)
}

#[test]
fn symbol_to_json_body_includes_multiline_attribute() {
    let source = "#[cfg(\n    target_os = \"linux\"\n)]\nfn foo() {}\n";
    let sym = crate::lsp::SymbolInfo {
        name: "foo".into(),
        name_path: "foo".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 3, // fn keyword
        end_line: 3,
        start_col: 0,
        children: vec![],
        range_start_line: Some(0), // includes #[cfg(
        detail: None,
    };
    let json = symbol_to_json(&sym, true, Some(source), 0, false);
    let body = json["body"].as_str().unwrap();
    assert!(
        body.contains("#[cfg("),
        "body should include multiline attribute opener; got:\n{body}"
    );
    assert!(
        body.contains("target_os"),
        "body should include attribute content; got:\n{body}"
    );
    assert!(
        body.contains(")]"),
        "body should include attribute closer; got:\n{body}"
    );
    assert_eq!(json["body_start_line"].as_u64(), Some(1));
}

#[test]
fn symbol_to_json_child_body_also_uses_full_range() {
    // Parent with a child that has its own attributes
    let source = "impl Foo {\n    #[test]\n    fn bar() {}\n}\n";
    let child = crate::lsp::SymbolInfo {
        name: "bar".into(),
        name_path: "Foo/bar".into(),
        kind: crate::lsp::SymbolKind::Function,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 2, // fn bar
        end_line: 2,
        start_col: 0,
        children: vec![],
        range_start_line: Some(1), // #[test]
        detail: None,
    };
    let parent = crate::lsp::SymbolInfo {
        name: "Foo".into(),
        name_path: "Foo".into(),
        kind: crate::lsp::SymbolKind::Struct,
        file: std::path::PathBuf::from("src/lib.rs"),
        start_line: 0,
        end_line: 3,
        start_col: 0,
        children: vec![child],
        range_start_line: Some(0),
        detail: None,
    };
    // depth=1 to include children
    let json = symbol_to_json(&parent, true, Some(source), 1, false);
    let child_body = json["children"][0]["body"].as_str().unwrap();
    assert!(
        child_body.contains("#[test]"),
        "child body should include its attribute; got:\n{child_body}"
    );
    assert!(
        child_body.contains("fn bar()"),
        "child body should include fn declaration; got:\n{child_body}"
    );
}

#[test]
fn find_insert_before_line_walks_past_multiline_attribute() {
    // #[cfg(
    //     target_os = "linux"
    // )]
    // fn foo() {}
    let lines = vec![
        "other code",
        "#[cfg(",
        "    target_os = \"linux\"",
        ")]",
        "fn foo() {}",
    ];
    assert_eq!(find_insert_before_line(&lines, 4), 1);
}

#[test]
fn find_insert_before_line_walks_past_nested_multiline_attributes() {
    // #[cfg(all(
    //     target_os = "linux",
    //     feature = "nightly"
    // ))]
    // #[inline]
    // fn foo() {}
    let lines = vec![
        "other code",
        "#[cfg(all(",
        "    target_os = \"linux\",",
        "    feature = \"nightly\"",
        "))]",
        "#[inline]",
        "fn foo() {}",
    ];
    assert_eq!(find_insert_before_line(&lines, 6), 1);
}

#[test]
fn find_insert_before_line_walks_past_python_multiline_decorator() {
    // @app.route(
    //     "/api/v1/users",
    //     methods=["GET"]
    // )
    // def get_users():
    let lines = vec![
        "other code",
        "@app.route(",
        "    \"/api/v1/users\",",
        "    methods=[\"GET\"]",
        ")",
        "def get_users():",
    ];
    // The `)` on line 4 is recognized as a bracket closer, triggering
    // upward scanning through the multi-line decorator.
    assert_eq!(find_insert_before_line(&lines, 5), 1);
}

#[test]
fn find_references_format_compact_shows_count() {
    use serde_json::json;
    let tool = References;
    let result = json!({
        "file_groups": [{"file": "a.rs", "count": 1, "items": [{"line": 10, "column": 0, "context": "foo()"}]}],
        "total": 1,
        "files": 1
    });
    let text = tool.format_compact(&result).unwrap();
    // Single-file result: render_grouped emits "file (count)\n  line  context"
    // The global "N references" header is suppressed for single-file results.
    assert!(text.contains("a.rs"), "got: {text}");
    assert!(text.contains("10"), "got: {text}");
}

#[tokio::test]
async fn references_returns_grouped_shape() {
    if !std::process::Command::new("rust-analyzer")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    }

    let dir = tempdir().unwrap();
    let lib_rs = dir.path().join("src").join("lib.rs");
    std::fs::create_dir_all(lib_rs.parent().unwrap()).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(
        &lib_rs,
        "pub fn greet() {}\nfn main() { greet(); greet(); }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let tool = crate::tools::symbol::references::References;
    let mut result_value: Option<Value> = None;
    for attempt in 0..10 {
        if attempt > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(500 * attempt)).await;
        }
        let value = match tool
            .call(json!({ "symbol": "greet", "path": "src/lib.rs" }), &ctx)
            .await
        {
            Ok(v) => v,
            Err(e) => {
                eprintln!("Skipping: LSP error: {}", e);
                return;
            }
        };
        if value["total"].as_u64().unwrap_or(0) >= 1 {
            result_value = Some(value);
            break;
        }
    }

    let result = match result_value {
        Some(v) => v,
        None => {
            eprintln!("Skipping: rust-analyzer did not index in time");
            return;
        }
    };

    let groups = result["file_groups"].as_array().unwrap();
    assert!(!groups.is_empty());
    for group in groups {
        assert!(group["file"].is_string());
        assert!(group["count"].is_u64());
        let items = group["items"].as_array().unwrap();
        for item in items {
            assert!(
                item.get("file").is_none(),
                "per-item file should be stripped: {item}"
            );
            assert!(item.get("line").is_some());
        }
    }
    assert!(result["total"].is_u64());
    assert!(result["files"].is_u64());
}

#[test]
fn rename_symbol_format_compact_shows_sites() {
    use serde_json::json;
    let tool = EditCode;
    let result = json!({ "total_edits": 5, "textual_match_count": 1, "files_changed": 2, "new_name": "bar" });
    let text = tool.format_compact(&result).unwrap();
    assert!(text.contains("bar"), "got: {text}");
}

#[test]
fn insert_code_format_compact_shows_location() {
    use serde_json::json;
    let tool = EditCode;
    let result = json!({ "status": "ok", "inserted_at_line": 42, "position": "after" });
    let text = tool.format_compact(&result).unwrap();
    assert!(text.contains("42"), "got: {text}");
}

#[test]
fn replace_symbol_format_compact_shows_range() {
    let tool = EditCode;
    let r = json!({ "status": "ok", "replaced_lines": "124-145" });
    let t = tool.format_compact(&r).unwrap();
    assert!(t.contains("L124"), "got: {t}");
}

#[test]
fn remove_symbol_format_compact_shows_range() {
    let tool = EditCode;
    let r = json!({ "status": "ok", "removed_lines": "201-215", "line_count": 14 });
    let t = tool.format_compact(&r).unwrap();
    assert!(t.contains("201"), "got: {t}");
    assert!(t.contains("14"), "got: {t}");
}

#[test]
fn symbol_at_requires_lsp() {
    let off = crate::tools::ToolCapabilities {
        has_lsp: false,
        has_embeddings: false,
        has_git_remote: false,
        has_libraries: false,
    };
    let on = crate::tools::ToolCapabilities {
        has_lsp: true,
        ..off
    };
    let t = SymbolAt;
    assert!(!t.availability(&off).is_available(&off));
    assert!(t.availability(&on).is_available(&on));
}

// --- format_goto_definition tests ---

#[test]
fn goto_single_project_definition() {
    let val = serde_json::json!({
        "definitions": [{
            "file": "src/tools/output.rs",
            "line": 35,
            "end_line": 41,
            "context": "pub struct OutputGuard {",
            "source": "project"
        }],
        "from": "symbol.rs:120"
    });
    let result = format_goto_definition(&val);
    assert_eq!(
        result,
        "src/tools/output.rs:35\n\n  pub struct OutputGuard {"
    );
}

#[test]
fn goto_single_external_definition() {
    let val = serde_json::json!({
        "definitions": [{
            "file": "/home/user/.rustup/toolchains/stable/lib.rs",
            "line": 100,
            "end_line": 110,
            "context": "pub enum Option<T> {",
            "source": "external"
        }],
        "from": "main.rs:5"
    });
    let result = format_goto_definition(&val);
    assert!(result.contains("(external)"));
    assert!(result.contains(":100"));
    assert!(result.contains("pub enum Option<T> {"));
}

#[test]
fn goto_multiple_definitions() {
    let val = serde_json::json!({
        "definitions": [
            { "file": "src/a.rs", "line": 10, "end_line": 15, "context": "fn foo()", "source": "project" },
            { "file": "src/b.rs", "line": 20, "end_line": 25, "context": "fn foo()", "source": "project" }
        ],
        "from": "main.rs:1"
    });
    let result = format_goto_definition(&val);
    assert!(result.starts_with("2 definitions"));
    assert!(result.contains("src/a.rs:10"));
    assert!(result.contains("src/b.rs:20"));
}

#[test]
fn goto_empty_definitions() {
    let val = serde_json::json!({ "definitions": [] });
    assert_eq!(format_goto_definition(&val), "");
}

#[test]
fn goto_empty_definitions_with_hint() {
    let val = serde_json::json!({
        "definitions": [],
        "from": "main.rs:42",
        "hint": "no definition resolvable at this position",
    });
    let out = format_goto_definition(&val);
    assert_eq!(out, "no definition resolvable at this position");
}

#[test]
fn goto_no_context() {
    let val = serde_json::json!({
        "definitions": [{
            "file": "src/lib.rs",
            "line": 1,
            "end_line": 1,
            "context": "",
            "source": "project"
        }],
        "from": "main.rs:1"
    });
    let result = format_goto_definition(&val);
    assert_eq!(result, "src/lib.rs:1");
}

#[test]
fn goto_multiple_with_external() {
    let val = serde_json::json!({
        "definitions": [
            { "file": "src/a.rs", "line": 10, "end_line": 10, "context": "fn foo()", "source": "project" },
            { "file": "/ext/lib.rs", "line": 20, "end_line": 20, "context": "fn foo()", "source": "lib:serde" }
        ],
        "from": "main.rs:1"
    });
    let result = format_goto_definition(&val);
    assert!(result.contains("2 definitions"));
    assert!(result.contains("src/a.rs:10"));
    assert!(result.contains("(lib:serde)"));
}

// --- format_hover tests ---

#[test]
fn hover_with_code_fence() {
    let val = serde_json::json!({
        "content": "```rust\npub struct OutputGuard {\n    mode: OutputMode,\n}\n```\n\nProgressive disclosure guard.",
        "location": "output.rs:35"
    });
    let result = format_hover(&val);
    assert!(result.starts_with("output.rs:35"));
    assert!(result.contains("  pub struct OutputGuard {"));
    assert!(result.contains("  Progressive disclosure guard."));
    assert!(!result.contains("```"));
}

#[test]
fn hover_plain_text_no_fences() {
    let val = serde_json::json!({
        "content": "Some plain documentation.",
        "location": "lib.rs:10"
    });
    let result = format_hover(&val);
    assert_eq!(result, "lib.rs:10\n\n  Some plain documentation.");
}

#[test]
fn hover_no_location() {
    let val = serde_json::json!({
        "content": "```rust\nfn main() {}\n```"
    });
    let result = format_hover(&val);
    assert!(!result.contains("```"));
    assert!(result.contains("  fn main() {}"));
}

#[test]
fn hover_empty_content() {
    let val = serde_json::json!({});
    assert_eq!(format_hover(&val), "");
}

#[test]
fn hover_null_content_with_hint_surfaces_hint() {
    let val = serde_json::json!({
        "content": null,
        "location": "lib.rs:10",
        "hint": "no hover info at this position",
    });
    let out = format_hover(&val);
    assert!(out.starts_with("lib.rs:10"));
    assert!(out.contains("no hover info at this position"));
}

#[test]
fn hover_null_content_hint_only() {
    let val = serde_json::json!({
        "content": null,
        "hint": "lone hint",
    });
    assert_eq!(format_hover(&val), "lone hint");
}

#[test]
fn hover_multiline_doc() {
    let val = serde_json::json!({
        "content": "```rust\nfn add(a: i32, b: i32) -> i32\n```\n\nAdds two numbers.\n\nReturns the sum.",
        "location": "math.rs:5"
    });
    let result = format_hover(&val);
    assert!(result.contains("  fn add(a: i32, b: i32) -> i32"));
    assert!(result.contains("  Adds two numbers."));
    assert!(result.contains("  Returns the sum."));
    assert!(!result.contains("```"));
}

// --- format_search_symbols tests ---

#[test]
fn symbols_no_body() {
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "OutputGuard", "symbol": "OutputGuard",
                "kind": "Struct", "file": "src/tools/output.rs",
                "start_line": 35, "end_line": 50
            },
            {
                "name": "cap_items", "symbol": "OutputGuard/cap_items",
                "kind": "Function", "file": "src/tools/output.rs",
                "start_line": 55, "end_line": 80
            }
        ],
        "total": 2
    });
    let result = format_search_symbols(&val);
    // Single-file: header is the file path, no global "N matches" line
    assert!(result.starts_with("src/tools/output.rs (2)\n"));
    assert!(result.contains("Struct"));
    assert!(result.contains("Function"));
    assert!(result.contains("OutputGuard"));
    assert!(result.contains("OutputGuard/cap_items"));
    // Rows show range only, not full path
    assert!(result.contains("35-50"));
    assert!(result.contains("55-80"));
    assert!(
        !result.contains("src/tools/output.rs:35-50"),
        "file path must not repeat in rows"
    );
}

#[test]
fn symbols_with_body() {
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "cap_items", "symbol": "OutputGuard/cap_items",
                "kind": "Function", "file": "src/tools/output.rs",
                "start_line": 55, "end_line": 80,
                "body": "pub fn cap_items(&self) -> Option<OverflowInfo> {\n    // impl\n}"
            }
        ],
        "total": 1
    });
    let result = format_search_symbols(&val);
    // Single-file: header is the file path, no global "1 match" line
    assert!(result.starts_with("src/tools/output.rs (1)\n"));
    assert!(result.contains("Function"));
    assert!(result.contains("OutputGuard/cap_items"));
    assert!(result.contains("      pub fn cap_items(&self) -> Option<OverflowInfo> {"));
    assert!(result.contains("      // impl"));
    assert!(result.contains("      }"));
}

#[test]
fn symbols_with_long_body_inlines_full_content() {
    // Bodies > 500 bytes must be inlined verbatim in compact text form.
    // Path 2 (`OutputForm::Text`, JSON ≤ 10 KB) returns this text directly with no
    // buffering — eliding the body here strands the agent because no `@tool_*` ref
    // is created for `json_path` to address. Path 1 (buffered, JSON > 10 KB)
    // truncates this summary at `COMPACT_SUMMARY_HARD_MAX_BYTES` with a
    // `… (truncated)` marker AND emits a `read_file("@tool_xxx", json_path=...)`
    // hint via call_content — so the truncation is recoverable in the buffered
    // case while the inline case stays self-sufficient.
    // Regression for docs/issues/2026-05-18-symbols-body-hint-unreachable.md.
    // (Test name kept for git history; previous behavior was the bug.)
    let long_body = "fun convert() {\n".to_string() + &"    val x = 1\n".repeat(50) + "}";
    assert!(long_body.len() > 500, "test body should be > 500 bytes");
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "convert", "symbol": "Stage1ToStage2Converter/convert",
                "kind": "Method", "file": "src/Converter.kt",
                "start_line": 160, "end_line": 490,
                "body": long_body
            }
        ],
        "total": 1
    });
    let result = format_search_symbols(&val);
    // Body lines must appear inline — the agent can read them without a json_path hop.
    assert!(
        result.contains("      fun convert() {"),
        "expected first body line inlined, got:\n{result}"
    );
    assert!(
        result.contains("      val x = 1"),
        "expected repeated body content inlined, got:\n{result}"
    );
    // The misleading "use json_path" elision hint must be gone.
    assert!(
        !result.contains("use json_path"),
        "compact text must not reference json_path — the outer call_content hint owns that, \
         got:\n{result}"
    );
}

#[test]
fn symbols_with_overflow() {
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "foo", "symbol": "foo",
                "kind": "Function", "file": "src/a.rs",
                "start_line": 10, "end_line": 10
            }
        ],
        "total": 100,
        "overflow": {
            "shown": 20, "total": 100,
            "hint": "narrow with path=",
            "by_file": [["src/a.rs", 50], ["src/b.rs", 30]]
        }
    });
    let result = format_search_symbols(&val);
    // Overflow hint line is appended regardless of single/multi-file layout
    assert!(result.contains("20 of 100"), "got:\n{result}");
    assert!(result.contains("narrow with path="), "got:\n{result}");
    // Symbol itself is rendered
    assert!(result.contains("foo"), "got:\n{result}");
}

#[test]
fn symbols_empty() {
    let val = serde_json::json!({
        "symbols": [],
        "total": 0
    });
    assert_eq!(format_search_symbols(&val), "0 matches");
}

#[test]
fn symbols_missing_symbols_key() {
    let val = serde_json::json!({});
    assert_eq!(format_search_symbols(&val), "");
}

#[test]
fn symbols_alignment() {
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "Foo", "symbol": "Foo",
                "kind": "Struct", "file": "src/a.rs",
                "start_line": 1, "end_line": 5
            },
            {
                "name": "bar_baz", "symbol": "bar_baz",
                "kind": "Function", "file": "src/very/long/path.rs",
                "start_line": 100, "end_line": 200
            }
        ],
        "total": 2
    });
    let result = format_search_symbols(&val);
    // Multi-file: file paths appear as group headers, not embedded in rows
    assert!(result.contains("src/a.rs (1)"), "got:\n{result}");
    assert!(
        result.contains("src/very/long/path.rs (1)"),
        "got:\n{result}"
    );
    assert!(result.contains("Struct"));
    assert!(result.contains("Function"));
    // Ranges appear in the rows
    assert!(result.contains("1-5"));
    assert!(result.contains("100-200"));
    // File paths must not repeat inside rows
    assert!(
        !result.contains("src/a.rs:1-5"),
        "file path must not be in rows: {result}"
    );
    assert!(
        !result.contains("src/very/long/path.rs:100-200"),
        "file path must not be in rows: {result}"
    );
}

#[test]
fn symbols_single_line_location() {
    let val = serde_json::json!({
        "symbols": [
            {
                "name": "X", "symbol": "X",
                "kind": "Constant", "file": "src/lib.rs",
                "start_line": 42, "end_line": 42
            }
        ],
        "total": 1
    });
    let result = format_search_symbols(&val);
    // Single-file: file is in the group header
    assert!(result.contains("src/lib.rs (1)"), "got:\n{result}");
    // Row shows the single line number without a range
    assert!(result.contains("42"));
    assert!(!result.contains("42-42"));
}

// --- format_overview_symbols tests ---

#[test]
fn symbols_overview_file_mode() {
    let val = serde_json::json!({
        "file": "src/tools/output.rs",
        "symbols": [
            {
                "name": "OutputMode", "symbol": "OutputMode",
                "kind": "Enum", "start_line": 10, "end_line": 15,
                "children": [
                    { "name": "Exploring", "kind": "EnumMember", "start_line": 11, "end_line": 11 },
                    { "name": "Focused", "kind": "EnumMember", "start_line": 12, "end_line": 12 }
                ]
            },
            {
                "name": "OutputGuard", "symbol": "OutputGuard",
                "kind": "Struct", "start_line": 35, "end_line": 50
            }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(result.starts_with("src/tools/output.rs — 2 symbols\n"));
    assert!(result.contains("Enum"));
    assert!(result.contains("OutputMode"));
    assert!(result.contains("L10-15"));
    assert!(result.contains("Exploring"));
    assert!(result.contains("L11"));
    assert!(result.contains("Focused"));
    assert!(result.contains("L12"));
    assert!(result.contains("Struct"));
    assert!(result.contains("OutputGuard"));
    assert!(result.contains("L35-50"));
    assert!(!result.contains("EnumMember"));
}

#[test]
fn symbols_overview_directory_mode() {
    let val = serde_json::json!({
        "directory": "src/tools",
        "files": [
            {
                "file": "src/tools/ast.rs",
                "symbols": [
                    { "name": "ListFunctions", "symbol": "ListFunctions", "kind": "Struct", "start_line": 10, "end_line": 20 }
                ]
            },
            {
                "file": "src/tools/config.rs",
                "symbols": [
                    { "name": "GetConfig", "symbol": "GetConfig", "kind": "Struct", "start_line": 5, "end_line": 15 },
                    { "name": "ActivateProject", "symbol": "ActivateProject", "kind": "Struct", "start_line": 20, "end_line": 30 }
                ]
            }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(result.starts_with("src/tools\n"));
    assert!(result.contains("src/tools/ast.rs — 1 symbol\n"));
    assert!(result.contains("src/tools/config.rs — 2 symbols\n"));
    assert!(result.contains("ListFunctions"));
    assert!(result.contains("GetConfig"));
    assert!(result.contains("ActivateProject"));
}

#[test]
fn symbols_overview_pattern_mode() {
    let val = serde_json::json!({
        "pattern": "src/**/*.rs",
        "files": [
            {
                "file": "src/main.rs",
                "symbols": [
                    { "name": "main", "symbol": "main", "kind": "Function", "start_line": 1, "end_line": 10 }
                ]
            }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(result.starts_with("src/**/*.rs\n"));
    assert!(result.contains("src/main.rs — 1 symbol\n"));
    assert!(result.contains("main"));
}

#[test]
fn symbols_overview_empty_file() {
    let val = serde_json::json!({
        "file": "src/empty.rs",
        "symbols": []
    });
    let result = format_overview_symbols(&val);
    assert!(result.contains("0 symbols"));
}

#[test]
fn symbols_overview_empty_directory() {
    let val = serde_json::json!({
        "directory": "src/empty",
        "files": []
    });
    let result = format_overview_symbols(&val);
    assert_eq!(result, "src/empty — 0 symbols");
}

#[tokio::test]
async fn symbols_overview_falls_back_to_treesitter_when_lsp_returns_empty() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::Symbols;

    // BUG-054 regression: rust-analyzer can return Ok(vec![]) during cold-start
    // indexing. The single-file branch of `list_overview` must fall over to
    // tree-sitter so the agent gets a usable result instead of empty `[]`.
    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("modlike.rs");
    std::fs::write(&file, "pub mod alpha;\npub mod beta;\nfn helper() {}\n").unwrap();

    // No symbols registered for the path → MockLspClient returns Ok(empty Vec),
    // mirroring rust-analyzer's cold-start behavior.
    let mock = MockLspClient::new();
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = Symbols
        .call(json!({"path": "src/modlike.rs"}), &ctx)
        .await
        .expect("call must succeed");

    let syms = result["symbols"].as_array().expect("symbols array");
    assert!(
        !syms.is_empty(),
        "expected tree-sitter fallback to populate symbols when LSP returns empty for non-empty file, got: {result}"
    );
    let names: Vec<&str> = syms.iter().filter_map(|s| s["name"].as_str()).collect();
    assert!(
        names.contains(&"alpha") || names.contains(&"helper"),
        "expected at least one of the source symbols, got names: {names:?}"
    );
}

#[tokio::test]
async fn symbols_overview_returns_empty_for_empty_file_via_treesitter() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::Symbols;

    // BUG-054 negative case: an actually-empty file should NOT trigger the
    // tree-sitter fallback (would still return empty), and must not regress
    // into a hang or error. Asserts the fallback is gated on file content.
    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("blank.rs");
    std::fs::write(&file, "// just a comment\n").unwrap();

    let mock = MockLspClient::new();
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = Symbols
        .call(json!({"path": "src/blank.rs"}), &ctx)
        .await
        .expect("call must succeed");

    let syms = result["symbols"].as_array().expect("symbols array");
    assert!(
        syms.is_empty(),
        "comment-only file should return empty symbols (no fallback needed), got: {result}"
    );
}

#[test]
fn symbols_overview_with_overflow() {
    let val = serde_json::json!({
        "directory": "src",
        "files": [
            {
                "file": "src/a.rs",
                "symbols": [
                    { "name": "Foo", "symbol": "Foo", "kind": "Struct", "start_line": 1, "end_line": 5 }
                ]
            }
        ],
        "overflow": { "shown": 10, "total": 50, "hint": "Narrow with a more specific glob or file path" }
    });
    let result = format_overview_symbols(&val);
    assert!(result.contains("10 of 50"));
    assert!(result.contains("Narrow with a more specific glob"));
}

#[test]
fn symbols_overview_children_with_fields() {
    let val = serde_json::json!({
        "file": "src/model.rs",
        "symbols": [
            {
                "name": "Config", "symbol": "Config",
                "kind": "Struct", "start_line": 1, "end_line": 10,
                "children": [
                    { "name": "port", "kind": "Field", "start_line": 2, "end_line": 2 },
                    { "name": "host", "kind": "Field", "start_line": 3, "end_line": 3 }
                ]
            }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(!result.contains("Field"));
    assert!(result.contains("port"));
    assert!(result.contains("host"));
    assert!(result.contains("L2"));
    assert!(result.contains("L3"));
}

#[test]
fn symbols_overview_children_with_methods() {
    let val = serde_json::json!({
        "file": "src/service.rs",
        "symbols": [
            {
                "name": "Server", "symbol": "Server",
                "kind": "Struct", "start_line": 1, "end_line": 50,
                "children": [
                    { "name": "new", "kind": "Function", "start_line": 5, "end_line": 10 },
                    { "name": "run", "kind": "Function", "start_line": 12, "end_line": 40 }
                ]
            }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(result.contains("Function  new"));
    assert!(result.contains("Function  run"));
}

#[test]
fn symbols_overview_missing_symbols_key() {
    let val = serde_json::json!({});
    assert_eq!(format_overview_symbols(&val), "");
}

#[test]
fn symbols_overview_singular_symbol_word() {
    let val = serde_json::json!({
        "file": "src/single.rs",
        "symbols": [
            { "name": "main", "symbol": "main", "kind": "Function", "start_line": 1, "end_line": 5 }
        ]
    });
    let result = format_overview_symbols(&val);
    assert!(result.contains("1 symbol\n"));
    assert!(!result.contains("1 symbols"));
}

// --- references format_compact tests ---

#[test]
fn find_references_basic() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    let tool = References;
    let result = serde_json::json!({
        "file_groups": [
            {"file": "src/foo.rs", "count": 2, "items": [
                {"line": 10, "column": 0, "context": ""},
                {"line": 30, "column": 0, "context": ""}
            ]},
            {"file": "src/bar.rs", "count": 1, "items": [
                {"line": 20, "column": 0, "context": ""}
            ]}
        ],
        "total": 3,
        "files": 2
    });
    let text = tool.format_compact(&result).unwrap();
    assert!(text.contains("3"), "should mention count");
    assert!(
        text.contains("references") || text.contains("refs"),
        "should say refs or reference(s)"
    );
}

#[test]
fn references_declares_output_form_text() {
    // Pinned wire contract: small `references` results render as the compact
    // ripgrep-style text via Tool::call_content (not pretty JSON). Full
    // integration through call_content needs an LSP fixture; asserting the
    // declared OutputForm is the cheap, durable contract check.
    use crate::tools::symbol::references::References;
    use crate::tools::{OutputForm, Tool};
    assert_eq!(References.output_form(), OutputForm::Text);
}

#[test]
fn references_completeness_hint_warns_only_when_calls_exceed_refs() {
    use crate::tools::symbol::references::references_completeness_hint;
    // The pathological case: references undercounts (3) vs call sites (17).
    assert!(references_completeness_hint(3, 17).is_some());
    // Worst silent failure: references returns 0 but callers exist.
    assert!(references_completeness_hint(0, 5).is_some());
    // references complete: it counts non-call refs too, so refs >= call sites.
    assert!(references_completeness_hint(198, 109).is_none());
    assert!(references_completeness_hint(12, 11).is_none());
    // Equal counts are not proof of incompleteness.
    assert!(references_completeness_hint(5, 5).is_none());
}
#[test]
fn contains_word_respects_identifier_boundaries() {
    use crate::tools::symbol::references::contains_word;
    assert!(contains_word("a = getLabel();", "getLabel"));
    assert!(contains_word("getLabel", "getLabel"));
    assert!(!contains_word("getLabelExtra()", "getLabel"));
    assert!(!contains_word("myGetLabel()", "getLabel"));
    assert!(!contains_word("", "getLabel"));
}

#[test]
fn corroborate_zero_references_finds_callers_via_text_scan() {
    // BUG 2026-06-09: the LSP-independent corroboration for a false 0-callers
    // result must find callers in OTHER files, exclude the definition file, and
    // honour word boundaries (not match a superstring).
    use crate::tools::symbol::references::corroborate_zero_references;
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    std::fs::write(root.join("def.rs"), "pub fn getStudentGroupLabel() {}").unwrap();
    std::fs::write(root.join("a.rs"), "fn x() { getStudentGroupLabel(); }").unwrap();
    std::fs::write(
        root.join("b.rs"),
        "fn y() { let _ = getStudentGroupLabel; }",
    )
    .unwrap();
    std::fs::write(root.join("c.rs"), "fn z() { getStudentGroupLabelExtra(); }").unwrap();
    let def = root.join("def.rs");
    let hits = corroborate_zero_references(root, &def, "getStudentGroupLabel", "rust");
    let names: std::collections::HashSet<String> = hits
        .iter()
        .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
        .collect();
    assert!(
        names.contains("a.rs"),
        "should find caller a.rs; got {names:?}"
    );
    assert!(
        names.contains("b.rs"),
        "should find caller b.rs; got {names:?}"
    );
    assert!(
        !names.contains("def.rs"),
        "must exclude the definition file"
    );
    assert!(
        !names.contains("c.rs"),
        "must not match superstring; got {names:?}"
    );
}

#[test]
fn references_format_compact_appends_completeness_warning() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    let result = serde_json::json!({
        "file_groups": [
            {"file": "src/a.rs", "count": 1, "items": [{"line": 1, "column": 0, "context": ""}]}
        ],
        "total": 1,
        "files": 1,
        "completeness_warning": "references found 1, but call-hierarchy found 9 call sites — use call_graph"
    });
    let text = References.format_compact(&result).unwrap();
    assert!(
        text.contains("call-hierarchy found 9"),
        "warning must render in normal branch: {text}"
    );
}

#[test]
fn references_format_compact_appends_warning_on_zero_refs() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    // The dangerous case: references returns 0 but there ARE callers — the
    // warning must still surface so the 0 isn't taken at face value.
    let result = serde_json::json!({
        "file_groups": [],
        "total": 0,
        "files": 0,
        "completeness_warning": "references found 0, but call-hierarchy found 4 call sites — use call_graph"
    });
    let text = References.format_compact(&result).unwrap();
    assert!(text.contains('0'), "should still say 0 references: {text}");
    assert!(
        text.contains("call-hierarchy found 4"),
        "warning must render even on zero refs: {text}"
    );
}

#[test]
fn symbols_declares_output_form_text() {
    // Pinned wire contract: small `symbols` results render via the compact
    // text form (file overview / search result tree), not pretty JSON.
    use crate::tools::symbol::symbols::Symbols;
    use crate::tools::{OutputForm, Tool};
    assert_eq!(Symbols.output_form(), OutputForm::Text);
}

#[test]
fn symbol_at_declares_output_form_text() {
    // Pinned wire contract: small `symbol_at` results (def + hover) render via
    // the compact text form, not pretty JSON. format_compact is lossless
    // (full def context + hover content), so the small path is safe to flip.
    use crate::tools::symbol::symbol_at::SymbolAt;
    use crate::tools::{OutputForm, Tool};
    assert_eq!(SymbolAt.output_form(), OutputForm::Text);
}

#[test]
fn symbol_at_format_compact_preserves_def_and_hover() {
    use crate::tools::symbol::symbol_at::SymbolAt;
    use crate::tools::Tool;
    use serde_json::json;
    let result = json!({
        "def": { "definitions": [{ "file": "src/a.rs", "line": 42, "context": "fn alpha()" }] },
        "hover": { "content": "fn alpha() -> i32", "location": "src/a.rs:42" },
    });
    let text = SymbolAt
        .format_compact(&result)
        .expect("def+hover should render");
    assert!(text.contains("src/a.rs:42"), "def location lost: {text}");
    assert!(text.contains("fn alpha()"), "def context lost: {text}");
    assert!(
        text.contains("fn alpha() -> i32"),
        "hover content lost: {text}"
    );
}

#[test]
fn find_references_empty() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    let tool = References;
    let result = serde_json::json!({ "file_groups": [], "total": 0, "files": 0 });
    let text = tool.format_compact(&result).unwrap();
    assert!(text.contains("0"), "should mention zero, got: {}", text);
}

#[test]
fn format_find_references_shows_locations() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    let tool = References;
    let result = serde_json::json!({
        "total": 8,
        "files": 5,
        "file_groups": [
            {"file": "src/tools/symbol.rs", "count": 2, "items": [
                {"line": 142, "column": 0, "context": ""},
                {"line": 198, "column": 0, "context": ""}
            ]},
            {"file": "src/server.rs", "count": 1, "items": [
                {"line": 87, "column": 0, "context": ""}
            ]},
            {"file": "src/agent.rs", "count": 1, "items": [
                {"line": 210, "column": 0, "context": ""}
            ]},
            {"file": "src/main.rs", "count": 1, "items": [
                {"line": 45, "column": 0, "context": ""}
            ]},
            {"file": "src/config.rs", "count": 1, "items": [
                {"line": 12, "column": 0, "context": ""}
            ]}
        ]
    });
    let out = tool.format_compact(&result).unwrap();
    // render_grouped emits "N references in F files\n\nfile (count)\n  line  context"
    assert!(out.contains("8"), "should show total");
    assert!(out.contains("references"), "should use references noun");
    assert!(out.contains("src/tools/symbol.rs"), "should show file");
    assert!(out.contains("142"), "should show line numbers");
    assert!(out.contains("src/server.rs"), "should show other files");
    assert!(
        out.contains("src/config.rs"),
        "format_compact shows all refs, no cap"
    );
}

#[test]
fn format_find_references_five_or_fewer_no_trailer() {
    use crate::tools::symbol::references::References;
    use crate::tools::Tool;
    let tool = References;
    let result = serde_json::json!({
        "total": 3,
        "files": 3,
        "file_groups": [
            {"file": "src/a.rs", "count": 1, "items": [{"line": 1, "column": 0, "context": ""}]},
            {"file": "src/b.rs", "count": 1, "items": [{"line": 2, "column": 0, "context": ""}]},
            {"file": "src/c.rs", "count": 1, "items": [{"line": 3, "column": 0, "context": ""}]}
        ]
    });
    let out = tool.format_compact(&result).unwrap();
    // render_grouped emits file headers; all files shown, no truncation trailer
    assert!(out.contains("src/a.rs"), "should show first file");
    assert!(out.contains("src/b.rs"), "should show second file");
    assert!(out.contains("src/c.rs"), "should show third file");
    assert!(!out.contains("more"), "no trailer when all refs fit");
}

#[tokio::test]
async fn symbols_falls_back_to_document_symbols_on_bad_workspace_range() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider, SymbolInfo, SymbolKind};

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(
        &file,
        "fn helper(x: i32) -> i32 {\n    let y = x + 1;\n    y * 2\n}\n",
    )
    .unwrap();

    // workspace/symbol returns degenerate range (start == end)
    let degenerate = SymbolInfo {
        name: "helper".to_string(),
        name_path: "helper".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0,
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    // document_symbols returns correct range
    let correct = SymbolInfo {
        name: "helper".to_string(),
        name_path: "helper".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 3,
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    let mock = MockLspClient::new()
        .with_workspace_symbols(vec![degenerate])
        .with_symbols(&file, vec![correct]);
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = Symbols
        .call(
            json!({
                "query": "helper",
                "include_body": true,
            }),
            &ctx,
        )
        .await;

    let val = result.expect("symbols should recover via document_symbols fallback");
    let symbols = val["symbols"].as_array().expect("symbols array");
    assert_eq!(symbols.len(), 1, "should find exactly one symbol");

    let body = symbols[0]["body"].as_str().expect("body should be present");
    assert!(
        body.contains("let y = x + 1"),
        "body should contain function contents; got: {body}"
    );
}

#[tokio::test]
async fn symbol_at_def_uses_col_param_over_identifier() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    // line 0: `fn helper(x: i32) {}` — identifier `helper` at byte col 3
    std::fs::write(&file, "fn helper(x: i32) {}\n").unwrap();

    // Register definition keyed at (line=0, col=3) only.
    // Caller passes col=4 (1-indexed) → 3 (0-indexed) plus a bogus identifier
    // that doesn't exist on the line. With col-priority, identifier is ignored.
    let target = lsp_types::Location {
        uri: url::Url::from_file_path(&file)
            .unwrap()
            .as_str()
            .parse()
            .unwrap(),
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 5,
                character: 0,
            },
            end: lsp_types::Position {
                line: 5,
                character: 6,
            },
        },
    };
    let mock = MockLspClient::new().with_definitions(0, 3, vec![target]);
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = SymbolAt
        .call(
            json!({
                "path": "src/lib.rs",
                "line": 1,
                "col": 4,
                "identifier": "DOES_NOT_EXIST_ON_LINE",
                "fields": ["def"],
            }),
            &ctx,
        )
        .await
        .expect("col should win over identifier and resolve");
    let defs = result["def"]["definitions"].as_array().unwrap();
    assert_eq!(defs.len(), 1, "exactly one definition expected");
    assert_eq!(defs[0]["line"].as_u64(), Some(6)); // 5 + 1 (1-indexed)
}

#[tokio::test]
async fn symbol_at_hover_returns_ok_with_null_content_when_lsp_empty() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(&file, "fn x() {}\n").unwrap();

    // MockLspClient::hover always returns Ok(None) — exercises empty-result path.
    let mock = MockLspClient::new();
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = SymbolAt
        .call(
            json!({
                "path": "src/lib.rs",
                "line": 1,
                "col": 4,
                "fields": ["hover"],
            }),
            &ctx,
        )
        .await
        .expect("empty hover must be Ok, not Err (no misclassification)");
    assert!(
        result["hover"]["content"].is_null(),
        "content should be null on empty"
    );
    assert!(
        result["hover"]["hint"].as_str().is_some(),
        "hint should be present to guide caller"
    );
}

#[tokio::test]
async fn symbol_at_hover_col_zero_rejected() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(&file, "fn x() {}\n").unwrap();

    let lsp = MockLspProvider::with_client(MockLspClient::new());
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let err = SymbolAt
        .call(
            json!({"path": "src/lib.rs", "line": 1, "col": 0, "fields": ["hover"]}),
            &ctx,
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("'col' must be >= 1"), "got: {err}");
}

#[tokio::test]
async fn symbol_at_hover_retries_once_on_mux_disconnect() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(&file, "fn x() {}\n").unwrap();

    // First hover errors with the magic mux-disconnect string; helper retries
    // and the second call succeeds with real content.
    let mock = MockLspClient::new().with_hover_responses(vec![
        Err(anyhow::anyhow!("Mux connection lost")),
        Ok(Some("```rust\nfn x()\n```".to_string())),
    ]);
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = SymbolAt
        .call(
            json!({"path": "src/lib.rs", "line": 1, "col": 4, "fields": ["hover"]}),
            &ctx,
        )
        .await
        .expect("transient mux disconnect should be retried, not surfaced");
    assert_eq!(
        result["hover"]["content"].as_str(),
        Some("```rust\nfn x()\n```"),
        "second-attempt content should be returned"
    );
}

#[tokio::test]
async fn symbol_at_hover_does_not_retry_non_disconnect_errors() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(&file, "fn x() {}\n").unwrap();

    let mock = MockLspClient::new()
        .with_hover_responses(vec![Err(anyhow::anyhow!("some unrelated LSP error"))]);
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let err = SymbolAt
        .call(
            json!({"path": "src/lib.rs", "line": 1, "col": 4, "fields": ["hover"]}),
            &ctx,
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("some unrelated LSP error"),
        "non-disconnect errors must surface immediately, got: {err}"
    );
}

#[tokio::test]
async fn symbol_at_returns_both_fields_by_default() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider};
    use crate::tools::symbol::SymbolAt;

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(&file, "fn helper(x: i32) {}\n").unwrap();

    // Hover returns Some(...), goto_definition returns one location.
    let target = lsp_types::Location {
        uri: url::Url::from_file_path(&file)
            .unwrap()
            .as_str()
            .parse()
            .unwrap(),
        range: lsp_types::Range {
            start: lsp_types::Position {
                line: 0,
                character: 3,
            },
            end: lsp_types::Position {
                line: 0,
                character: 9,
            },
        },
    };
    let mock = MockLspClient::new()
        .with_definitions(0, 3, vec![target])
        .with_hover_responses(vec![Ok(Some(
            "```rust\nfn helper(x: i32)\n```".to_string(),
        ))]);
    let lsp = MockLspProvider::with_client(mock);

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = SymbolAt
        .call(json!({"path": "src/lib.rs", "line": 1, "col": 4}), &ctx)
        .await
        .expect("symbol_at with default fields should succeed");
    assert!(
        result.get("def").is_some(),
        "default fields should include def; got: {result:?}"
    );
    assert!(
        result.get("hover").is_some(),
        "default fields should include hover; got: {result:?}"
    );
}

#[test]
fn find_matching_symbol_finds_top_level() {
    use crate::lsp::SymbolKind;
    let symbols = vec![SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: SymbolKind::Function,
        file: PathBuf::from("lib.rs"),
        start_line: 10,
        end_line: 20,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    }];
    let result = find_matching_symbol(&symbols, "foo", 10);
    assert!(result.is_some());
    assert_eq!(result.unwrap().end_line, 20);
}

#[test]
fn find_matching_symbol_finds_nested_child() {
    use crate::lsp::SymbolKind;
    let child = SymbolInfo {
        name: "bar".to_string(),
        name_path: "Foo/bar".to_string(),
        kind: SymbolKind::Function,
        file: PathBuf::from("lib.rs"),
        start_line: 15,
        end_line: 18,
        start_col: 4,
        children: vec![],
        range_start_line: None,
        detail: None,
    };
    let parent = SymbolInfo {
        name: "Foo".to_string(),
        name_path: "Foo".to_string(),
        kind: SymbolKind::Struct,
        file: PathBuf::from("lib.rs"),
        start_line: 10,
        end_line: 20,
        start_col: 0,
        children: vec![child],
        range_start_line: None,
        detail: None,
    };
    let result = find_matching_symbol(&[parent], "bar", 15);
    assert!(result.is_some());
    assert_eq!(result.unwrap().end_line, 18);
}

#[test]
fn find_matching_symbol_returns_none_on_name_mismatch() {
    use crate::lsp::SymbolKind;
    let symbols = vec![SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: SymbolKind::Function,
        file: PathBuf::from("lib.rs"),
        start_line: 10,
        end_line: 20,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    }];
    let result = find_matching_symbol(&symbols, "bar", 10);
    assert!(result.is_none());
}

#[test]
fn find_matching_symbol_returns_none_when_line_too_far() {
    use crate::lsp::SymbolKind;
    let symbols = vec![SymbolInfo {
        name: "foo".to_string(),
        name_path: "foo".to_string(),
        kind: SymbolKind::Function,
        file: PathBuf::from("lib.rs"),
        start_line: 10,
        end_line: 20,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    }];
    // lsp_start=13 → abs_diff(10, 13) = 3 > 1 → no match
    let result = find_matching_symbol(&symbols, "foo", 13);
    assert!(result.is_none());
}

#[cfg_attr(
    target_os = "windows",
    ignore = "Windows path/canon shape differs from Linux; needs investigation. See docs/issues/2026-05-24-ci-windows-test-portability-rot.md"
)]
#[cfg_attr(
    target_os = "macos",
    ignore = "fallback succeeds on macOS where Linux fails — needs investigation, see docs/issues/2026-05-24-ci-macos-tempdir-canonicalization.md"
)]
#[tokio::test]
async fn symbols_propagates_error_when_fallback_also_fails() {
    use crate::lsp::{mock::MockLspClient, mock::MockLspProvider, SymbolInfo, SymbolKind};

    let dir = tempfile::tempdir().unwrap();
    let src_dir = dir.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    let file = src_dir.join("lib.rs");
    std::fs::write(
        &file,
        "fn helper(x: i32) -> i32 {\n    let y = x + 1;\n    y * 2\n}\n",
    )
    .unwrap();

    // workspace/symbol returns degenerate range
    let degenerate = SymbolInfo {
        name: "helper".to_string(),
        name_path: "helper".to_string(),
        kind: SymbolKind::Function,
        file: file.clone(),
        start_line: 0,
        end_line: 0,
        start_col: 3,
        children: vec![],
        range_start_line: None,
        detail: None,
    };

    // document_symbols returns NOTHING — fallback will fail
    let mock = MockLspClient::new().with_workspace_symbols(vec![degenerate]);
    // Note: NOT calling .with_symbols() — document_symbols will return empty vec
    let lsp = MockLspProvider::with_client(mock);

    // Use the same ToolContext setup pattern as the other test
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = Symbols
        .call(
            json!({
                "query": "helper",
                "include_body": true,
            }),
            &ctx,
        )
        .await;

    // Should fail with the original RecoverableError
    let err = result.expect_err("should propagate error when fallback fails");
    let msg = err.to_string();
    assert!(
        msg.contains("suspicious range"),
        "error should mention suspicious range; got: {msg}"
    );
}

// ── resolve_library_roots ────────────────────────────────────────────────

#[tokio::test]
async fn resolve_library_roots_empty_when_no_libraries() {
    let dir = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let roots = resolve_library_roots(&crate::library::scope::Scope::Libraries, &agent)
        .await
        .unwrap();
    assert!(roots.is_empty());
}

#[tokio::test]
async fn resolve_library_roots_returns_registered_libraries() {
    let dir = tempdir().unwrap();
    let lib_dir = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "mylib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }
    let roots = resolve_library_roots(&crate::library::scope::Scope::Libraries, &agent)
        .await
        .unwrap();
    assert_eq!(roots.len(), 1);
    assert_eq!(roots[0].0, "mylib");
    assert_eq!(roots[0].1, lib_dir.path().to_path_buf());
}

#[tokio::test]
async fn resolve_library_roots_filters_by_name() {
    let dir = tempdir().unwrap();
    let lib1 = tempdir().unwrap();
    let lib2 = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "alpha".to_string(),
            lib1.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
        project.library_registry.register(
            "beta".to_string(),
            lib2.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }
    let roots = resolve_library_roots(
        &crate::library::scope::Scope::Library("alpha".to_string()),
        &agent,
    )
    .await
    .unwrap();
    assert_eq!(roots.len(), 1);
    assert_eq!(roots[0].0, "alpha");
}

#[tokio::test]
async fn resolve_library_roots_project_scope_returns_empty() {
    let dir = tempdir().unwrap();
    let lib_dir = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "mylib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }
    let roots = resolve_library_roots(&crate::library::scope::Scope::Project, &agent)
        .await
        .unwrap();
    assert!(roots.is_empty());
}

#[tokio::test]
async fn resolve_library_roots_all_scope_returns_all() {
    let dir = tempdir().unwrap();
    let lib1 = tempdir().unwrap();
    let lib2 = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "alpha".to_string(),
            lib1.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
        project.library_registry.register(
            "beta".to_string(),
            lib2.path().to_path_buf(),
            "python".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }
    let roots = resolve_library_roots(&crate::library::scope::Scope::All, &agent)
        .await
        .unwrap();
    assert_eq!(roots.len(), 2);
}

#[tokio::test]
async fn resolve_library_roots_excludes_source_unavailable() {
    let dir = tempdir().unwrap();
    let lib_dir = tempdir().unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "available".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
        project.library_registry.register(
            "unavailable".to_string(),
            PathBuf::new(),
            "java".to_string(),
            crate::library::registry::DiscoveryMethod::ManifestScan,
            false,
        );
    }
    // Explicit library scope for unavailable lib should error
    let result = resolve_library_roots(
        &crate::library::scope::Scope::Library("unavailable".to_string()),
        &agent,
    )
    .await;
    assert!(
        result.is_err(),
        "should return error for source-unavailable library"
    );
    let err = result.unwrap_err().to_string();
    assert!(err.contains("source code is not available"), "error: {err}");

    // All scope should silently skip unavailable
    let roots = resolve_library_roots(&crate::library::scope::Scope::All, &agent)
        .await
        .unwrap();
    assert_eq!(
        roots.len(),
        1,
        "All scope should only return available libs"
    );
    assert_eq!(roots[0].0, "available");
}

// ── format_library_path ──────────────────────────────────────────────────

#[test]
fn format_library_path_strips_root() {
    let lib_root = PathBuf::from("/home/user/.cargo/registry/src/serde-1.0");
    let file = PathBuf::from("/home/user/.cargo/registry/src/serde-1.0/src/lib.rs");
    let result = format_library_path("serde", &lib_root, &file);
    assert_eq!(result, "lib:serde/src/lib.rs");
}

#[test]
fn format_library_path_fallback_for_outside_root() {
    let lib_root = PathBuf::from("/home/user/.cargo/registry/src/serde-1.0");
    let file = PathBuf::from("/somewhere/else/lib.rs");
    let result = format_library_path("serde", &lib_root, &file);
    assert_eq!(result, "/somewhere/else/lib.rs");
}

// ── classify_reference_path ──────────────────────────────────────────────

#[test]
fn classify_reference_path_project() {
    let root = PathBuf::from("/project");
    let libs = vec![("mylib".to_string(), PathBuf::from("/libs/mylib"))];
    let path = PathBuf::from("/project/src/main.rs");
    let (classification, display) = classify_reference_path(&path, &root, &libs);
    assert_eq!(classification, "project");
    assert_eq!(display, "src/main.rs");
}

#[test]
fn classify_reference_path_library() {
    let root = PathBuf::from("/project");
    let libs = vec![("mylib".to_string(), PathBuf::from("/libs/mylib"))];
    let path = PathBuf::from("/libs/mylib/src/lib.rs");
    let (classification, display) = classify_reference_path(&path, &root, &libs);
    assert_eq!(classification, "lib:mylib");
    assert_eq!(display, "lib:mylib/src/lib.rs");
}

#[test]
fn classify_reference_path_external() {
    let root = PathBuf::from("/project");
    let libs = vec![("mylib".to_string(), PathBuf::from("/libs/mylib"))];
    let path = PathBuf::from("/somewhere/else.rs");
    let (classification, display) = classify_reference_path(&path, &root, &libs);
    assert_eq!(classification, "external");
    assert_eq!(display, "/somewhere/else.rs");
}

/// Regression (issues/2026-06-11-lsp-tools-ignore-workspace-pin-path): the
/// LSP-position tools must resolve a relative `path` against the per-request
/// `workspace=` pin, not the session-default project. Before the fix they
/// called the unpinned `resolve_read_path` and returned `path not found` for a
/// file that exists only in the pinned workspace. Each test pins workspace A
/// (which holds the marker) while the default project is B (which does not),
/// and asserts resolution gets PAST the path stage — never `path not found`.
#[tokio::test]
async fn references_honors_workspace_override_for_relative_path() {
    use crate::tools::symbol::references::References;

    let dir_a = tempdir().unwrap();
    let dir_b = tempdir().unwrap();
    std::fs::create_dir_all(dir_a.path().join(".codescout")).unwrap();
    std::fs::create_dir_all(dir_b.path().join(".codescout")).unwrap();
    // Marker exists ONLY in pinned workspace A, NOT in default workspace B.
    std::fs::write(dir_a.path().join("pin_marker.txt"), "x").unwrap();
    let root_a = std::fs::canonicalize(dir_a.path()).unwrap();

    // Default (unpinned) project is B; pin THIS request to A.
    let agent = Agent::new(Some(dir_b.path().to_path_buf())).await.unwrap();
    let mut ctx = test_ctx_with_agent(agent);
    ctx.workspace_override = Some(root_a);

    let err = References
        .call(
            json!({ "symbol": "Whatever", "path": "pin_marker.txt" }),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();

    assert!(
        !err.contains("path not found"),
        "pinned relative path must resolve against workspace A, not default B; got: {err}"
    );
    assert!(
        err.contains("unsupported language"),
        "resolution should reach the language guard on the .txt marker; got: {err}"
    );
}

#[tokio::test]
async fn symbol_at_honors_workspace_override_for_relative_path() {
    use crate::tools::symbol::symbol_at::SymbolAt;

    let dir_a = tempdir().unwrap();
    let dir_b = tempdir().unwrap();
    std::fs::create_dir_all(dir_a.path().join(".codescout")).unwrap();
    std::fs::create_dir_all(dir_b.path().join(".codescout")).unwrap();
    std::fs::write(dir_a.path().join("pin_marker.txt"), "x").unwrap();
    let root_a = std::fs::canonicalize(dir_a.path()).unwrap();

    let agent = Agent::new(Some(dir_b.path().to_path_buf())).await.unwrap();
    let mut ctx = test_ctx_with_agent(agent);
    ctx.workspace_override = Some(root_a);

    let err = SymbolAt
        .call(json!({ "path": "pin_marker.txt", "line": 1 }), &ctx)
        .await
        .unwrap_err()
        .to_string();

    assert!(
        !err.contains("path not found"),
        "pinned relative path must resolve against workspace A, not default B; got: {err}"
    );
    assert!(
        err.contains("unsupported language"),
        "resolution should reach the language guard on the .txt marker; got: {err}"
    );
}

#[tokio::test]
async fn call_graph_honors_workspace_override_for_relative_path() {
    use crate::tools::symbol::call_graph::CallGraph;

    let dir_a = tempdir().unwrap();
    let dir_b = tempdir().unwrap();
    std::fs::create_dir_all(dir_a.path().join(".codescout")).unwrap();
    std::fs::create_dir_all(dir_b.path().join(".codescout")).unwrap();
    std::fs::write(dir_a.path().join("pin_marker.txt"), "x").unwrap();
    let root_a = std::fs::canonicalize(dir_a.path()).unwrap();

    let agent = Agent::new(Some(dir_b.path().to_path_buf())).await.unwrap();
    let mut ctx = test_ctx_with_agent(agent);
    ctx.workspace_override = Some(root_a);

    let err = CallGraph
        .call(
            json!({ "symbol": "Whatever", "path": "pin_marker.txt" }),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();

    assert!(
        !err.contains("path not found"),
        "pinned relative path must resolve against workspace A, not default B; got: {err}"
    );
    assert!(
        err.contains("unsupported file type"),
        "resolution should reach get_lsp_client's language guard on the .txt marker; got: {err}"
    );
}

fn test_ctx_with_agent(agent: Agent) -> ToolContext {
    ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    }
}

#[tokio::test]
async fn symbols_overview_scope_libraries_includes_library_files() {
    let project_dir = tempdir().unwrap();
    std::fs::create_dir_all(project_dir.path().join(".codescout")).unwrap();
    let lib_dir = tempdir().unwrap();
    let lib_src = lib_dir.path().join("src");
    std::fs::create_dir_all(&lib_src).unwrap();
    std::fs::write(lib_src.join("lib.rs"), "pub fn hello() {}\n").unwrap();

    let agent = Agent::new(Some(project_dir.path().to_path_buf()))
        .await
        .unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "testlib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }

    let ctx = test_ctx_with_agent(agent);
    let tool = Symbols;
    let result = tool
        .call(json!({"scope": "libraries"}), &ctx)
        .await
        .unwrap();

    let files = result["files"].as_array().unwrap();
    assert!(!files.is_empty(), "should find library files");
    let first_file = files[0]["file"].as_str().unwrap();
    assert!(
        first_file.starts_with("lib:testlib/"),
        "library file should have lib: prefix, got: {}",
        first_file
    );
}

#[tokio::test]
async fn symbols_overview_scope_project_excludes_libraries() {
    let project_dir = tempdir().unwrap();
    std::fs::create_dir_all(project_dir.path().join(".codescout")).unwrap();
    let lib_dir = tempdir().unwrap();
    std::fs::create_dir_all(lib_dir.path().join("src")).unwrap();
    std::fs::write(lib_dir.path().join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
    std::fs::write(project_dir.path().join("main.rs"), "fn main() {}\n").unwrap();

    let agent = Agent::new(Some(project_dir.path().to_path_buf()))
        .await
        .unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "testlib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }

    let ctx = test_ctx_with_agent(agent);
    let tool = Symbols;
    let result = tool.call(json!({"scope": "project"}), &ctx).await.unwrap();

    let empty = vec![];
    let files = result["files"].as_array().unwrap_or(&empty);
    for f in files {
        let path = f["file"].as_str().unwrap();
        assert!(
            !path.starts_with("lib:"),
            "project scope should not include library files: {}",
            path
        );
    }
}

#[tokio::test]
async fn symbols_scope_libraries_searches_library_dirs() {
    let project_dir = tempdir().unwrap();
    std::fs::create_dir_all(project_dir.path().join(".codescout")).unwrap();
    let lib_dir = tempdir().unwrap();
    std::fs::create_dir_all(lib_dir.path().join("src")).unwrap();
    std::fs::write(
        lib_dir.path().join("src/lib.rs"),
        "pub fn library_unique_symbol_xyz() {}\n",
    )
    .unwrap();

    let agent = Agent::new(Some(project_dir.path().to_path_buf()))
        .await
        .unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "testlib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }

    let ctx = test_ctx_with_agent(agent);
    let tool = Symbols;
    let result = tool
        .call(
            json!({
                "query": "library_unique_symbol_xyz",
                "scope": "libraries"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    assert!(!symbols.is_empty(), "should find symbol in library");
    let file = symbols[0]["file"]
        .as_str()
        .or_else(|| result["file"].as_str())
        .unwrap();
    assert!(
        file.starts_with("lib:testlib/"),
        "file path should have lib: prefix: {}",
        file
    );
}

#[tokio::test]
async fn symbols_scope_all_searches_both() {
    let project_dir = tempdir().unwrap();
    std::fs::create_dir_all(project_dir.path().join(".codescout")).unwrap();
    let lib_dir = tempdir().unwrap();
    std::fs::write(project_dir.path().join("main.rs"), "fn project_func() {}\n").unwrap();
    std::fs::create_dir_all(lib_dir.path().join("src")).unwrap();
    std::fs::write(lib_dir.path().join("src/lib.rs"), "pub fn lib_func() {}\n").unwrap();

    let agent = Agent::new(Some(project_dir.path().to_path_buf()))
        .await
        .unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "testlib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }

    let ctx = test_ctx_with_agent(agent);
    let tool = Symbols;
    let result = tool
        .call(
            json!({
                "query": "func",
                "scope": "all"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    let files: Vec<&str> = symbols.iter().filter_map(|s| s["file"].as_str()).collect();
    assert!(
        files.iter().any(|f| f.starts_with("lib:testlib/")),
        "should include library symbol"
    );
    assert!(
        files.iter().any(|f| !f.starts_with("lib:")),
        "should include project symbol"
    );
}

#[tokio::test]
async fn symbols_scope_project_default_excludes_libraries() {
    let project_dir = tempdir().unwrap();
    std::fs::create_dir_all(project_dir.path().join(".codescout")).unwrap();
    let lib_dir = tempdir().unwrap();
    std::fs::write(project_dir.path().join("main.rs"), "fn my_func() {}\n").unwrap();
    std::fs::create_dir_all(lib_dir.path().join("src")).unwrap();
    std::fs::write(lib_dir.path().join("src/lib.rs"), "pub fn my_func() {}\n").unwrap();

    let agent = Agent::new(Some(project_dir.path().to_path_buf()))
        .await
        .unwrap();
    {
        let mut inner = agent.inner.write().await;
        let project = inner.active_project_mut().unwrap();
        project.library_registry.register(
            "testlib".to_string(),
            lib_dir.path().to_path_buf(),
            "rust".to_string(),
            crate::library::registry::DiscoveryMethod::Manual,
            true,
        );
    }

    let ctx = test_ctx_with_agent(agent);
    let tool = Symbols;
    let result = tool
        .call(
            json!({
                "query": "my_func",
                "scope": "project"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    let top_file = result["file"].as_str();
    for s in symbols {
        let file = s["file"].as_str().or(top_file).unwrap();
        assert!(
            !file.starts_with("lib:"),
            "project scope should not include library: {}",
            file
        );
    }
}

/// symbols with multiple matches returns all of them.
#[tokio::test]
async fn symbols_with_multiple_matches_returns_all() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("src/a")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    // Three files each defining a function named `process_*` — guarantees 3+ matches.
    std::fs::write(
        dir.path().join("src/a/alpha.rs"),
        "pub fn process_alpha() -> i32 { 1 }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/a/beta.rs"),
        "pub fn process_beta() -> i32 { 2 }\n",
    )
    .unwrap();
    std::fs::write(
        dir.path().join("src/a/gamma.rs"),
        "pub fn process_gamma() -> i32 { 3 }\n",
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: lsp(),
        output_buffer: buf(),
        progress: None,
        peer: None, // no elicitation peer
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };

    let result = Symbols
        .call(json!({ "query": "process" }), &ctx)
        .await
        .unwrap();

    let symbols = result["symbols"].as_array().unwrap();
    // With no peer, ALL matches must be returned (no disambiguation prompt).
    assert!(
        symbols.len() >= 3,
        "should return all matches when peer=None, got {} symbols: {:?}",
        symbols.len(),
        result
    );
    // The total field must also reflect >= 3 results.
    let total = result["total"].as_u64().unwrap_or(0);
    assert!(total >= 3, "total should be >= 3 with no peer, got {total}");
}

#[tokio::test]
async fn symbols_rejects_regex_alternation() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);

    let err = Symbols
        .call(json!({"query": "foo|bar"}), &ctx)
        .await
        .unwrap_err();

    let rec = err
        .downcast_ref::<crate::tools::RecoverableError>()
        .expect("should be RecoverableError");
    assert!(
        rec.message.contains("regex"),
        "message should mention regex, got: {}",
        rec.message
    );
    assert!(
        rec.hint().unwrap_or("").contains("grep"),
        "hint should mention grep, got: {:?}",
        rec.hint()
    );
}

#[tokio::test]
async fn symbols_rejects_regex_wildcard() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);

    let err = Symbols
        .call(json!({"query": "foo.*bar"}), &ctx)
        .await
        .unwrap_err();

    assert!(
        err.downcast_ref::<crate::tools::RecoverableError>()
            .is_some(),
        "should be RecoverableError, got: {}",
        err
    );
}

#[tokio::test]
async fn symbols_allows_plain_pattern() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(dir.path().join("test.rs"), "fn my_function() {}\n").unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);

    let result = Symbols.call(json!({"query": "my_function"}), &ctx).await;
    assert!(result.is_ok(), "plain pattern should not be rejected");
}

#[tokio::test]
async fn symbols_allows_name_path_with_regex_chars() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);

    let result = Symbols.call(json!({"symbol": "foo|bar"}), &ctx).await;
    assert!(
        result.is_ok(),
        "name_path should skip regex check, got err: {:?}",
        result.err()
    );
}

#[test]
fn find_split_point_collapses_single_child_chain() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    // a/ → b/ → c/ (three files directly in c/) — should collapse to c/
    std::fs::create_dir_all(root.join("a/b/c")).unwrap();
    for i in 0..3 {
        std::fs::write(root.join(format!("a/b/c/file{i}.rs")), "").unwrap();
    }
    let split = find_split_point(root);
    assert_eq!(split, root.join("a/b/c"));
}

#[test]
fn find_split_point_stops_at_branch() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join("a/b")).unwrap();
    std::fs::create_dir_all(root.join("a/c")).unwrap();
    std::fs::write(root.join("a/b/file.rs"), "").unwrap();
    std::fs::write(root.join("a/c/file.rs"), "").unwrap();
    let split = find_split_point(root);
    assert_eq!(split, root.join("a"), "should stop at branching dir");
}

#[test]
fn find_split_point_stops_when_dir_has_direct_files() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    // a/ has one child b/ but also a direct source file — stop here
    std::fs::create_dir_all(root.join("a/b")).unwrap();
    std::fs::write(root.join("a/root.rs"), "").unwrap();
    std::fs::write(root.join("a/b/file.rs"), "").unwrap();
    let split = find_split_point(root);
    assert_eq!(split, root.join("a"), "mixed dir stops descent");
}

#[test]
fn count_files_by_subdir_groups_and_sorts() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join("sub_a")).unwrap();
    for i in 0..3 {
        std::fs::write(root.join(format!("sub_a/file{i}.rs")), "").unwrap();
    }
    std::fs::create_dir_all(root.join("sub_b")).unwrap();
    for i in 0..5 {
        std::fs::write(root.join(format!("sub_b/file{i}.rs")), "").unwrap();
    }
    // 1 file directly in root (counted in total, not in subdirs)
    std::fs::write(root.join("root.rs"), "").unwrap();

    let (total, subdirs) = count_files_by_subdir(root, root);

    assert_eq!(total, 9);
    assert_eq!(subdirs.len(), 2);
    assert!(subdirs[0].0.contains("sub_b"), "largest subdir first");
    assert_eq!(subdirs[0].1, 5);
    assert!(subdirs[1].0.contains("sub_a"));
    assert_eq!(subdirs[1].1, 3);
}

#[test]
fn count_files_by_subdir_collapses_passthrough() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    // kotlin/ → edu/ → planner/ → [api/(3), domain/(2)]
    for (sub, n) in &[("api", 3usize), ("domain", 2)] {
        std::fs::create_dir_all(root.join(format!("kotlin/edu/planner/{sub}"))).unwrap();
        for i in 0..*n {
            std::fs::write(root.join(format!("kotlin/edu/planner/{sub}/f{i}.rs")), "").unwrap();
        }
    }
    let (total, subdirs) = count_files_by_subdir(root, &root.join("kotlin"));
    assert_eq!(total, 5);
    assert_eq!(subdirs.len(), 2, "collapsed to planner/ children, not edu/");
    assert!(subdirs[0].0.contains("api"), "api (3) before domain (2)");
    assert_eq!(subdirs[0].1, 3);
}

#[test]
fn count_files_by_subdir_flat_dir_returns_empty_subdirs() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    for i in 0..4 {
        std::fs::write(root.join(format!("file{i}.rs")), "").unwrap();
    }
    let (total, subdirs) = count_files_by_subdir(root, root);
    assert_eq!(total, 4);
    assert!(subdirs.is_empty());
}

#[test]
fn count_files_by_subdir_ignores_non_source_files() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::write(root.join("sub/README.md"), "").unwrap(); // ignored
    std::fs::write(root.join("sub/build.rs"), "").unwrap(); // counted
    let (total, _subdirs) = count_files_by_subdir(root, root);
    assert_eq!(total, 1, "markdown should not be counted as source");
}

#[test]
fn ast_class_names_for_dir_extracts_class_like_symbols() {
    let dir = tempdir().unwrap();
    std::fs::write(
        dir.path().join("types.rs"),
        r#"
struct Foo { x: i32 }
struct Bar;
enum Baz { A, B }
fn not_a_class() {}
const SKIP: i32 = 1;
"#,
    )
    .unwrap();
    std::fs::write(dir.path().join("README.md"), "# hi").unwrap();

    let names = ast_class_names_for_dir(dir.path());

    assert!(names.contains(&"Foo".to_string()));
    assert!(names.contains(&"Bar".to_string()));
    assert!(names.contains(&"Baz".to_string()));
    assert!(!names.contains(&"not_a_class".to_string()));
    assert!(!names.contains(&"SKIP".to_string()));
    // sorted
    assert_eq!(names, {
        let mut v = names.clone();
        v.sort();
        v
    });
}

#[test]
fn ast_class_names_for_dir_does_not_recurse_into_subdirs() {
    let dir = tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("sub")).unwrap();
    std::fs::write(dir.path().join("sub/deep.rs"), "struct DeepClass;").unwrap();
    std::fs::write(dir.path().join("top.rs"), "struct TopClass;").unwrap();

    let names = ast_class_names_for_dir(dir.path());

    assert!(names.contains(&"TopClass".to_string()));
    assert!(!names.contains(&"DeepClass".to_string()));
}

#[tokio::test]
async fn symbols_overview_nested_dir_returns_overview_mode() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join(".codescout")).unwrap();
    // sub_a and sub_b each with 20 Rust files (total=40 > RECURSE_SMALL=30)
    for sub in &["sub_a", "sub_b"] {
        std::fs::create_dir_all(root.join(sub)).unwrap();
        for i in 0..20 {
            std::fs::write(root.join(format!("{sub}/f{i}.rs")), "pub struct S;").unwrap();
        }
    }
    let agent = Agent::new(Some(root.to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);
    let result = Symbols.call(json!({ "path": "." }), &ctx).await.unwrap();

    // 40 files in two subdirs → class_overview (31–80 range)
    assert_eq!(result["mode"].as_str(), Some("class_overview"));
    let subdirs = result["subdirectories"].as_array().unwrap();
    assert_eq!(subdirs.len(), 2);
    assert_eq!(result["total_files"].as_u64(), Some(40));
    let sub_a = subdirs
        .iter()
        .find(|s| s["path"].as_str().unwrap_or("").contains("sub_a"))
        .unwrap();
    assert!(
        sub_a["classes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|c| c.as_str() == Some("S")),
        "AST class names extracted"
    );
}

#[tokio::test]
async fn symbols_overview_force_mode_symbols_bypasses_threshold() {
    let dir = tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join(".codescout")).unwrap();
    for sub in &["sub_a", "sub_b"] {
        std::fs::create_dir_all(root.join(sub)).unwrap();
        for i in 0..20 {
            std::fs::write(root.join(format!("{sub}/f{i}.rs")), "pub struct S;").unwrap();
        }
    }
    let agent = Agent::new(Some(root.to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);
    let result = Symbols
        .call(json!({ "path": ".", "force_mode": "symbols" }), &ctx)
        .await
        .unwrap();

    // force_mode: "symbols" → no "mode" key, returns files array
    assert!(result["mode"].is_null(), "no mode field in symbols output");
    assert!(result["files"].is_array(), "files array present");
}

#[tokio::test]
async fn edit_code_replace_appends_caller_hint() {
    if !std::process::Command::new("rust-analyzer")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        eprintln!("Skipping: rust-analyzer not installed");
        return;
    }

    let dir = tempdir().unwrap();
    std::fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"test-hint\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn greet(name: &str) -> String {\n    format!(\"Hello, {}!\", name)\n}\n",
    )
    .unwrap();

    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);

    // Retry loop: rust-analyzer needs time to index
    let mut outcome: Option<Value> = None;
    for attempt in 0..5 {
        if attempt > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(600 * attempt)).await;
        }
        let result = EditCode
            .call(
                json!({
                    "symbol": "greet",
                    "path": "src/lib.rs",
                    "action": "replace",
                    "body": "pub fn greet(name: &str) -> String {\n    format!(\"Hi, {}!\", name)\n}\n"
                }),
                &ctx,
            )
            .await;
        match result {
            Ok(v) => {
                outcome = Some(v);
                break;
            }
            Err(e) => {
                eprintln!("Attempt {}: {}", attempt + 1, e);
            }
        }
    }

    let result = match outcome {
        Some(v) => v,
        None => {
            eprintln!("Skipping: LSP did not respond in time");
            return;
        }
    };

    let hint = result["hint"]
        .as_str()
        .expect("replace result must contain 'hint' field");
    assert!(
        hint.contains("references("),
        "hint should mention references: {hint}"
    );
    assert!(
        hint.contains("greet"),
        "hint should include symbol name: {hint}"
    );
    assert!(
        hint.contains("src/lib.rs"),
        "hint should include file path: {hint}"
    );
}

#[test]
fn collect_matching_skips_function_children_when_pushed() {
    // Regression: a function whose Variable children's name_path starts with
    // the function name (e.g. Python parameters) must not be returned as
    // separate hits. Even when the predicate matches both, the parent's body
    // already contains the children verbatim, so emitting them is duplication.
    use crate::lsp::SymbolKind;
    let symbols = vec![SymbolInfo {
        name: "complete_text".into(),
        name_path: "complete_text".into(),
        kind: SymbolKind::Function,
        file: PathBuf::from("gemini.py"),
        start_line: 130,
        end_line: 169,
        start_col: 0,
        children: vec![
            SymbolInfo {
                name: "prompt".into(),
                name_path: "complete_text/prompt".into(),
                kind: SymbolKind::Variable,
                file: PathBuf::from("gemini.py"),
                start_line: 131,
                end_line: 131,
                start_col: 4,
                children: vec![],
                range_start_line: None,
                detail: None,
            },
            SymbolInfo {
                name: "model".into(),
                name_path: "complete_text/model".into(),
                kind: SymbolKind::Variable,
                file: PathBuf::from("gemini.py"),
                start_line: 132,
                end_line: 132,
                start_col: 4,
                children: vec![],
                range_start_line: None,
                detail: None,
            },
        ],
        range_start_line: None,
        detail: None,
    }];

    // Use the legacy buggy-style predicate (matches name OR name_path) to prove
    // the suppression works regardless of predicate width.
    let mut out = vec![];
    collect_matching(
        &symbols,
        &substr_pred("complete_text"),
        true,
        None,
        0,
        true,
        &mut out,
        None,
    );
    assert_eq!(
        out.len(),
        1,
        "function parent should suppress its parameter children"
    );
    assert_eq!(out[0]["name"], "complete_text");
}

#[test]
fn collect_matching_keeps_class_method_descendants() {
    // Counterexample: Class/Struct/Module/Interface keep recursing — their
    // methods are independent navigation targets, not sub-locations.
    use crate::lsp::SymbolKind;
    let symbols = vec![SymbolInfo {
        name: "Foo".into(),
        name_path: "Foo".into(),
        kind: SymbolKind::Class,
        file: PathBuf::from("a.py"),
        start_line: 0,
        end_line: 20,
        start_col: 0,
        children: vec![SymbolInfo {
            name: "Foo_helper".into(),
            name_path: "Foo/Foo_helper".into(),
            kind: SymbolKind::Method,
            file: PathBuf::from("a.py"),
            start_line: 2,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        }],
        range_start_line: None,
        detail: None,
    }];

    let mut out = vec![];
    collect_matching(
        &symbols,
        &substr_pred("foo"),
        true,
        None,
        0,
        true,
        &mut out,
        None,
    );
    assert_eq!(out.len(), 2, "class should not suppress method descendants");
}

#[test]
fn format_search_symbols_groups_by_file() {
    use crate::tools::symbol::display::format_search_symbols;
    let val = json!({
        "symbols": [
            { "kind": "Function", "file": "a.rs", "start_line": 1, "end_line": 5, "name": "foo", "symbol": "foo" },
            { "kind": "Function", "file": "a.rs", "start_line": 10, "end_line": 15, "name": "bar", "symbol": "bar" },
            { "kind": "Function", "file": "b.rs", "start_line": 3, "end_line": 7, "name": "baz", "symbol": "baz" },
        ],
        "total": 3,
    });
    let out = format_search_symbols(&val);
    assert!(out.starts_with("3 matches in 2 files\n"), "got:\n{out}");
    assert!(out.contains("a.rs (2)"));
    assert!(out.contains("b.rs (1)"));
    assert!(
        !out.contains("a.rs:1-5"),
        "row should not repeat file path: {out}"
    );
    assert!(out.contains("foo"));
    assert!(out.contains("bar"));
    assert!(out.contains("baz"));
}

#[test]
fn format_search_symbols_single_file_no_global_header() {
    use crate::tools::symbol::display::format_search_symbols;
    let val = json!({
        "symbols": [
            { "kind": "Function", "file": "a.rs", "start_line": 1, "end_line": 5, "name": "foo", "symbol": "foo" },
        ],
        "total": 1,
    });
    let out = format_search_symbols(&val);
    assert!(
        !out.contains(" in 1 files"),
        "single-file output should omit global header: {out}"
    );
    assert!(out.starts_with("a.rs (1)\n"), "got:\n{out}");
}

// ── symbols single-match focus + search-mode include_docs ──────────────────

#[tokio::test]
async fn include_docs_attaches_docs_in_search_mode() {
    // Regression (docs/issues/2026-06-11-symbols-search-include-docs-and-focus):
    // include_docs was consumed only by the overview path; a search (name given)
    // silently dropped it. End-to-end proof through Symbols::call that the live
    // search path now attaches a per-symbol `docs` field.
    let dir = tempfile::TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("lib.rs"),
        "/// Adds two numbers together.\nfn my_documented_add(a: i32, b: i32) -> i32 { a + b }\n",
    )
    .unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    let ctx = test_ctx_with_agent(agent);
    let result = Symbols
        .call(
            json!({ "query": "my_documented_add", "path": "lib.rs", "include_docs": true }),
            &ctx,
        )
        .await
        .unwrap();
    let syms = result["symbols"].as_array().expect("symbols array");
    assert!(!syms.is_empty(), "expected a match for my_documented_add");
    let docs = syms[0]["docs"]
        .as_str()
        .expect("include_docs must attach a `docs` field in SEARCH mode (was ignored; only overview honored it)");
    assert!(docs.contains("Adds two numbers"), "got: {docs}");
}

#[test]
fn focus_single_symbol_inlines_large_leaf_body() {
    use super::symbols::focus_single_symbol;
    let dir = tempfile::TempDir::new().unwrap();
    // A function longer than the conservative 40-line auto-inline cap.
    let mut content = String::from("fn big() {\n");
    for i in 0..50 {
        content.push_str(&format!("    let _x{i} = {i};\n"));
    }
    content.push_str("}\n");
    let n_lines = content.lines().count() as u64;
    std::fs::write(dir.path().join("big.rs"), &content).unwrap();
    let mut matches = vec![json!({
        "name": "big", "symbol": "big", "kind": "Function",
        "file": "big.rs", "start_line": 1, "end_line": n_lines,
    })];
    focus_single_symbol(&mut matches, dir.path());
    let body = matches[0]["body"]
        .as_str()
        .expect("a single leaf match should inline its full body even past the 40-line cap");
    assert!(body.contains("let _x0"));
    assert!(matches[0].get("children").is_none());
}

#[test]
fn focus_single_symbol_shows_members_for_large_container() {
    use super::symbols::focus_single_symbol;
    let dir = tempfile::TempDir::new().unwrap();
    // A Kotlin object whose enclosing range exceeds the 80-line container cap.
    let mut content =
        String::from("object Big {\n    fun alpha() {}\n    fun beta() {}\n    fun gamma() {}\n");
    for i in 0..90 {
        content.push_str(&format!("    // pad {i}\n"));
    }
    content.push_str("}\n");
    let n_lines = content.lines().count() as u64;
    std::fs::write(dir.path().join("Big.kt"), &content).unwrap();
    let mut matches = vec![json!({
        "name": "Big", "symbol": "Big", "kind": "Object",
        "file": "Big.kt", "start_line": 1, "end_line": n_lines,
    })];
    focus_single_symbol(&mut matches, dir.path());
    assert!(
        matches[0].get("body").is_none(),
        "a large container should expose members, not dump its full body"
    );
    let children = matches[0]["children"]
        .as_array()
        .expect("large container should expose its direct members");
    let names: Vec<&str> = children.iter().filter_map(|c| c["name"].as_str()).collect();
    assert!(
        names.contains(&"alpha") && names.contains(&"beta") && names.contains(&"gamma"),
        "expected the object's methods as members, got: {names:?}"
    );
    assert!(matches[0]["members_hint"]
        .as_str()
        .unwrap_or("")
        .contains("members"));
}

#[test]
fn attach_docstrings_attaches_symbol_doc() {
    use super::symbols::attach_docstrings;
    let dir = tempfile::TempDir::new().unwrap();
    std::fs::write(
        dir.path().join("m.rs"),
        "/// Adds two numbers.\nfn add(a: i32, b: i32) -> i32 { a + b }\n",
    )
    .unwrap();
    // `add` is declared on line 2; its doc occupies line 1.
    let mut matches = vec![json!({
        "name": "add", "symbol": "add", "kind": "Function",
        "file": "m.rs", "start_line": 2, "end_line": 2,
    })];
    attach_docstrings(&mut matches, dir.path());
    let docs = matches[0]["docs"]
        .as_str()
        .expect("docs should be attached");
    assert!(docs.contains("Adds two numbers"), "got: {docs}");
}

#[test]
fn format_search_symbols_renders_docs_members_and_hint() {
    use crate::tools::symbol::display::format_search_symbols;
    let val = json!({
        "symbols": [{
            "name": "Big", "symbol": "Big", "kind": "Object",
            "file": "Big.kt", "start_line": 1, "end_line": 200,
            "docs": "A big thing.",
            "children": [
                {"name": "alpha", "symbol": "Big/alpha", "kind": "Method",
                 "start_line": 2, "end_line": 2, "signature": "fun alpha()"}
            ],
            "members_hint": "1 direct member (200-line object)."
        }],
        "total": 1
    });
    let text = format_search_symbols(&val);
    assert!(
        text.contains("// A big thing."),
        "docs should render as a comment line:\n{text}"
    );
    assert!(text.contains("Big/alpha"), "member should render:\n{text}");
    assert!(
        text.contains("fun alpha()"),
        "member signature should render:\n{text}"
    );
    assert!(
        text.contains("-> 1 direct member"),
        "members_hint should render:\n{text}"
    );
}

#[test]
fn attach_docs_from_array_sets_docs_recursively() {
    use super::list_overview::attach_docs_from_array;
    let mut symbols = vec![json!({
        "name": "Outer", "symbol": "Outer", "kind": "Class",
        "start_line": 1, "end_line": 20,
        "children": [
            {"name": "inner_method", "symbol": "Outer/inner_method", "kind": "Method",
             "start_line": 5, "end_line": 7}
        ]
    })];
    let docstrings = vec![
        json!({"symbol_name": "Outer", "content": "The outer class.", "start_line": 1, "end_line": 1}),
        json!({"symbol_name": "inner_method", "content": "An inner method.", "start_line": 4, "end_line": 4}),
    ];
    attach_docs_from_array(&mut symbols, &docstrings);
    assert_eq!(symbols[0]["docs"].as_str(), Some("The outer class."));
    assert_eq!(
        symbols[0]["children"][0]["docs"].as_str(),
        Some("An inner method."),
        "docs must attach to nested children too"
    );
}

#[test]
fn format_overview_symbols_renders_per_symbol_doc() {
    use crate::tools::symbol::display::format_overview_symbols;
    let val = json!({
        "file": "lib.rs",
        "symbols": [{
            "name": "documented_fn", "symbol": "documented_fn", "kind": "Function",
            "start_line": 2, "end_line": 4,
            "docs": "Does a thing.\nMore detail."
        }]
    });
    let text = format_overview_symbols(&val);
    assert!(
        text.contains("documented_fn"),
        "symbol should render:\n{text}"
    );
    assert!(
        text.contains("// Does a thing."),
        "first doc line should render inline:\n{text}"
    );
    assert!(
        !text.contains("More detail"),
        "only the first doc line belongs in overview:\n{text}"
    );
}

// ---------- auto_inline_small_bodies ----------

fn fixture_with_class(dir: &std::path::Path, lines: usize) -> std::path::PathBuf {
    let path = dir.join("models.py");
    let mut body = String::from("# header line 1\n# header line 2\n");
    body.push_str("class DocumentChunk:\n");
    for i in 0..lines {
        body.push_str(&format!("    field_{i}: int = 0\n"));
    }
    std::fs::write(&path, body).unwrap();
    path
}

#[test]
fn auto_inline_attaches_body_when_one_small_match() {
    let dir = tempdir().unwrap();
    let _ = fixture_with_class(dir.path(), 8);
    let mut matches = vec![json!({
        "name": "DocumentChunk",
        "kind": "Class",
        "file": "models.py",
        "start_line": 3,
        "end_line": 11,
    })];
    super::symbols::auto_inline_small_bodies(&mut matches, dir.path());
    let body = matches[0]
        .get("body")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert!(
        body.contains("class DocumentChunk:"),
        "expected body to start at class declaration, got: {body:?}"
    );
    assert!(
        body.contains("field_0: int = 0"),
        "expected body to include first field, got: {body:?}"
    );
}

#[test]
fn auto_inline_skips_when_match_too_large() {
    let dir = tempdir().unwrap();
    let _ = fixture_with_class(dir.path(), 60);
    let mut matches = vec![json!({
        "name": "BigClass",
        "kind": "Class",
        "file": "models.py",
        "start_line": 3,
        "end_line": 63,
    })];
    super::symbols::auto_inline_small_bodies(&mut matches, dir.path());
    assert!(
        matches[0].get("body").is_none(),
        "61-line match exceeds AUTO_INLINE_MAX_LINES (40); body should not be attached"
    );
}

#[test]
fn auto_inline_skips_when_too_many_matches() {
    let dir = tempdir().unwrap();
    let _ = fixture_with_class(dir.path(), 4);
    // Three tiny matches — over the 2-match cap even though total LOC is fine.
    let mut matches = vec![
        json!({"name": "a", "file": "models.py", "start_line": 1, "end_line": 1}),
        json!({"name": "b", "file": "models.py", "start_line": 2, "end_line": 2}),
        json!({"name": "c", "file": "models.py", "start_line": 3, "end_line": 3}),
    ];
    super::symbols::auto_inline_small_bodies(&mut matches, dir.path());
    for m in &matches {
        assert!(
            m.get("body").is_none(),
            "3 matches exceeds AUTO_INLINE_MAX_MATCHES (2); no bodies should be attached"
        );
    }
}

#[test]
fn auto_inline_skips_library_matches() {
    let dir = tempdir().unwrap();
    let mut matches = vec![json!({
        "name": "Foo",
        "kind": "Class",
        "file": "lib:numpy/core.py",
        "start_line": 1,
        "end_line": 5,
    })];
    super::symbols::auto_inline_small_bodies(&mut matches, dir.path());
    assert!(
        matches[0].get("body").is_none(),
        "lib: prefix should be skipped (no library-root resolution here)"
    );
}

#[test]
fn auto_inline_preserves_existing_body() {
    let dir = tempdir().unwrap();
    let path = fixture_with_class(dir.path(), 4);
    let _ = path;
    let mut matches = vec![json!({
        "name": "DocumentChunk",
        "file": "models.py",
        "start_line": 3,
        "end_line": 7,
        "body": "ALREADY SET",
    })];
    super::symbols::auto_inline_small_bodies(&mut matches, dir.path());
    assert_eq!(matches[0]["body"], "ALREADY SET");
}