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
//! Regression tests for LSP-backed symbol tools using a mock LSP client.
//!
//! These tests verify the "trust LSP" file-splice logic without requiring a live
//! language server. The mock returns pre-configured symbol positions that reproduce
//! LSP range quirks (over-extension, degenerate ranges, lead-in artifacts).

use codescout::agent::Agent;
use codescout::lsp::{MockLspClient, MockLspProvider, SymbolInfo, SymbolKind};
use codescout::tools::symbol::{EditCode, SymbolAt, Symbols};
use codescout::tools::{Tool, ToolContext};
use serde_json::json;

// ── Test helpers ──────────────────────────────────────────────────────────────

/// Build a ToolContext with a mock LSP provider.
///
/// `files` are written relative to a fresh tempdir (which becomes the project root).
/// `build_mock` receives the absolute project root so it can pre-load symbols keyed
/// by their absolute paths (which is what the tool passes to `document_symbols`).
async fn ctx_with_mock(
    files: &[(&str, &str)],
    build_mock: impl FnOnce(&std::path::Path) -> MockLspClient,
) -> (tempfile::TempDir, ToolContext) {
    let dir = tempfile::tempdir().unwrap();
    // Canonicalize the project root so mock-keyed symbol paths match what
    // production code looks up after its own canonicalize() pass. On macOS
    // tempdir() returns `/var/folders/...` but Agent canonicalizes to
    // `/private/var/folders/...`; without this the mock lookup misses.
    let root = std::fs::canonicalize(dir.path()).unwrap();
    std::fs::create_dir_all(root.join(".codescout")).unwrap();
    for (name, content) in files {
        let path = root.join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }
    let mock = build_mock(&root);
    let agent = Agent::new(Some(root.clone())).await.unwrap();
    let ctx = ToolContext {
        agent,
        lsp: MockLspProvider::with_client(mock),
        output_buffer: std::sync::Arc::new(codescout::tools::output_buffer::OutputBuffer::new(20)),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            codescout::tools::section_coverage::SectionCoverage::new(),
        )),
        guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
        workspace_override: None,
    };
    (dir, ctx)
}

/// Build a minimal SymbolInfo for use in mock fixtures (0-indexed lines).
fn sym(
    name: &str,
    start_line: u32,
    end_line: u32,
    path: impl Into<std::path::PathBuf>,
) -> SymbolInfo {
    SymbolInfo {
        name: name.to_string(),
        name_path: name.to_string(),
        kind: SymbolKind::Function,
        file: path.into(),
        start_line,
        end_line,
        start_col: 0,
        children: vec![],
        range_start_line: None,
        detail: None,
    }
}

/// Like `sym`, but with an explicit `range_start_line` (simulates documentSymbol
/// which provides both `selectionRange` and `range`).
fn sym_with_range(
    name: &str,
    start_line: u32,
    end_line: u32,
    range_start: u32,
    path: impl Into<std::path::PathBuf>,
) -> SymbolInfo {
    SymbolInfo {
        name: name.to_string(),
        name_path: name.to_string(),
        kind: SymbolKind::Function,
        file: path.into(),
        start_line,
        end_line,
        start_col: 0,
        children: vec![],
        range_start_line: Some(range_start),
        detail: None,
    }
}

// ── replace_symbol: trust LSP start_line ─────────────────────────────────────

/// With "trust LSP" design, when LSP says start_line=0 (the `}` of a preceding
/// method), we replace from line 0. The preceding `}` is replaced along with the
/// old body — there is no lead-in skipping.
#[tokio::test]
async fn replace_symbol_trusts_lsp_start_line() {
    // File layout (0-indexed):
    //  0: "    }"          ← closing brace of a preceding method (LSP start_line=0)
    //  1: ""               ← blank line
    //  2: "    fn target() {"
    //  3: "        old_body();"
    //  4: "    }"
    let src = "    }\n\n    fn target() {\n        old_body();\n    }\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(
            file.clone(),
            // LSP reports start_line=0 (the `}` line) — trust LSP, replace from there
            vec![sym("target", 0, 4, file)],
        )
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "    fn target() {\n        new_body();\n    }"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    // With "trust LSP", the preceding `}` is within the LSP range and is replaced
    assert!(
        result.contains("new_body()"),
        "replacement body must be applied; got:\n{result}"
    );
    assert!(
        !result.contains("old_body()"),
        "old body must be gone; got:\n{result}"
    );
}

/// With "trust LSP" design, when LSP says start_line=0 (the `})` of a preceding
/// method), we replace from line 0. The `})` and `}` lines are gone — no lead-in
/// skipping.
#[tokio::test]
async fn replace_symbol_trusts_lsp_start_with_paren_close() {
    // File layout (0-indexed):
    //  0: "        })"     ← closing `)` of json! macro in the preceding method
    //  1: "    }"          ← closing brace of the preceding method
    //  2: ""               ← blank line
    //  3: "    fn target() {"
    //  4: "        old_body();"
    //  5: "    }"
    let src = "        })\n    }\n\n    fn target() {\n        old_body();\n    }\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(
            file.clone(),
            // LSP reports start_line=0 (the `})` line) — trust LSP, replace from there
            vec![sym("target", 0, 5, file)],
        )
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "    fn target() {\n        new_body();\n    }"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    // With "trust LSP", lines 0-5 are replaced — `})` and `}` are gone
    assert!(
        result.contains("new_body()"),
        "replacement body must be applied; got:\n{result}"
    );
    assert!(
        !result.contains("old_body()"),
        "old body must be gone; got:\n{result}"
    );
}

/// Normal case: LSP start_line points directly at `fn` — no lead-in to skip.
#[tokio::test]
async fn replace_symbol_clean_start_line() {
    // File layout (0-indexed):
    //  0: "fn foo() {"
    //  1: "    old();"
    //  2: "}"
    let src = "fn foo() {\n    old();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("foo", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "foo",
                "action": "replace",
                "body": "fn foo() {\n    new();\n}"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("new()"),
        "replacement must apply; got:\n{result}"
    );
    assert!(
        !result.contains("old()"),
        "old body must be gone; got:\n{result}"
    );
}
// ── BUG-018: replace_symbol truncated end_line (inside body, misses closing `}`) ──

/// When LSP reports an end_line that lands inside the function body instead of
/// at the closing `}`, trusting that range causes replace_symbol to splice only
/// the first N lines and leave the tail of the old body in the file — stray
/// tokens, compilation failure, silent corruption.
///
/// validate_symbol_range must catch `end_line < AST end_line` and return
/// RecoverableError before touching the file. Regression test for BUG-018.
#[tokio::test]
async fn replace_symbol_rejects_truncated_end_line() {
    // File layout (0-indexed):
    //  0: "fn target() {"       ← LSP start=0 (correct)
    //  1: "    old_body();"     ← LSP end=1   (WRONG — truncated, misses `}`)
    //  2: "}"                   ← actual end=2, not covered by LSP range
    let src = "fn target() {\n    old_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(
            file.clone(),
            // end_line=1 is inside the body — truncated off-by-one (BUG-018 pattern)
            vec![sym("target", 0, 1, file)],
        )
    })
    .await;

    let err = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "fn target() {\n    new_body();\n}"
            }),
            &ctx,
        )
        .await
        .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("suspicious range"),
        "expected suspicious range error, got: {msg}"
    );

    // File must be untouched — truncated splice would have left a stray `}`
    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("old_body()"),
        "file must be unmodified after truncated-range guard; got:\n{content}"
    );
}

// ── Read/write symmetry: symbols body → replace_symbol round-trip ────────

/// Round-trip: symbols(include_body) → modify → replace_symbol preserves attributes.
/// This is the bug that motivated the full-range body change: symbols returned
/// body from start_line (no attributes), but replace_symbol replaced from
/// editing_start_line (with attributes), consuming #[test] etc.
#[tokio::test]
async fn replace_symbol_round_trip_preserves_attributes() {
    // File layout (0-indexed):
    //  0: "#[test]"                     <- range_start = 0
    //  1: "/// A test function"
    //  2: "fn target() {"               <- selectionRange.start = 2
    //  3: "    old_body();"
    //  4: "}"                           <- end = 4
    let src = "#[test]\n/// A test function\nfn target() {\n    old_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 2, 4, 0, file)])
    })
    .await;

    // Step 1: Read the symbol body (simulates what the agent does)
    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    // The body should include #[test] and /// doc
    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    assert!(
        body.contains("#[test]"),
        "symbols body should include attribute; got:\n{body}"
    );

    // Step 2: Agent modifies the body (changes old_body to new_body, keeps attrs)
    let new_body = body.replace("old_body()", "new_body()");

    // Step 3: Replace with the modified body
    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("#[test]"),
        "attribute must be preserved after round-trip; got:\n{result}"
    );
    assert!(
        result.contains("/// A test function"),
        "doc comment must be preserved after round-trip; got:\n{result}"
    );
    assert!(
        result.contains("new_body()"),
        "new body must be applied; got:\n{result}"
    );
    assert!(
        !result.contains("old_body()"),
        "old body must be gone; got:\n{result}"
    );
}

/// Python: decorators above def are in range_start, docstrings are inside the body.
#[tokio::test]
async fn replace_symbol_round_trip_preserves_python_decorator() {
    // File layout (0-indexed):
    //  0: "@staticmethod"               <- range_start = 0
    //  1: "def target():"               <- selectionRange.start = 1
    //  2: "    old_body()"              <- end = 2
    let src = "@staticmethod\ndef target():\n    old_body()\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.py", src)], |root| {
        let file = root.join("src/lib.py");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 1, 2, 0, file)])
    })
    .await;

    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.py",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    assert!(
        body.contains("@staticmethod"),
        "body should include decorator; got:\n{body}"
    );

    let new_body = body.replace("old_body()", "new_body()");

    EditCode
        .call(
            json!({
                "path": "src/lib.py",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.py")).unwrap();
    assert!(
        result.contains("@staticmethod"),
        "decorator must survive round-trip; got:\n{result}"
    );
    assert!(
        result.contains("new_body()"),
        "new body must be applied; got:\n{result}"
    );
}

/// Java: @Override annotation + Javadoc above method.
#[tokio::test]
async fn replace_symbol_round_trip_preserves_java_annotation() {
    // File layout (0-indexed):
    //  0: "/** Javadoc comment */"       <- range_start = 0
    //  1: "@Override"
    //  2: "public void target() {"       <- selectionRange.start = 2
    //  3: "    oldBody();"
    //  4: "}"                            <- end = 4
    let src = "/** Javadoc comment */\n@Override\npublic void target() {\n    oldBody();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/Main.java", src)], |root| {
        let file = root.join("src/Main.java");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 2, 4, 0, file)])
    })
    .await;

    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/Main.java",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    assert!(
        body.contains("@Override"),
        "body should include annotation; got:\n{body}"
    );
    assert!(
        body.contains("/** Javadoc"),
        "body should include Javadoc; got:\n{body}"
    );

    let new_body = body.replace("oldBody()", "newBody()");

    EditCode
        .call(
            json!({
                "path": "src/Main.java",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/Main.java")).unwrap();
    assert!(
        result.contains("@Override"),
        "annotation must survive; got:\n{result}"
    );
    assert!(
        result.contains("/** Javadoc"),
        "Javadoc must survive; got:\n{result}"
    );
    assert!(
        result.contains("newBody()"),
        "new body applied; got:\n{result}"
    );
}

/// Clean round-trip with no attributes — no regression from the full-range change.
#[tokio::test]
async fn replace_symbol_round_trip_no_attributes() {
    let src = "fn target() {\n    old_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(
            file.clone(),
            // range_start == start — no attributes
            vec![sym_with_range("target", 0, 2, 0, file)],
        )
    })
    .await;

    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    let new_body = body.replace("old_body()", "new_body()");

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("new_body()"),
        "new body must be applied; got:\n{result}"
    );
    assert!(
        !result.contains("old_body()"),
        "old body must be gone; got:\n{result}"
    );
    // File should have exactly the same number of lines
    assert_eq!(result.lines().count(), src.lines().count());
}

/// Guard: replace_symbol with body-only code (missing signature) is detected,
/// rejected, and the file is restored automatically.
#[tokio::test]
async fn replace_symbol_rejects_body_only_new_body_and_restores_file() {
    let src = "fn target() {\n    original_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 0, 2, 0, file)])
    })
    .await;

    // Pass body-only code — no `fn target()` signature.
    let body_only = "    new_body();\n";
    let err = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": body_only
            }),
            &ctx,
        )
        .await
        .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("dropped the symbol definition"),
        "error must mention dropped symbol; got: {msg}"
    );

    // File must be restored to original content.
    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert_eq!(
        result, src,
        "file must be restored to original after rollback"
    );
}

/// BUG-042 extension: body-only rejection must work for NESTED symbols too.
/// The original fix (2026-04-16) counted pre/post symbols at the flat top
/// level of the AST tree. That caught top-level Rust fns — and Rust `impl`
/// methods because `extract_rust_symbols` flattens them to top level — but
/// MISSED languages where class members stay in the `children` array:
/// Java, Kotlin, Python, TypeScript. This test uses Java, whose parser keeps
/// methods nested under the class.
#[tokio::test]
async fn replace_symbol_rejects_body_only_for_nested_method() {
    let src = "\
class Foo {
    void target() {
        originalBody();
    }
}
";

    let (dir, ctx) = ctx_with_mock(&[("src/Foo.java", src)], |root| {
        let file = root.join("src/Foo.java");
        // LSP reports the method as Foo/target (nested under the class).
        let mut sym = sym_with_range("target", 1, 3, 1, file.clone());
        sym.name_path = "Foo/target".to_string();
        MockLspClient::new().with_symbols(file, vec![sym])
    })
    .await;

    // Pass body-only code — no `void target()` signature.
    let body_only = "        newBody();\n";
    let err = EditCode
        .call(
            json!({
                "path": "src/Foo.java",
                "symbol": "Foo/target",
                "action": "replace",
                "body": body_only
            }),
            &ctx,
        )
        .await
        .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("dropped the symbol definition"),
        "nested method body-only must be caught; got: {msg}"
    );

    // File must be restored.
    let result = std::fs::read_to_string(dir.path().join("src/Foo.java")).unwrap();
    assert_eq!(
        result, src,
        "file must be restored to original after rollback"
    );
}

/// BUG-044 regression: if the LSP reports a child method's `range.end` as
/// overshooting into a sibling method inside the same `impl` block, the
/// symmetric parent clamp alone does not save us — the overshoot stops at the
/// parent's closer but still eats the sibling. The sibling-drop post-write
/// guard compares AST `name_path` sets pre/post-write and rolls back when a
/// sibling vanishes.
///
/// To keep the test deterministic we use a scenario in which `editing_end_line`
/// cannot correct the overshoot via AST: the LSP reports method names that do
/// not appear in the actual source (e.g. post-rename stale data). This leaves
/// the overshooting LSP `range.end` intact and exercises the sibling-drop
/// rollback path directly.
#[tokio::test]
async fn replace_symbol_rolls_back_when_sibling_method_would_be_dropped() {
    let src = "\
struct Foo;

impl Foo {
    fn alpha(&self) -> i32 {
        1
    }

    fn beta(&self) -> i32 {
        2
    }
}
";
    // Line indices (0-based):
    //   0 struct Foo;
    //   1
    //   2 impl Foo {
    //   3     fn alpha(&self) -> i32 {
    //   4         1
    //   5     }
    //   6
    //   7     fn beta(&self) -> i32 {
    //   8         2
    //   9     }
    //  10 }

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // Stale LSP: reports old names (`a`/`b`) that don't match the real source
        // (`alpha`/`beta`). This defeats AST end-line correction, leaving the
        // LSP-reported `range.end` of 9 (overshoot into beta) in place.
        let a = SymbolInfo {
            name: "a".to_string(),
            name_path: "impl Foo/a".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 3,
            end_line: 9, // overshoot — truthful end is 5
            start_col: 4,
            children: vec![],
            range_start_line: Some(3),
            detail: None,
        };
        let b = SymbolInfo {
            name: "b".to_string(),
            name_path: "impl Foo/b".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 7,
            end_line: 9,
            start_col: 4,
            children: vec![],
            range_start_line: Some(7),
            detail: None,
        };
        let impl_block = SymbolInfo {
            name: "impl Foo".to_string(),
            name_path: "impl Foo".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 2,
            end_line: 10,
            start_col: 0,
            children: vec![a, b],
            range_start_line: Some(2),
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![impl_block])
    })
    .await;

    let new_body = "    fn a(&self) -> i32 {\n        99\n    }";
    let err = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "impl Foo/a",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("dropped sibling symbols") || msg.contains("overshot"),
        "sibling-drop error expected; got: {msg}"
    );
    assert!(
        msg.contains("Foo/beta") || msg.contains("Foo/alpha"),
        "error must name the dropped sibling(s); got: {msg}"
    );

    // File must be untouched.
    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert_eq!(
        result, src,
        "file must be restored after sibling-drop rollback"
    );
}

/// BUG-041: `textDocument/didChange` is a fire-and-forget notification, so the
/// LSP may still be reindexing when the next `documentSymbol` query arrives.
/// That query returns stale positions and any write based on them corrupts
/// the file. replace_symbol must detect staleness (name not found in the
/// reported range), fire a fresh `did_change`, and retry — the second fetch
/// sees the fresh positions and the write succeeds.
#[tokio::test]
async fn replace_symbol_retries_on_stale_lsp_positions_until_fresh() {
    let src = "\
fn filler1() { one(); }
fn filler2() { two(); }
fn target() {
    original();
}
";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // Stale: LSP reports target at line 0 (filler1's spot). `target` is
        // not in that range, so validate_symbol_position rejects it as stale.
        let stale = vec![sym_with_range("target", 0, 0, 0, file.clone())];
        // Fresh: LSP caught up; target is on line 2.
        let fresh = vec![sym_with_range("target", 2, 4, 2, file.clone())];
        MockLspClient::new().with_symbols_sequence(file, vec![stale, fresh])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "fn target() {\n    new_body();\n}"
            }),
            &ctx,
        )
        .await
        .expect("retry must recover from a single stale LSP response");

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("new_body()"),
        "edit must apply; got:\n{result}"
    );
    assert!(
        !result.contains("original()"),
        "old body must be gone; got:\n{result}"
    );
}

/// If the LSP keeps returning stale positions across every retry, the tool
/// must surface a RecoverableError — don't silently fall through to a write
/// using stale offsets (which BUG-041 originally did).
#[tokio::test]
async fn replace_symbol_surfaces_stale_error_after_max_retries() {
    let src = "\
fn filler1() { one(); }
fn filler2() { two(); }
fn target() {
    original();
}
";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // Every call returns stale. did_change pops the queue but once a single
        // entry remains it sticks — so retries never see fresh data.
        let stale = vec![sym_with_range("target", 0, 0, 0, file.clone())];
        MockLspClient::new().with_symbols_sequence(file, vec![stale])
    })
    .await;

    let err = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "fn target() {\n    new_body();\n}"
            }),
            &ctx,
        )
        .await
        .unwrap_err();

    let msg = err.to_string();
    assert!(
        msg.contains("stale"),
        "error must still mention staleness when retries are exhausted; got: {msg}"
    );
}

/// Agent changes the attribute: #[test] → #[tokio::test]
#[tokio::test]
async fn replace_symbol_round_trip_agent_changes_attribute() {
    let src = "#[test]\nfn target() {\n    old_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 1, 3, 0, file)])
    })
    .await;

    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    assert!(body.contains("#[test]"), "body should include attribute");

    // Agent changes the attribute AND the body
    let new_body = body
        .replace("#[test]", "#[tokio::test]")
        .replace("old_body()", "new_body()");

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("#[tokio::test]"),
        "new attribute must be present; got:\n{result}"
    );
    assert!(
        !result.contains("\n#[test]\n"),
        "old attribute must be gone; got:\n{result}"
    );
    assert!(
        result.contains("new_body()"),
        "new body must be applied; got:\n{result}"
    );
}

/// Agent modifies the doc comment during a refactor.
#[tokio::test]
async fn replace_symbol_round_trip_agent_changes_doc_comment() {
    let src = "/// Old documentation\nfn target() {\n    old_body();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 1, 3, 0, file)])
    })
    .await;

    let find_result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let body = find_result["symbols"][0]["body"].as_str().unwrap();
    let new_body = body
        .replace(
            "/// Old documentation",
            "/// Updated documentation\n/// With extra detail",
        )
        .replace("old_body()", "new_body()");

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": new_body
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("/// Updated documentation"),
        "new doc must be present; got:\n{result}"
    );
    assert!(
        result.contains("/// With extra detail"),
        "extra doc line must be present; got:\n{result}"
    );
    assert!(
        !result.contains("/// Old documentation"),
        "old doc must be gone; got:\n{result}"
    );
    assert!(
        result.contains("new_body()"),
        "new body must be applied; got:\n{result}"
    );
}

/// R-08 regression: When new_body does NOT contain the doc comment but the
/// symbol has one immediately above, `edit_code(replace)` must preserve the
/// existing doc comment rather than dropping it via the BUG-031 walk-back.
///
/// Surfaced by the edit_code eval (R-08, `replace_doc_adj.rs`). BUG-031's
/// walk-back exists to prevent doc-comment DUPLICATION when the LLM passes
/// a new_body that already contains the doc comment. But when the LLM passes
/// a new_body that intentionally omits the doc comment (e.g. only changing the
/// body), the walk-back dropped the original doc. Fix: detect whether new_body
/// leads with decorators; if not, anchor the replace at the keyword line.
#[tokio::test]
async fn replace_symbol_preserves_doc_when_new_body_has_no_doc_comment() {
    let src = "/// Doc that lives immediately above the target with no blank line.\npub fn documented() -> &'static str {\n    \"before\"\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // range_start_line=1 — rust-analyzer points at the `pub fn` line, skipping the doc.
        MockLspClient::new().with_symbols(
            file.clone(),
            vec![sym_with_range("documented", 1, 3, 1, file)],
        )
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "documented",
                "action": "replace",
                "body": "pub fn documented() -> &'static str {\n    \"after\"\n}",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("/// Doc that lives immediately above"),
        "doc comment must survive replace when new_body omits it; got:\n{result}"
    );
    assert!(
        result.contains("\"after\""),
        "new body must be applied; got:\n{result}"
    );
    assert!(
        !result.contains("\"before\""),
        "old body must be gone; got:\n{result}"
    );
}

#[tokio::test]
async fn insert_code_before_with_range_start_line_inserts_above_attribute() {
    // File layout (0-indexed):
    //  0: "#[test]"                     <- range_start = 0
    //  1: "fn target() {}"              <- selectionRange.start = 1
    let src = "#[test]\nfn target() {}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 1, 1, 0, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "position": "before",
                "action": "insert",
                "body": "// inserted above"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    let lines: Vec<&str> = result.lines().collect();
    assert_eq!(
        lines[0], "// inserted above",
        "inserted code must be above #[test]; got:\n{result}"
    );
    // insert_code(before) adds a blank separator line after the inserted code
    assert_eq!(
        lines[1], "",
        "blank separator line after inserted code; got:\n{result}"
    );
    assert_eq!(
        lines[2], "#[test]",
        "#[test] must follow separator; got:\n{result}"
    );
    assert!(
        lines[3].contains("fn target()"),
        "fn must follow #[test]; got:\n{result}"
    );
}

/// symbols body_start_line field present and correct in integration context.
#[tokio::test]
async fn symbols_body_start_line_field_with_attributes() {
    let src = "#[test]\n/// doc\nfn target() {\n    body();\n}\n";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 2, 4, 0, file)])
    })
    .await;

    let result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": true
            }),
            &ctx,
        )
        .await
        .unwrap();

    let sym = &result["symbols"][0];
    // body_start_line = 1 (1-indexed, the #[test] line)
    assert_eq!(
        sym["body_start_line"].as_u64(),
        Some(1),
        "body_start_line should point to attribute line"
    );
    // start_line = 3 (1-indexed, the fn keyword line)
    assert_eq!(
        sym["start_line"].as_u64(),
        Some(3),
        "start_line should point to fn keyword"
    );
    // body should contain both attribute and fn
    let body = sym["body"].as_str().unwrap();
    assert!(
        body.starts_with("#[test]"),
        "body should start with attribute"
    );
}

#[tokio::test]
async fn symbols_no_body_start_line_without_include_body() {
    // Auto-inline (src/tools/symbol/symbols.rs:560) attaches `body` for small results
    // when `include_body` is not passed. Explicit `include_body=false` opts out of
    // auto-inline via the `include_body_explicit.is_some()` branch — that's the
    // contract this test now pins.
    let src = "#[test]\nfn target() {}\n";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("target", 1, 1, 0, file)])
    })
    .await;

    let result = Symbols
        .call(
            json!({
                "symbol": "target",
                "path": "src/lib.rs",
                "include_body": false
            }),
            &ctx,
        )
        .await
        .unwrap();

    let sym = &result["symbols"][0];
    assert!(
        sym.get("body").is_none(),
        "body should not be present with explicit include_body=false"
    );
    assert!(
        sym.get("body_start_line").is_none(),
        "body_start_line should not be present with explicit include_body=false"
    );
}

// ── BUG-010: insert_code "before" must walk past #[attr] and /// doc lines ────

/// `insert_code(position="before")` targeting a struct with a leading doc comment
/// and `#[derive]` attribute must insert the code BEFORE the `///` comment, not
/// between the attribute and the struct declaration.
#[tokio::test]
async fn insert_code_before_walks_past_attributes_and_doc_comments() {
    // File layout (0-indexed):
    //  0: "/// A useful struct."  <- doc comment
    //  1: "#[derive(Clone)]"      <- attribute
    //  2: "pub struct Foo {"      <- LSP start_line points here
    //  3: "    x: u32,"
    //  4: "}"
    //  5: ""
    //  6: "const SENTINEL: &str = \"survives\";"
    let src = "/// A useful struct.\n#[derive(Clone)]\npub struct Foo {\n    x: u32,\n}\n\nconst SENTINEL: &str = \"survives\";\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // LSP reports start_line=2 (struct declaration), not 0 (doc comment) — BUG-010
        MockLspClient::new().with_symbols(file.clone(), vec![sym("Foo", 2, 4, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "Foo",
                "position": "before",
                "action": "insert",
                "body": "const BEFORE: u32 = 1;\n"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    let before_pos = result.find("BEFORE").unwrap();
    let doc_pos = result.find("/// A useful").unwrap();
    let derive_pos = result.find("#[derive").unwrap();
    assert!(
        before_pos < doc_pos,
        "const must be inserted before the doc comment, got:\n{result}"
    );
    assert!(
        before_pos < derive_pos,
        "const must be inserted before #[derive], got:\n{result}"
    );
    assert!(
        result.contains("const SENTINEL"),
        "sentinel must survive; got:\n{result}"
    );
}

// ── insert_code: trust LSP start/end ─────────────────────────────────────────

/// With "trust LSP", start_line=0 means insert_code(before) inserts at line 0.
/// No lead-in skipping — find_insert_before_line starts from sym.start_line directly.
/// The `}` at line 0 is NOT skipped; insertion lands before everything.
#[tokio::test]
async fn insert_code_before_trusts_lsp_start() {
    // File layout (0-indexed):
    //  0: "    }"          ← LSP says start_line=0 — trust it, insert before line 0
    //  1: ""               ← blank line
    //  2: "    fn target() {"
    //  3: "    }"
    let src = "    }\n\n    fn target() {\n    }\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("target", 0, 3, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "position": "before",
                "action": "insert",
                "body": "    // inserted\n"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("// inserted"),
        "insertion must be present; got:\n{result}"
    );
    // With "trust LSP", insertion at sym.start_line=0 lands before the `}`
    let insert_pos = result.find("// inserted").unwrap();
    let brace_pos = result.find("    }").unwrap();
    assert!(
        insert_pos < brace_pos,
        "with trust LSP, insertion at sym.start_line=0 lands before `}}`; got:\n{result}"
    );
}

/// Normal "after" case: symbol at [0,1], insertion goes after line 1.
#[tokio::test]
async fn insert_code_after_lands_past_symbol() {
    let src = "fn foo() {\n}\n\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("foo", 0, 1, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "foo",
                "position": "after",
                "action": "insert",
                "body": "fn bar() {}\n"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("fn foo()"),
        "original must be present; got:\n{result}"
    );
    assert!(
        result.contains("fn bar()"),
        "insertion must be present; got:\n{result}"
    );
    let foo_pos = result.find("fn foo()").unwrap();
    let bar_pos = result.find("fn bar()").unwrap();
    assert!(
        bar_pos > foo_pos,
        "bar must be inserted after foo; got:\n{result}"
    );
}

/// BUG-023 regression: when LSP over-extends end_line to the next function's opening
/// line, editing_end_line() caps it to the AST-reported end, so insertion lands
/// between the closing `}` and the next function — NOT inside the next function body.
#[tokio::test]
async fn insert_code_after_caps_overextended_lsp_end() {
    // File layout (0-indexed):
    //  0: "fn target() {"
    //  1: "    body();"
    //  2: "}"
    //  3: "fn following() {"   ← LSP over-extends target's end_line to here
    //  4: "    inside();"
    //  5: "}"
    let src = "fn target() {\n    body();\n}\nfn following() {\n    inside();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // LSP reports end_line=3 (over-extended into fn following() { line)
        MockLspClient::new().with_symbols(file.clone(), vec![sym("target", 0, 3, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "position": "after",
                "action": "insert",
                "body": "// inserted\n"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("// inserted"),
        "insertion must be present; got:\n{result}"
    );
    // editing_end_line caps to AST end (line 2 = closing `}`),
    // so insertion goes after line 2 — between `}` and `fn following()`.
    let insert_pos = result.find("// inserted").unwrap();
    let following_fn = result.find("fn following()").unwrap();
    assert!(
        insert_pos < following_fn,
        "insertion should land before fn following(), not inside it; got:\n{result}"
    );
}

/// Regression for docs/issues/2026-06-05-edit-code-insert-after-last-python-method.md:
/// inserting after the LAST child of a dedent-delimited (Python) class spliced the
/// new sibling *before* the method's trailing statement, orphaning it.
///
/// Root cause: Python classes have no closer line, so the parent's `end_line` equals
/// the last child's `end_line`. `do_insert` used `parent.end_line` as an *exclusive*
/// upper bound, which is off by one for inclusive node ends — it clamped
/// `insert_at0` (strict-AST child_end + 1) back to the child's last line. The fix
/// uses `parent.end_line + 1`. Brace languages are unaffected because a child's
/// strict-AST end is always strictly below the parent closer.
#[tokio::test]
async fn insert_code_after_last_python_method_keeps_trailing_stmt() {
    // File layout (0-indexed):
    //  0: "class C:"
    //  1: "    def m(self):"
    //  2: "        x = compute("
    //  3: "            a=1,"
    //  4: "        )"
    //  5: ""                       <- blank line before the trailing statement
    //  6: "        assert x"        <- last stmt of m AND last line of class C
    let src = "class C:\n    def m(self):\n        x = compute(\n            a=1,\n        )\n\n        assert x\n";

    let (dir, ctx) = ctx_with_mock(&[("mod.py", src)], |root| {
        let file = root.join("mod.py");
        // Parent class and its single method share end_line=6 (no closer line).
        let method = SymbolInfo {
            name: "m".to_string(),
            name_path: "C/m".to_string(),
            kind: SymbolKind::Method,
            file: file.clone(),
            start_line: 1,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        };
        let class = SymbolInfo {
            name: "C".to_string(),
            name_path: "C".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 6,
            start_col: 0,
            children: vec![method],
            range_start_line: None,
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![class])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "mod.py",
                "symbol": "C/m",
                "position": "after",
                "action": "insert",
                "body": "\n    def added(self):\n        assert added_marker\n"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("mod.py")).unwrap();
    let assert_pos = result
        .find("assert x")
        .unwrap_or_else(|| panic!("trailing `assert x` vanished; got:\n{result}"));
    let added_pos = result
        .find("def added")
        .unwrap_or_else(|| panic!("inserted method missing; got:\n{result}"));
    // The trailing statement must stay INSIDE m — i.e. before the new sibling.
    assert!(
        assert_pos < added_pos,
        "trailing `assert x` must remain in method `m`, not leak past the inserted \
         method; got:\n{result}"
    );
}

/// Companion to insert: `replace` of the LAST child of a Python class must replace the
/// WHOLE method, including its trailing statement. The same `parent.end_line` off-by-one
/// in `do_replace`'s `clamp_range_to_parent` call dropped the last line from the replaced
/// range, leaving the old trailing statement orphaned after the new body.
/// docs/issues/2026-06-05-edit-code-insert-after-last-python-method.md
#[tokio::test]
async fn replace_last_python_method_replaces_trailing_stmt() {
    // 0: "class C:"
    // 1: "    def m(self):"
    // 2: "        x = compute("
    // 3: "            a=1,"
    // 4: "        )"
    // 5: ""
    // 6: "        assert x"   <- last stmt of m AND last line of class C
    let src = "class C:\n    def m(self):\n        x = compute(\n            a=1,\n        )\n\n        assert x\n";

    let (dir, ctx) = ctx_with_mock(&[("mod.py", src)], |root| {
        let file = root.join("mod.py");
        let method = SymbolInfo {
            name: "m".to_string(),
            name_path: "C/m".to_string(),
            kind: SymbolKind::Method,
            file: file.clone(),
            start_line: 1,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        };
        let class = SymbolInfo {
            name: "C".to_string(),
            name_path: "C".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 6,
            start_col: 0,
            children: vec![method],
            range_start_line: None,
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![class])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "mod.py",
                "symbol": "C/m",
                "action": "replace",
                "body": "    def m(self):\n        return 42"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("mod.py")).unwrap();
    assert!(
        result.contains("return 42"),
        "new body must be present; got:\n{result}"
    );
    // The old trailing statement was part of `m` and must be replaced, not orphaned.
    assert!(
        !result.contains("assert x"),
        "old trailing `assert x` must be replaced with the rest of m, not left behind; got:\n{result}"
    );
}

/// Companion to insert: `remove` of the LAST child of a Python class must remove the
/// WHOLE method, including its trailing statement. Same off-by-one in `do_remove`.
/// docs/issues/2026-06-05-edit-code-insert-after-last-python-method.md
#[tokio::test]
async fn remove_last_python_method_removes_trailing_stmt() {
    let src = "class C:\n    def m(self):\n        x = compute(\n            a=1,\n        )\n\n        assert x\n";

    let (dir, ctx) = ctx_with_mock(&[("mod.py", src)], |root| {
        let file = root.join("mod.py");
        let method = SymbolInfo {
            name: "m".to_string(),
            name_path: "C/m".to_string(),
            kind: SymbolKind::Method,
            file: file.clone(),
            start_line: 1,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        };
        let class = SymbolInfo {
            name: "C".to_string(),
            name_path: "C".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 6,
            start_col: 0,
            children: vec![method],
            range_start_line: None,
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![class])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "mod.py",
                "symbol": "C/m",
                "action": "remove"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("mod.py")).unwrap();
    assert!(
        !result.contains("def m"),
        "method `m` must be fully removed; got:\n{result}"
    );
    // The trailing statement belonged to m and must go with it.
    assert!(
        !result.contains("assert x"),
        "trailing `assert x` must be removed with its method, not orphaned; got:\n{result}"
    );
}

/// BUG-016 regression: insert_code(after) on a nested `mod tests` function
/// where LSP reports end_line as a line *inside* the body (truncated range).
/// validate_symbol_range catches ast_end > sym.end_line and returns
/// RecoverableError — the file is never corrupted.
#[tokio::test]
async fn insert_code_after_rejects_truncated_end_in_nested_fn() {
    // File layout (0-indexed):
    //  0: "#[cfg(test)]"
    //  1: "mod tests {"
    //  2: "    #[test]"
    //  3: "    fn target_test() {"
    //  4: "        let x = 1;"         <- LSP (wrongly) reports end_line here
    //  5: "        assert_eq!(x, 1);"
    //  6: "    }"                       <- true end (AST knows this)
    //  7: "}"
    let src =
        "#[cfg(test)]\nmod tests {\n    #[test]\n    fn target_test() {\n        let x = 1;\n        assert_eq!(x, 1);\n    }\n}\n";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // LSP reports end_line=4 (inside the body), not 6 (closing `}`)
        let inner = SymbolInfo {
            name: "target_test".to_string(),
            name_path: "tests/target_test".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 3,
            end_line: 4, // truncated — true end is line 6
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        };
        let module = SymbolInfo {
            name: "tests".to_string(),
            name_path: "tests".to_string(),
            kind: SymbolKind::Module,
            file: file.clone(),
            start_line: 1,
            end_line: 7,
            start_col: 0,
            children: vec![inner],
            range_start_line: None,
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![module])
    })
    .await;

    let result = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "tests/target_test",
                "position": "after",
                "action": "insert",
                "body": "    #[test]\n    fn new_test() {}\n"
            }),
            &ctx,
        )
        .await;

    // validate_symbol_range must catch ast_end (6) > sym.end_line (4)
    // and return RecoverableError — not silently insert mid-body
    let err = result.expect_err("should fail with RecoverableError for truncated end_line");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("suspicious range"),
        "error should mention suspicious range; got: {msg}"
    );
}

/// Regression for the strict-refuse path on `insert_code(position="after")`.
///
/// Scenario: LSP reports a stale name (`a` instead of the AST's `alpha`) so
/// `editing_end_line_strict` returns None. Before fix `201dcb5b`, a parented
/// symbol would silently fall back to LSP's overshoot and then rely on the
/// parent clamp — but the clamp only catches *over*-extension, not
/// *under*-extension into the same body. The fix removes that fallback;
/// insert-after now refuses with a RecoverableError naming the workarounds.
#[tokio::test]
async fn insert_code_after_refuses_when_ast_cannot_pin_symbol_end() {
    let src = "\
struct Foo;

impl Foo {
    fn alpha(&self) {}
}
";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let alpha = SymbolInfo {
            name: "a".to_string(),
            name_path: "impl Foo/a".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 3,
            end_line: 10,
            start_col: 4,
            children: vec![],
            range_start_line: Some(3),
            detail: None,
        };
        let impl_block = SymbolInfo {
            name: "impl Foo".to_string(),
            name_path: "impl Foo".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 2,
            end_line: 4,
            start_col: 0,
            children: vec![alpha],
            range_start_line: Some(2),
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![impl_block])
    })
    .await;

    let err = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "impl Foo/a",
                "position": "after",
                "action": "insert",
                "body": "    fn beta(&self) {}\n"
            }),
            &ctx,
        )
        .await
        .expect_err("insert-after must refuse when AST cannot pin the symbol's end");

    let msg = err.to_string();
    assert!(
        msg.contains("cannot determine end") && msg.contains("AST parse failed"),
        "error must explain why it refused; got: {msg}"
    );

    let unchanged = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert_eq!(
        unchanged, src,
        "refused insert-after must leave the file unchanged"
    );
}

/// BUG-051 residual: a top-level symbol with no parent has no clamp safety net,
/// so when AST cannot pinpoint its end (broken parse, ambiguous match, etc.)
/// `do_insert` "after" must refuse rather than fall back to LSP's
/// possibly-corrupted `end_line` and risk splicing new code mid-function.
#[tokio::test]
async fn insert_code_after_refuses_when_ast_fails_and_no_parent_clamp() {
    let src = "\
fn alpha() {
    println!(\"hello\");
}
";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // Top-level fn with a name AST can't match. No parent in the symbol
        // tree, so the parent clamp cannot recover.
        let alpha = SymbolInfo {
            name: "a".to_string(),
            name_path: "a".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 0,
            end_line: 1, // suspiciously short — under-extension scenario
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![alpha])
    })
    .await;

    let result = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "a",
                "position": "after",
                "action": "insert",
                "body": "fn beta() {}\n"
            }),
            &ctx,
        )
        .await;

    let err = result.expect_err("must refuse when AST fails and no parent clamp is available");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("AST parse failed") || msg.contains("cannot determine end"),
        "error should explain AST failure; got: {msg}"
    );
}

// ── remove_symbol: trust LSP ranges ──────────────────────────────────────────

/// BUG-024 regression (remove_symbol): when LSP over-extends `end_line` to include a
/// sibling `const`, editing_end_line() caps to the AST-reported end so the const survives.
#[tokio::test]
async fn remove_symbol_caps_overextended_lsp_end() {
    // File layout (0-indexed):
    //  0: "fn target() {"
    //  1: "    // body"
    //  2: "}"
    //  3: "const SENTINEL: &str = \"survives\";"  <- LSP over-extends end_line here
    let src = "fn target() {\n    // body\n}\nconst SENTINEL: &str = \"survives\";\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // LSP reports end_line=3 (over-extended to const line — true end is line 2)
        MockLspClient::new().with_symbols(file.clone(), vec![sym("target", 0, 3, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "remove"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        !result.contains("fn target"),
        "function must be removed; got:\n{result}"
    );
    // editing_end_line caps to AST end (line 2) — SENTINEL is outside the range and survives
    assert!(
        result.contains("SENTINEL"),
        "SENTINEL must survive — it is outside the true symbol range; got:\n{result}"
    );
}

/// When `range_start_line` is set (documentSymbol path), remove_symbol uses it
/// to include attributes and doc comments in the removal range.
#[tokio::test]
async fn remove_symbol_uses_range_start_line_to_include_doc_comment() {
    // File layout (0-indexed):
    //  0: "fn preceding() {"
    //  1: "    // body"
    //  2: "}"
    //  3: "use std::fmt;"
    //  4: ""                                   <- blank line
    //  5: "/// A constant."                    <- range.start = 5
    //  6: "const TARGET: bool = false;"        <- selectionRange.start = 6, end = 6
    //  7: "fn following() {}"
    let src = "fn preceding() {\n    // body\n}\nuse std::fmt;\n\n/// A constant.\nconst TARGET: bool = false;\nfn following() {}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // range_start=5 includes the doc comment
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("TARGET", 6, 6, 5, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "TARGET",
                "action": "remove"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        !result.contains("TARGET"),
        "const must be removed; got:\n{result}"
    );
    assert!(
        !result.contains("A constant"),
        "doc comment included in range_start_line — must also be removed; got:\n{result}"
    );
    assert!(
        result.contains("fn preceding()"),
        "preceding function must survive; got:\n{result}"
    );
    assert!(
        result.contains("fn following()"),
        "following function must survive; got:\n{result}"
    );
    let use_count = result.matches("use std::fmt;").count();
    assert_eq!(
        use_count, 1,
        "use import must not be duplicated; found {use_count} occurrences in:\n{result}"
    );
}

/// When `range_start_line` is `None` (workspace/symbol or tree-sitter), the
/// heuristic fallback walks backwards past doc comments and attributes.
#[tokio::test]
async fn remove_symbol_heuristic_fallback_includes_doc_comment() {
    let src = "fn preceding() {\n    // body\n}\nuse std::fmt;\n\n/// A constant.\nconst TARGET: bool = false;\nfn following() {}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // No range_start_line — triggers heuristic fallback
        MockLspClient::new().with_symbols(file.clone(), vec![sym("TARGET", 6, 6, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "TARGET",
                "action": "remove"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        !result.contains("TARGET"),
        "const must be removed; got:\n{result}"
    );
    assert!(
        !result.contains("A constant"),
        "heuristic should walk back past doc comment; got:\n{result}"
    );
    assert!(
        result.contains("fn preceding()"),
        "preceding function must survive; got:\n{result}"
    );
    assert!(
        result.contains("fn following()"),
        "following function must survive; got:\n{result}"
    );
}

/// When `range_start_line` explicitly excludes the doc comment, but doc comments
/// exist directly above, editing_start_line walks back to include them (BUG-031 fix).
/// Orphaned doc comments after symbol removal are worse than removing them.
#[tokio::test]
async fn remove_symbol_range_start_line_excludes_doc_comment() {
    let src = "fn preceding() {\n    // body\n}\nuse std::fmt;\n\n/// A constant.\nconst TARGET: bool = false;\nfn following() {}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // range_start=6 (same as selectionRange) — LSP explicitly says no doc comment
        MockLspClient::new()
            .with_symbols(file.clone(), vec![sym_with_range("TARGET", 6, 6, 6, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "TARGET",
                "action": "remove"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        !result.contains("TARGET"),
        "const must be removed; got:\n{result}"
    );
    // BUG-031 fix: editing_start_line now walks back past `///` doc comments
    // even when range_start_line points to the keyword line. This prevents
    // orphaned doc comments and fixes replace_symbol duplication.
    assert!(
        !result.contains("A constant"),
        "doc comment should also be removed (BUG-031 fix); got:\n{result}"
    );
}

// ── symbols: name_path exact match (BUG-011) ──────────────────────────────

/// Searching by name_path must return only the exact symbol, not child symbols
/// whose name_path happens to contain the query as a substring.
///
/// Regression for BUG-011: `collect_matching` used `contains()`, so a Variable
/// child with name_path "my_fn/local_var" matched a query for "my_fn".
#[tokio::test]
async fn symbols_name_path_does_not_return_local_variable_children() {
    use codescout::lsp::SymbolKind;

    let src = "fn my_fn() {\n    let local_var = 1;\n}\n";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let child = SymbolInfo {
            name: "local_var".to_string(),
            name_path: "my_fn/local_var".to_string(),
            kind: SymbolKind::Variable,
            file: file.clone(),
            start_line: 1,
            end_line: 1,
            start_col: 4,
            children: vec![],
            range_start_line: None,
            detail: None,
        };
        let parent = SymbolInfo {
            name: "my_fn".to_string(),
            name_path: "my_fn".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 0,
            end_line: 2,
            start_col: 0,
            children: vec![child],
            range_start_line: None,
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

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

    let symbols = result["symbols"].as_array().unwrap();
    assert_eq!(
        symbols.len(),
        1,
        "name_path lookup must return exactly the matching symbol, not its Variable children; got: {symbols:?}"
    );
    assert_eq!(symbols[0]["name"], "my_fn");
}

// ── symbol_at def: no-identifier fallback (BUG-012) ───────────────────────────

/// When `identifier` is omitted, `symbol_at` (def) must use the first
/// non-whitespace column of the line, not error with "identifier not found".
///
/// Regression for BUG-012: the old code called `str::find(ident)` which returned
/// `None` for nearly every call, causing a 100% error rate.
#[tokio::test]
async fn symbol_at_def_unknown_identifier_falls_back_to_first_nonwhitespace() {
    // Line 0 (1-indexed: line 1) has 4 spaces of indent before "let".
    // First non-whitespace column = 4.
    let src = "    let foo = 1;\n";

    let (_dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let def_path = root.join("src/lib.rs");
        // Configure a definition at exactly (line=0, col=4) — the expected column.
        // If the tool uses any other column (e.g. 0), the mock returns [] and
        // the tool fails with "no definition found" instead of the expected result.
        MockLspClient::new().with_definitions(
            0,
            4,
            vec![lsp_types::Location {
                uri: url::Url::from_file_path(&def_path)
                    .unwrap()
                    .as_str()
                    .parse()
                    .unwrap(),
                range: lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 4,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 7,
                    },
                },
            }],
        )
    })
    .await;

    let result = SymbolAt
        .call(
            json!({
                "path": "src/lib.rs",
                "line": 1,
                "fields": ["def"]
                // no "identifier" — must fall back to first-nonwhitespace column
            }),
            &ctx,
        )
        .await
        .expect("should succeed: omitting identifier must not cause 'identifier not found'");

    let defs = result["def"]["definitions"].as_array().unwrap();
    assert_eq!(
        defs.len(),
        1,
        "mock should return the pre-configured definition at col=4; \
         if col is wrong the mock returns [] and the tool errors instead"
    );
}

// ── replace_symbol: language-agnostic (BUG-019 regression) ───────────────────
//
// The old `is_valid_symbol_start_line` guard had a Rust-only keyword allowlist
// (`fn `, `pub `, `struct `, `impl `, …). Any LSP start_line whose content did not
// match was rejected as "symbol location appears stale", breaking replace_symbol
// for every non-Rust language.
//
// Fix: the guard was removed. `validate_symbol_range` (AST cross-check) is the
// canonical staleness defense and is language-agnostic.
//
// Each test below is a sandwich regression:
//   Baseline  — Rust `fn` continues to work (covered by replace_symbol_clean_start_line).
//   Stale     — the language's function keyword was NOT in the old Rust allowlist, so
//               is_valid_symbol_start_line would have returned false and EditCode
//               would have returned Err("symbol location appears stale").
//   Fixed     — ReplaceSymbol now succeeds and the new body appears in the file.

/// Python: `def` was not in the Rust keyword allowlist → old code rejected it.
#[tokio::test]
async fn replace_symbol_works_for_python() {
    // 0: "def greet():"
    // 1: "    return 'old'"
    let src = "def greet():\n    return 'old'\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.py", src)], |root| {
        let file = root.join("greet.py");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 1, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.py", "symbol": "greet",
                    "action": "replace",
                "body": "def greet():\n    return 'new'" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.py")).unwrap();
    assert!(
        result.contains("'new'"),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("'old'"),
        "old body must be gone; got:\n{result}"
    );
}

/// TypeScript: `function` was not in the Rust keyword allowlist → old code rejected it.
#[tokio::test]
async fn replace_symbol_works_for_typescript() {
    // 0: "function greet(): string {"
    // 1: "    return 'old';"
    // 2: "}"
    let src = "function greet(): string {\n    return 'old';\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.ts", src)], |root| {
        let file = root.join("greet.ts");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.ts", "symbol": "greet",
                    "action": "replace",
                "body": "function greet(): string {\n    return 'new';\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.ts")).unwrap();
    assert!(
        result.contains("'new'"),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("'old'"),
        "old body must be gone; got:\n{result}"
    );
}

/// JavaScript: `function` keyword → same Rust-allowlist rejection as TypeScript.
#[tokio::test]
async fn replace_symbol_works_for_javascript() {
    let src = "function greet() {\n    return 'old';\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.js", src)], |root| {
        let file = root.join("greet.js");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.js", "symbol": "greet",
                    "action": "replace",
                "body": "function greet() {\n    return 'new';\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.js")).unwrap();
    assert!(
        result.contains("'new'"),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("'old'"),
        "old body must be gone; got:\n{result}"
    );
}

/// Go: `func` was not in the Rust keyword allowlist → old code rejected it.
#[tokio::test]
async fn replace_symbol_works_for_go() {
    let src = "func Greet() string {\n\treturn \"old\"\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.go", src)], |root| {
        let file = root.join("greet.go");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("Greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.go", "symbol": "Greet",
                    "action": "replace",
                "body": "func Greet() string {\n\treturn \"new\"\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.go")).unwrap();
    assert!(
        result.contains("\"new\""),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("\"old\""),
        "old body must be gone; got:\n{result}"
    );
}

/// Java: `public` at the start of a method was not in the allowlist → rejected.
/// (Note: `pub ` and `pub(` were in the allowlist but not `public `.)
#[tokio::test]
async fn replace_symbol_works_for_java() {
    let src = "public String greet() {\n    return \"old\";\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("Greet.java", src)], |root| {
        let file = root.join("Greet.java");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "Greet.java", "symbol": "greet",
                    "action": "replace",
                "body": "public String greet() {\n    return \"new\";\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("Greet.java")).unwrap();
    assert!(
        result.contains("\"new\""),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("\"old\""),
        "old body must be gone; got:\n{result}"
    );
}

/// Kotlin: `fun` was not in the Rust keyword allowlist → old code rejected it.
#[tokio::test]
async fn replace_symbol_works_for_kotlin() {
    let src = "fun greet(): String {\n    return \"old\"\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("Greet.kt", src)], |root| {
        let file = root.join("Greet.kt");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "Greet.kt", "symbol": "greet",
                    "action": "replace",
                "body": "fun greet(): String {\n    return \"new\"\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("Greet.kt")).unwrap();
    assert!(
        result.contains("\"new\""),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("\"old\""),
        "old body must be gone; got:\n{result}"
    );
}

/// C: return-type-first signatures were not in the Rust keyword allowlist → rejected.
#[tokio::test]
async fn replace_symbol_works_for_c() {
    let src = "int greet() {\n    return 0;\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.c", src)], |root| {
        let file = root.join("greet.c");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.c", "symbol": "greet",
                    "action": "replace",
                "body": "int greet() {\n    return 1;\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.c")).unwrap();
    assert!(
        result.contains("return 1"),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("return 0"),
        "old body must be gone; got:\n{result}"
    );
}

/// C++: same as C — return-type-first → rejected by old allowlist.
#[tokio::test]
async fn replace_symbol_works_for_cpp() {
    let src = "std::string greet() {\n    return \"old\";\n}\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.cpp", src)], |root| {
        let file = root.join("greet.cpp");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.cpp", "symbol": "greet",
                    "action": "replace",
                "body": "std::string greet() {\n    return \"new\";\n}" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.cpp")).unwrap();
    assert!(
        result.contains("\"new\""),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("\"old\""),
        "old body must be gone; got:\n{result}"
    );
}

/// Ruby: `def` (without parens) was not in the Rust keyword allowlist → rejected.
#[tokio::test]
async fn replace_symbol_works_for_ruby() {
    // Ruby methods end with `end`, not `}`
    // 0: "def greet"
    // 1: "  'old'"
    // 2: "end"
    let src = "def greet\n  'old'\nend\n";
    let (dir, ctx) = ctx_with_mock(&[("greet.rb", src)], |root| {
        let file = root.join("greet.rb");
        MockLspClient::new().with_symbols(file.clone(), vec![sym("greet", 0, 2, file)])
    })
    .await;

    EditCode
        .call(
            json!({ "path": "greet.rb", "symbol": "greet",
                    "action": "replace",
                "body": "def greet\n  'new'\nend" }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("greet.rb")).unwrap();
    assert!(
        result.contains("'new'"),
        "new body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("'old'"),
        "old body must be gone; got:\n{result}"
    );
}

/// BUG-024 regression: replace_symbol with over-extended LSP end range must not
/// consume the next function's opening line.
#[tokio::test]
async fn replace_symbol_caps_overextended_lsp_end() {
    // File layout (0-indexed):
    //  0: "fn target() {"
    //  1: "    old_body();"
    //  2: "}"
    //  3: "fn following() {"   <- LSP over-extends target's end_line to here
    //  4: "    inside();"
    //  5: "}"
    let src = "fn target() {\n    old_body();\n}\nfn following() {\n    inside();\n}\n";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // LSP reports end_line=3 (over-extended — true end is line 2)
        MockLspClient::new().with_symbols(file.clone(), vec![sym("target", 0, 3, file)])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "target",
                "action": "replace",
                "body": "fn target() {\n    new_body();\n}"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        result.contains("fn following()"),
        "fn following() must still be present; got:\n{result}"
    );
    assert!(
        result.contains("new_body()"),
        "replacement body must be present; got:\n{result}"
    );
    assert!(
        !result.contains("old_body()"),
        "old body must be gone; got:\n{result}"
    );
    // fn following() must appear after the replacement, not be eaten by it
    let replaced_pos = result.find("new_body()").unwrap();
    let following_pos = result.find("fn following()").unwrap();
    assert!(
        following_pos > replaced_pos,
        "fn following() must come after replacement; got:\n{result}"
    );
}

/// BUG-034 reproduction: replace_symbol on the first child inside `mod tests`
/// must NOT eat the parent's `#[cfg(test)]\nmod tests {` header, even when the
/// LSP reports a stale `range_start_line` that points to the parent's attribute.
#[tokio::test]
async fn replace_symbol_child_in_mod_tests_preserves_module_header() {
    // File layout (0-indexed):
    //  0: "#[cfg(test)]"               <- parent range_start = 0
    //  1: "mod tests {"                <- parent start_line = 1
    //  2: "    #[test]"                <- child range_start SHOULD be 2, but stale LSP says 0
    //  3: "    fn first_test() {"      <- child start_line = 3
    //  4: "        assert!(true);"
    //  5: "    }"                      <- child end = 5
    //  6: ""
    //  7: "    #[test]"
    //  8: "    fn second_test() {"
    //  9: "        assert!(false);"
    // 10: "    }"
    // 11: "}"
    let src = "\
#[cfg(test)]
mod tests {
    #[test]
    fn first_test() {
        assert!(true);
    }

    #[test]
    fn second_test() {
        assert!(false);
    }
}
";

    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        // Parent: mod tests — range starts at #[cfg(test)] (line 0), keyword at line 1
        let mut parent = SymbolInfo {
            name: "tests".to_string(),
            name_path: "tests".to_string(),
            kind: SymbolKind::Module,
            file: file.clone(),
            start_line: 1,
            end_line: 11,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        // Child: first_test — stale LSP reports range_start_line = 0 (#[cfg(test)])
        // instead of the correct 2 (#[test])
        let child1 = SymbolInfo {
            name: "first_test".to_string(),
            name_path: "tests/first_test".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 3,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // BUG: stale, points to parent's #[cfg(test)]
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "second_test".to_string(),
            name_path: "tests/second_test".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 8,
            end_line: 10,
            start_col: 4,
            children: vec![],
            range_start_line: Some(7),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    // Replace first_test with a new body
    let new_body = "    #[test]\n    fn first_test() {\n        assert_eq!(1, 1);\n    }";
    let result = EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "tests/first_test",
                "action": "replace",
                "body": new_body,
            }),
            &ctx,
        )
        .await
        .unwrap();

    // Verify the module header is preserved
    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("#[cfg(test)]"),
        "BUG-034: #[cfg(test)] must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("mod tests {"),
        "BUG-034: mod tests {{ must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("assert_eq!(1, 1)"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("second_test"),
        "second_test must be preserved; got:\n{content}"
    );

    // Verify replaced_lines doesn't extend into module header
    let replaced = result["replaced_lines"].as_str().unwrap();
    let start_line: usize = replaced.split('-').next().unwrap().parse().unwrap();
    assert!(
        start_line >= 3, // 1-indexed: line 3 = #[test] for first_test
        "BUG-034: replaced_lines should start at or after #[test] (line 3), got: {replaced}"
    );
}

// ── BUG-034 guard: cross-language integration tests ──────────────────────────

/// BUG-034 guard: Rust child in `impl` block with stale range_start_line.
/// The guard must prevent eating `impl Foo {` when the child's range is stale.
#[tokio::test]
async fn bug034_guard_rust_child_in_impl_block_stale_range() {
    let src = "\
impl Foo {
    /// Does something.
    fn method(&self) {
        old_body();
    }

    fn other(&self) {}
}
";
    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let mut parent = SymbolInfo {
            name: "Foo".to_string(),
            name_path: "Foo".to_string(),
            kind: SymbolKind::Object,
            file: file.clone(),
            start_line: 0,
            end_line: 7,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        // Stale: range_start_line=0 (impl Foo line) instead of correct 1 (/// doc)
        let child1 = SymbolInfo {
            name: "method".to_string(),
            name_path: "Foo/method".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 2,
            end_line: 4,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // stale — points to parent's impl line
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "other".to_string(),
            name_path: "Foo/other".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 6,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: Some(6),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "Foo/method",
                "action": "replace",
                "body": "    /// Does something.\n    fn method(&self) {\n        new_body();\n    }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("impl Foo {"),
        "impl Foo {{ must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("new_body()"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("fn other"),
        "sibling must be preserved; got:\n{content}"
    );
}

/// BUG-034 guard: Rust child in `impl` with CORRECT range — verify no over-clamping.
#[tokio::test]
async fn bug034_guard_rust_impl_correct_range_no_overclamping() {
    let src = "\
impl Foo {
    /// A doc comment.
    #[inline]
    fn method(&self) {
        old_body();
    }
}
";
    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let mut parent = SymbolInfo {
            name: "Foo".to_string(),
            name_path: "Foo".to_string(),
            kind: SymbolKind::Object,
            file: file.clone(),
            start_line: 0,
            end_line: 6,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        // Correct range: points to doc comment
        let child = SymbolInfo {
            name: "method".to_string(),
            name_path: "Foo/method".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 3,
            end_line: 5,
            start_col: 4,
            children: vec![],
            range_start_line: Some(1), // correct — points to `/// A doc comment.`
            detail: None,
        };
        parent.children = vec![child];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "Foo/method",
                "action": "replace",
                "body": "    /// Updated doc.\n    #[inline]\n    fn method(&self) {\n        new_body();\n    }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("impl Foo {"),
        "impl header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("Updated doc"),
        "new doc comment must be present; got:\n{content}"
    );
    assert!(
        !content.contains("A doc comment"),
        "old doc comment must be replaced; got:\n{content}"
    );
}

/// BUG-034 guard: Python decorated method in class with stale range.
#[tokio::test]
async fn bug034_guard_python_decorated_method_stale_range() {
    let src = "\
class MyService:
    @staticmethod
    def handle(request):
        return old_response()

    def other(self):
        pass
";
    let (dir, ctx) = ctx_with_mock(&[("service.py", src)], |root| {
        let file = root.join("service.py");
        let mut parent = SymbolInfo {
            name: "MyService".to_string(),
            name_path: "MyService".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 6,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        // Stale: range_start_line=0 (class line) instead of correct 1 (@staticmethod)
        let child1 = SymbolInfo {
            name: "handle".to_string(),
            name_path: "MyService/handle".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 2,
            end_line: 3,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // stale
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "other".to_string(),
            name_path: "MyService/other".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 5,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: Some(5),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "service.py",
                "symbol": "MyService/handle",
                "action": "replace",
                "body": "    @staticmethod\n    def handle(request):\n        return new_response()",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("service.py")).unwrap();
    assert!(
        content.contains("class MyService:"),
        "class header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("new_response()"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("def other"),
        "sibling must be preserved; got:\n{content}"
    );
}

/// BUG-034 guard: TypeScript method in class with stale range.
#[tokio::test]
async fn bug034_guard_typescript_method_stale_range() {
    let src = "\
export class UserService {
    private validate(input: string): boolean {
        return false;
    }

    public greet(): string {
        return 'hello';
    }
}
";
    let (dir, ctx) = ctx_with_mock(&[("service.ts", src)], |root| {
        let file = root.join("service.ts");
        let mut parent = SymbolInfo {
            name: "UserService".to_string(),
            name_path: "UserService".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 8,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        let child1 = SymbolInfo {
            name: "validate".to_string(),
            name_path: "UserService/validate".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 1,
            end_line: 3,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // stale — points to class declaration
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "greet".to_string(),
            name_path: "UserService/greet".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 5,
            end_line: 7,
            start_col: 4,
            children: vec![],
            range_start_line: Some(5),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "service.ts",
                "symbol": "UserService/validate",
                "action": "replace",
                "body": "    private validate(input: string): boolean {\n        return true;\n    }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("service.ts")).unwrap();
    assert!(
        content.contains("export class UserService {"),
        "class header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("return true"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("public greet"),
        "sibling must be preserved; got:\n{content}"
    );
}

/// BUG-034 guard: Java annotated method in class with stale range.
#[tokio::test]
async fn bug034_guard_java_annotated_method_stale_range() {
    let src = "\
public class Handler {
    @Override
    public void process(Request req) {
        oldLogic();
    }

    public void other() {}
}
";
    let (dir, ctx) = ctx_with_mock(&[("Handler.java", src)], |root| {
        let file = root.join("Handler.java");
        let mut parent = SymbolInfo {
            name: "Handler".to_string(),
            name_path: "Handler".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 7,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        let child1 = SymbolInfo {
            name: "process".to_string(),
            name_path: "Handler/process".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 2,
            end_line: 4,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // stale — points to class declaration
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "other".to_string(),
            name_path: "Handler/other".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 6,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: Some(6),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "Handler.java",
                "symbol": "Handler/process",
                "action": "replace",
                "body": "    @Override\n    public void process(Request req) {\n        newLogic();\n    }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("Handler.java")).unwrap();
    assert!(
        content.contains("public class Handler {"),
        "class header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("newLogic()"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("public void other"),
        "sibling must be preserved; got:\n{content}"
    );
}

/// BUG-034 guard: Kotlin annotated method in class with stale range.
#[tokio::test]
async fn bug034_guard_kotlin_annotated_method_stale_range() {
    let src = "\
class Repository {
    @Throws(IOException::class)
    fun load(id: String): Data {
        return oldLoad(id)
    }

    fun save(data: Data) {}
}
";
    let (dir, ctx) = ctx_with_mock(&[("Repository.kt", src)], |root| {
        let file = root.join("Repository.kt");
        let mut parent = SymbolInfo {
            name: "Repository".to_string(),
            name_path: "Repository".to_string(),
            kind: SymbolKind::Class,
            file: file.clone(),
            start_line: 0,
            end_line: 7,
            start_col: 0,
            children: vec![],
            range_start_line: Some(0),
            detail: None,
        };
        let child1 = SymbolInfo {
            name: "load".to_string(),
            name_path: "Repository/load".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 2,
            end_line: 4,
            start_col: 4,
            children: vec![],
            range_start_line: Some(0), // stale
            detail: None,
        };
        let child2 = SymbolInfo {
            name: "save".to_string(),
            name_path: "Repository/save".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 6,
            end_line: 6,
            start_col: 4,
            children: vec![],
            range_start_line: Some(6),
            detail: None,
        };
        parent.children = vec![child1, child2];
        MockLspClient::new().with_symbols(file, vec![parent])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "Repository.kt",
                "symbol": "Repository/load",
                "action": "replace",
                "body": "    @Throws(IOException::class)\n    fun load(id: String): Data {\n        return newLoad(id)\n    }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("Repository.kt")).unwrap();
    assert!(
        content.contains("class Repository {"),
        "class header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("newLoad(id)"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        content.contains("fun save"),
        "sibling must be preserved; got:\n{content}"
    );
}

/// BUG-034 guard: deeply nested Rust — fn inside impl inside mod.
/// The guard should find the IMMEDIATE parent (impl), not the grandparent (mod).
#[tokio::test]
async fn bug034_guard_rust_deeply_nested_fn_in_impl_in_mod() {
    let src = "\
mod inner {
    pub struct Bar;

    impl Bar {
        pub fn do_thing(&self) {
            old();
        }
    }
}
";
    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let method = SymbolInfo {
            name: "do_thing".to_string(),
            name_path: "inner/Bar/do_thing".to_string(),
            kind: SymbolKind::Function,
            file: file.clone(),
            start_line: 4,
            end_line: 6,
            start_col: 8,
            children: vec![],
            range_start_line: Some(0), // extremely stale — points to `mod inner`
            detail: None,
        };
        let impl_block = SymbolInfo {
            name: "Bar".to_string(),
            name_path: "inner/Bar".to_string(),
            kind: SymbolKind::Object,
            file: file.clone(),
            start_line: 3,
            end_line: 7,
            start_col: 4,
            children: vec![method],
            range_start_line: Some(3),
            detail: None,
        };
        let struct_sym = SymbolInfo {
            name: "Bar".to_string(),
            name_path: "inner/Bar".to_string(),
            kind: SymbolKind::Struct,
            file: file.clone(),
            start_line: 1,
            end_line: 1,
            start_col: 4,
            children: vec![],
            range_start_line: Some(1),
            detail: None,
        };
        let module = SymbolInfo {
            name: "inner".to_string(),
            name_path: "inner".to_string(),
            kind: SymbolKind::Module,
            file: file.clone(),
            start_line: 0,
            end_line: 8,
            start_col: 0,
            children: vec![struct_sym, impl_block],
            range_start_line: Some(0),
            detail: None,
        };
        MockLspClient::new().with_symbols(file, vec![module])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "inner/Bar/do_thing",
                "action": "replace",
                "body": "        pub fn do_thing(&self) {\n            new();\n        }",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("mod inner {"),
        "module header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("impl Bar {"),
        "impl header must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("new()"),
        "new body must be applied; got:\n{content}"
    );
}

/// BUG-034 guard: top-level Rust function (no parent) — verify no regression.
/// find_parent_symbol returns None, guard doesn't fire.
#[tokio::test]
async fn bug034_guard_top_level_function_no_parent_no_regression() {
    let src = "\
/// Top-level function.
pub fn standalone() {
    old_impl();
}

pub fn other() {}
";
    let (dir, ctx) = ctx_with_mock(&[("src/lib.rs", src)], |root| {
        let file = root.join("src/lib.rs");
        let sym1 = sym_with_range("standalone", 1, 3, 0, file.clone());
        let sym2 = sym_with_range("other", 5, 5, 5, file.clone());
        MockLspClient::new().with_symbols(file, vec![sym1, sym2])
    })
    .await;

    EditCode
        .call(
            json!({
                "path": "src/lib.rs",
                "symbol": "standalone",
                "action": "replace",
                "body": "/// Top-level function.\npub fn standalone() {\n    new_impl();\n}",
            }),
            &ctx,
        )
        .await
        .unwrap();

    let content = std::fs::read_to_string(dir.path().join("src/lib.rs")).unwrap();
    assert!(
        content.contains("new_impl()"),
        "new body must be applied; got:\n{content}"
    );
    assert!(
        !content.contains("old_impl()"),
        "old body must be gone; got:\n{content}"
    );
    assert!(
        content.contains("pub fn other"),
        "sibling must be preserved; got:\n{content}"
    );
}