agnix-lsp 0.18.0

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

/// Test that Backend::new creates a valid Backend instance.
/// We verify this by creating a service and checking initialize returns proper capabilities.
#[tokio::test]
async fn test_backend_new_creates_valid_instance() {
    let (service, _socket) = LspService::new(Backend::new);

    // The service was created successfully, meaning Backend::new worked
    // We can verify by calling initialize
    let init_params = InitializeParams::default();
    let result = service.inner().initialize(init_params).await;

    assert!(result.is_ok());
}

/// Test that initialize() returns correct server capabilities.
#[tokio::test]
async fn test_initialize_returns_correct_capabilities() {
    let (service, _socket) = LspService::new(Backend::new);

    let init_params = InitializeParams::default();
    let result = service.inner().initialize(init_params).await;

    let init_result = result.expect("initialize should succeed");

    // Verify text document sync capability
    match init_result.capabilities.text_document_sync {
        Some(TextDocumentSyncCapability::Kind(kind)) => {
            assert_eq!(kind, TextDocumentSyncKind::FULL);
        }
        _ => panic!("Expected FULL text document sync capability"),
    }

    assert!(
        init_result.capabilities.completion_provider.is_some(),
        "Expected completion provider capability"
    );

    // Verify server info
    let server_info = init_result
        .server_info
        .expect("server_info should be present");
    assert_eq!(server_info.name, "agnix-lsp");
    assert!(server_info.version.is_some());
}

#[tokio::test]
async fn test_completion_returns_skill_frontmatter_candidates() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    let content = "---\nna\n---\n";
    std::fs::write(&skill_path, content).unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;

    let completion = service
        .inner()
        .completion(CompletionParams {
            text_document_position: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: Position {
                    line: 1,
                    character: 1,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
            context: None,
        })
        .await
        .unwrap();

    let items = match completion {
        Some(CompletionResponse::Array(items)) => items,
        _ => panic!("Expected completion items"),
    };
    assert!(items.iter().any(|item| item.label == "name"));
}

/// Test that shutdown() returns Ok.
#[tokio::test]
async fn test_shutdown_returns_ok() {
    let (service, _socket) = LspService::new(Backend::new);

    let result = service.inner().shutdown().await;
    assert!(result.is_ok());
}

/// Test validation error diagnostic has correct code.
/// We test the diagnostic structure directly since we can't easily mock the validation.
#[test]
fn test_validation_error_diagnostic_structure() {
    // Simulate what validate_file returns on validation error
    let error_message = "Failed to parse file";
    let diagnostic = Diagnostic {
        range: Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 0,
            },
        },
        severity: Some(DiagnosticSeverity::ERROR),
        code: Some(NumberOrString::String(
            "agnix::validation-error".to_string(),
        )),
        code_description: None,
        source: Some("agnix".to_string()),
        message: format!("Validation error: {}", error_message),
        related_information: None,
        tags: None,
        data: None,
    };

    assert_eq!(
        diagnostic.code,
        Some(NumberOrString::String(
            "agnix::validation-error".to_string()
        ))
    );
    assert_eq!(diagnostic.source, Some("agnix".to_string()));
    assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
    assert!(diagnostic.message.contains("Validation error:"));
}

/// Test internal error diagnostic has correct code.
#[test]
fn test_internal_error_diagnostic_structure() {
    // Simulate what validate_file returns on panic/internal error
    let error_message = "task panicked";
    let diagnostic = Diagnostic {
        range: Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 0,
            },
        },
        severity: Some(DiagnosticSeverity::ERROR),
        code: Some(NumberOrString::String("agnix::internal-error".to_string())),
        code_description: None,
        source: Some("agnix".to_string()),
        message: format!("Internal error: {}", error_message),
        related_information: None,
        tags: None,
        data: None,
    };

    assert_eq!(
        diagnostic.code,
        Some(NumberOrString::String("agnix::internal-error".to_string()))
    );
    assert_eq!(diagnostic.source, Some("agnix".to_string()));
    assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
    assert!(diagnostic.message.contains("Internal error:"));
}

/// Test that invalid URIs are identified correctly.
/// Non-file URIs should fail to_file_path().
#[test]
fn test_invalid_uri_detection() {
    // Non-file URIs should fail to_file_path()
    let http_uri = Url::parse("http://example.com/file.md").unwrap();
    assert!(http_uri.to_file_path().is_err());

    let data_uri = Url::parse("data:text/plain;base64,SGVsbG8=").unwrap();
    assert!(data_uri.to_file_path().is_err());

    // File URIs should succeed - use platform-appropriate path
    #[cfg(windows)]
    let file_uri = Url::parse("file:///C:/tmp/test.md").unwrap();
    #[cfg(not(windows))]
    let file_uri = Url::parse("file:///tmp/test.md").unwrap();
    assert!(file_uri.to_file_path().is_ok());
}

/// Test validate_file with a valid file returns diagnostics.
#[tokio::test]
async fn test_validate_file_valid_skill() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create a valid skill file
    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill

This is a valid skill.
"#,
    )
    .unwrap();

    // We can't directly call validate_file since it's private,
    // but we can verify the validation logic works through did_open
    // The Backend will log messages to the client
    let uri = Url::from_file_path(&skill_path).unwrap();

    // Call did_open which triggers validate_and_publish internally
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(), // Content is read from file
            },
        })
        .await;

    // If we get here without panicking, the validation completed
}

/// Test validate_file with an invalid skill file.
#[tokio::test]
async fn test_validate_file_invalid_skill() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create an invalid skill file (invalid name with spaces)
    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: Invalid Name With Spaces
version: 1.0.0
model: sonnet
---

# Invalid Skill

This skill has an invalid name.
"#,
    )
    .unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Call did_open which triggers validation
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Validation should complete and publish diagnostics
}

/// Test did_save triggers validation.
#[tokio::test]
async fn test_did_save_triggers_validation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
    )
    .unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Call did_save which triggers validate_and_publish
    service
        .inner()
        .did_save(DidSaveTextDocumentParams {
            text_document: TextDocumentIdentifier { uri },
            text: None,
        })
        .await;

    // Validation should complete without error
}

/// Test did_save on a project-level trigger file starts project-level revalidation.
#[tokio::test]
async fn test_did_save_project_trigger_starts_project_revalidation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let agents_path = temp_dir.path().join("AGENTS.md");
    std::fs::write(&agents_path, "# Root AGENTS").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let before = service
        .inner()
        .project_validation_generation
        .load(Ordering::SeqCst);

    let uri = Url::from_file_path(&agents_path).unwrap();
    service
        .inner()
        .did_save(DidSaveTextDocumentParams {
            text_document: TextDocumentIdentifier { uri },
            text: None,
        })
        .await;

    let mut observed_increment = false;
    for _ in 0..40 {
        let current = service
            .inner()
            .project_validation_generation
            .load(Ordering::SeqCst);
        if current > before {
            observed_increment = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }

    assert!(
        observed_increment,
        "did_save on AGENTS.md should trigger project-level revalidation"
    );
}

/// Test did_close clears diagnostics.
#[tokio::test]
async fn test_did_close_clears_diagnostics() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test").unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Call did_close which publishes empty diagnostics
    service
        .inner()
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri },
        })
        .await;

    // Should complete without error
}

/// Test initialized() completes without error.
#[tokio::test]
async fn test_initialized_completes() {
    let (service, _socket) = LspService::new(Backend::new);

    // Call initialized
    service.inner().initialized(InitializedParams {}).await;

    // Should complete without error (logs a message to client)
}

/// Test validate_and_publish with non-file URI is handled gracefully.
/// Since validate_and_publish is private, we test the URI validation logic directly.
#[tokio::test]
async fn test_non_file_uri_handled_gracefully() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create a non-file URI (http://)
    let http_uri = Url::parse("http://example.com/test.md").unwrap();

    // Call did_open with non-file URI
    // This should be handled gracefully (log warning and return early)
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: http_uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Should complete without panic
}

/// Test validation with non-existent file.
#[tokio::test]
async fn test_validate_nonexistent_file() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create a URI for a file that doesn't exist
    let temp_dir = tempfile::tempdir().unwrap();
    let nonexistent_path = temp_dir.path().join("nonexistent.md");
    let uri = Url::from_file_path(&nonexistent_path).unwrap();

    // Call did_open - should handle missing file gracefully
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Should complete without panic (will publish error diagnostic)
}

/// Test server info contains version from Cargo.toml.
#[tokio::test]
async fn test_server_info_version() {
    let (service, _socket) = LspService::new(Backend::new);

    let init_params = InitializeParams::default();
    let result = service.inner().initialize(init_params).await.unwrap();

    let server_info = result.server_info.unwrap();
    let version = server_info.version.unwrap();

    // Version should be a valid semver string
    assert!(!version.is_empty());
    // Should match the crate version pattern (e.g., "0.1.0")
    assert!(version.contains('.'));
}

/// Test that initialize captures workspace root from root_uri.
#[tokio::test]
async fn test_initialize_captures_workspace_root() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    let init_params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };

    let result = service.inner().initialize(init_params).await;
    assert!(result.is_ok());

    // The workspace root should now be set (we can't directly access it,
    // but the test verifies initialize handles root_uri without error)
}

/// Test that initialize loads config from .agnix.toml when present.
#[tokio::test]
async fn test_initialize_loads_config_from_file() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create a .agnix.toml config file
    let config_path = temp_dir.path().join(".agnix.toml");
    std::fs::write(
        &config_path,
        r#"
severity = "Warning"
target = "ClaudeCode"
exclude = []

[rules]
skills = false
"#,
    )
    .unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    let init_params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };

    let result = service.inner().initialize(init_params).await;
    assert!(result.is_ok());

    // The config should have been loaded (we can't directly access it,
    // but the test verifies initialize handles .agnix.toml without error)
}

/// Test that initialize handles invalid .agnix.toml gracefully.
#[tokio::test]
async fn test_initialize_handles_invalid_config() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create an invalid .agnix.toml config file
    let config_path = temp_dir.path().join(".agnix.toml");
    std::fs::write(&config_path, "this is not valid toml [[[").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    let init_params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };

    // Should still succeed (logs warning, uses default config)
    let result = service.inner().initialize(init_params).await;
    assert!(result.is_ok());
}

/// Test that files within workspace are validated normally.
#[tokio::test]
async fn test_file_within_workspace_validated() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create workspace with a skill file
    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
    )
    .unwrap();

    // Initialize with workspace root
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    let init_params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };
    service.inner().initialize(init_params).await.unwrap();

    // File within workspace should be validated
    let uri = Url::from_file_path(&skill_path).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Should complete without error (file is within workspace)
}

/// Test that files outside workspace are rejected.
/// This tests the workspace boundary validation security feature.
#[tokio::test]
async fn test_file_outside_workspace_rejected() {
    let (service, _socket) = LspService::new(Backend::new);

    // Create two separate directories
    let workspace_dir = tempfile::tempdir().unwrap();
    let outside_dir = tempfile::tempdir().unwrap();

    // Create a file outside the workspace
    let outside_file = outside_dir.path().join("SKILL.md");
    std::fs::write(
        &outside_file,
        r#"---
name: outside-skill
version: 1.0.0
model: sonnet
---

# Outside Skill
"#,
    )
    .unwrap();

    // Initialize with workspace root
    let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
    let init_params = InitializeParams {
        root_uri: Some(root_uri),
        ..Default::default()
    };
    service.inner().initialize(init_params).await.unwrap();

    // Try to validate file outside workspace
    let uri = Url::from_file_path(&outside_file).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Should complete without error (logs warning and returns early)
    // The file is rejected but no panic occurs
}

/// Test validation without workspace root (backwards compatibility).
/// When no workspace root is set, all files should be accepted.
#[tokio::test]
async fn test_validation_without_workspace_root() {
    let (service, _socket) = LspService::new(Backend::new);

    // Initialize without root_uri
    let init_params = InitializeParams::default();
    service.inner().initialize(init_params).await.unwrap();

    // Create a file anywhere
    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
    )
    .unwrap();

    // Should validate normally (no workspace boundary check)
    let uri = Url::from_file_path(&skill_path).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: String::new(),
            },
        })
        .await;

    // Should complete without error
}

/// Test that cached config is used (performance optimization).
/// We verify this indirectly by running multiple validations.
#[tokio::test]
async fn test_cached_config_used_for_multiple_validations() {
    let (service, _socket) = LspService::new(Backend::new);

    // Initialize
    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Create multiple skill files
    let temp_dir = tempfile::tempdir().unwrap();
    for i in 0..3 {
        let skill_path = temp_dir.path().join(format!("skill{}/SKILL.md", i));
        std::fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
        std::fs::write(
            &skill_path,
            format!(
                r#"---
name: test-skill-{}
version: 1.0.0
model: sonnet
---

# Test Skill {}
"#,
                i, i
            ),
        )
        .unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;
    }

    // All validations should complete (config is reused internally)
}

/// Regression test: validates multiple files using the cached registry.
/// Verifies the Arc<ValidatorRegistry> is thread-safe across spawn_blocking tasks.
#[tokio::test]
async fn test_cached_registry_used_for_multiple_validations() {
    let (service, _socket) = LspService::new(Backend::new);

    // Initialize
    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let temp_dir = tempfile::tempdir().unwrap();

    // Skill file
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
    )
    .unwrap();

    // CLAUDE.md file
    let claude_path = temp_dir.path().join("CLAUDE.md");
    std::fs::write(
        &claude_path,
        r#"# Project Memory

This is a test project.
"#,
    )
    .unwrap();

    for path in [&skill_path, &claude_path] {
        let uri = Url::from_file_path(path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: String::new(),
                },
            })
            .await;
    }
}

// ===== Cache Invalidation Tests =====

/// Test that document cache is cleared when document is closed.
#[tokio::test]
async fn test_document_cache_cleared_on_close() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: test\ndescription: Test\n---\n# Test",
    )
    .unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Open document
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: test\ndescription: Test\n---\n# Test".to_string(),
            },
        })
        .await;

    // Verify document is cached (hover should work)
    let hover_before = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;
    assert!(hover_before.is_ok());
    assert!(hover_before.unwrap().is_some());

    // Close document
    service
        .inner()
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
        })
        .await;

    // Verify document cache is cleared (hover should return None)
    let hover_after = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;
    assert!(hover_after.is_ok());
    assert!(hover_after.unwrap().is_none());
}

/// Test that document cache is updated on change.
#[tokio::test]
async fn test_document_cache_updated_on_change() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Initial").unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Open with initial content
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Initial".to_string(),
            },
        })
        .await;

    // Change to content with frontmatter
    service
        .inner()
        .did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "---\nname: updated\ndescription: Updated\n---\n# Updated".to_string(),
            }],
        })
        .await;

    // Verify cache has new content (hover should work on frontmatter)
    let hover = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;
    assert!(hover.is_ok());
    assert!(hover.unwrap().is_some());
}

/// Regression: cached document reads should share the same allocation.
#[tokio::test]
async fn test_get_document_content_returns_shared_arc() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Shared").unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Shared".to_string(),
            },
        })
        .await;

    let first = service
        .inner()
        .get_document_content(&uri)
        .await
        .expect("cached content should exist");
    let second = service
        .inner()
        .get_document_content(&uri)
        .await
        .expect("cached content should exist");

    assert!(Arc::ptr_eq(&first, &second));
}

/// Test that multiple documents have independent caches.
#[tokio::test]
async fn test_multiple_documents_independent_caches() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create two skill files
    let skill1_path = temp_dir.path().join("skill1").join("SKILL.md");
    let skill2_path = temp_dir.path().join("skill2").join("SKILL.md");
    std::fs::create_dir_all(skill1_path.parent().unwrap()).unwrap();
    std::fs::create_dir_all(skill2_path.parent().unwrap()).unwrap();

    std::fs::write(
        &skill1_path,
        "---\nname: skill-one\ndescription: First\n---\n# One",
    )
    .unwrap();
    std::fs::write(
        &skill2_path,
        "---\nname: skill-two\ndescription: Second\n---\n# Two",
    )
    .unwrap();

    let uri1 = Url::from_file_path(&skill1_path).unwrap();
    let uri2 = Url::from_file_path(&skill2_path).unwrap();

    // Open both documents
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri1.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: skill-one\ndescription: First\n---\n# One".to_string(),
            },
        })
        .await;

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri2.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: skill-two\ndescription: Second\n---\n# Two".to_string(),
            },
        })
        .await;

    // Close first document
    service
        .inner()
        .did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: uri1.clone() },
        })
        .await;

    // First document should be cleared
    let hover1 = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri: uri1 },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;
    assert!(hover1.is_ok());
    assert!(hover1.unwrap().is_none());

    // Second document should still be cached
    let hover2 = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri: uri2 },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;
    assert!(hover2.is_ok());
    assert!(hover2.unwrap().is_some());
}

// ===== Configuration Change Tests =====

/// Test that did_change_configuration handles valid settings.
#[tokio::test]
async fn test_did_change_configuration_valid_settings() {
    let (service, _socket) = LspService::new(Backend::new);

    // Initialize first
    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Send valid configuration
    let settings = serde_json::json!({
        "severity": "Error",
        "target": "ClaudeCode",
        "rules": {
            "skills": false,
            "hooks": true
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
    // The config is internally updated but we can't directly access it
}

/// Test that did_change_configuration handles partial settings.
#[tokio::test]
async fn test_did_change_configuration_partial_settings() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Send only severity (partial config)
    let settings = serde_json::json!({
        "severity": "Info"
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test that did_change_configuration handles invalid JSON gracefully.
#[tokio::test]
async fn test_did_change_configuration_invalid_json() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Send invalid JSON type (string instead of object)
    let settings = serde_json::json!("not an object");

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error (logs warning and returns early)
}

/// Test bounded helper used by did_change_configuration.
#[test]
fn test_config_revalidation_concurrency_bounds() {
    let expected_cap = std::thread::available_parallelism()
        .map(|count| count.get())
        .unwrap_or(4)
        .clamp(1, MAX_CONFIG_REVALIDATION_CONCURRENCY);

    assert_eq!(config_revalidation_concurrency(0), 0);
    assert_eq!(config_revalidation_concurrency(1), 1);
    assert_eq!(
        config_revalidation_concurrency(MAX_CONFIG_REVALIDATION_CONCURRENCY * 4),
        expected_cap
    );
}

/// Test bounded helper handles empty inputs with no task errors.
#[tokio::test]
async fn test_for_each_bounded_empty_input() {
    let errors = for_each_bounded(Vec::<usize>::new(), 3, |_| async {}).await;
    assert!(errors.is_empty());
}

/// Test bounded helper reports join errors when inner tasks panic.
#[tokio::test]
async fn test_for_each_bounded_collects_join_errors() {
    let errors = for_each_bounded(vec![0usize, 1, 2], 2, |idx| async move {
        if idx == 1 {
            panic!("intentional panic for join error coverage");
        }
    })
    .await;

    assert_eq!(errors.len(), 1);
    assert!(errors[0].is_panic());
}

/// Test generation guard for config-change batch publishing.
#[tokio::test]
async fn test_should_publish_diagnostics_guard() {
    let (service, _socket) = LspService::new(Backend::new);
    let backend = service.inner();

    let temp_dir = tempfile::tempdir().unwrap();
    let path = temp_dir.path().join("SKILL.md");
    std::fs::write(&path, "# test").unwrap();
    let uri = Url::from_file_path(&path).unwrap();

    let snapshot = Arc::new("# test".to_string());
    backend
        .documents
        .write()
        .await
        .insert(uri.clone(), Arc::clone(&snapshot));
    backend.config_generation.store(7, Ordering::SeqCst);

    assert!(
        backend
            .should_publish_diagnostics(&uri, Some(7), Some(&snapshot))
            .await
    );
    assert!(
        !backend
            .should_publish_diagnostics(&uri, Some(6), Some(&snapshot))
            .await
    );

    // New content (new Arc) means stale validation result should not publish.
    backend
        .documents
        .write()
        .await
        .insert(uri.clone(), Arc::new("# updated".to_string()));
    assert!(
        !backend
            .should_publish_diagnostics(&uri, Some(7), Some(&snapshot))
            .await
    );

    backend.documents.write().await.remove(&uri);
    assert!(
        !backend
            .should_publish_diagnostics(&uri, Some(7), Some(&snapshot))
            .await
    );

    assert!(backend.should_publish_diagnostics(&uri, None, None).await);
}

/// Test bounded helper used by did_change_configuration.
#[tokio::test]
async fn test_did_change_configuration_concurrency_bound_helper() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;
    use tokio::sync::Barrier;

    let max_concurrency = 3usize;
    let in_flight = Arc::new(AtomicUsize::new(0));
    let peak_in_flight = Arc::new(AtomicUsize::new(0));
    let completed = Arc::new(AtomicUsize::new(0));
    let ready = Arc::new(Barrier::new(max_concurrency + 1));
    let release = Arc::new(Barrier::new(max_concurrency + 1));
    let total_items = 12usize;

    let run = tokio::spawn(for_each_bounded(0..total_items, max_concurrency, {
        let in_flight = Arc::clone(&in_flight);
        let peak_in_flight = Arc::clone(&peak_in_flight);
        let completed = Arc::clone(&completed);
        let ready = Arc::clone(&ready);
        let release = Arc::clone(&release);
        move |idx| {
            let in_flight = Arc::clone(&in_flight);
            let peak_in_flight = Arc::clone(&peak_in_flight);
            let completed = Arc::clone(&completed);
            let ready = Arc::clone(&ready);
            let release = Arc::clone(&release);

            async move {
                let current = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
                peak_in_flight.fetch_max(current, Ordering::SeqCst);

                if idx < max_concurrency {
                    ready.wait().await;
                    release.wait().await;
                } else {
                    tokio::task::yield_now().await;
                }

                in_flight.fetch_sub(1, Ordering::SeqCst);
                completed.fetch_add(1, Ordering::SeqCst);
            }
        }
    }));

    // Wait for the first wave of tasks to all be in-flight at once.
    tokio::time::timeout(Duration::from_secs(2), ready.wait())
        .await
        .expect("timed out waiting for first wave");
    assert_eq!(peak_in_flight.load(Ordering::SeqCst), max_concurrency);
    tokio::time::timeout(Duration::from_secs(2), release.wait())
        .await
        .expect("timed out releasing first wave");

    let join_errors = tokio::time::timeout(Duration::from_secs(2), run)
        .await
        .expect("timed out waiting for bounded worker completion")
        .unwrap();

    assert!(join_errors.is_empty());
    assert_eq!(completed.load(Ordering::SeqCst), total_items);
}

/// Test that did_change_configuration triggers revalidation.
#[tokio::test]
async fn test_did_change_configuration_triggers_revalidation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        r#"---
name: test-skill
version: 1.0.0
model: sonnet
---

# Test Skill
"#,
    )
    .unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: std::fs::read_to_string(&skill_path).unwrap(),
            },
        })
        .await;

    // Now change configuration - should trigger revalidation
    let settings = serde_json::json!({
        "severity": "Error",
        "rules": {
            "skills": false
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error - open document was revalidated
}

/// Test that config changes revalidate all currently open documents.
#[tokio::test]
async fn test_did_change_configuration_triggers_revalidation_for_multiple_documents() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let document_count = 6usize;

    for i in 0..document_count {
        let skill_path = temp_dir.path().join(format!("skill-{i}/SKILL.md"));
        std::fs::create_dir_all(skill_path.parent().unwrap()).unwrap();
        std::fs::write(
            &skill_path,
            format!(
                r#"---
name: test-skill-{i}
version: 1.0.0
model: sonnet
---

# Test Skill {i}
"#
            ),
        )
        .unwrap();

        let uri = Url::from_file_path(&skill_path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&skill_path).unwrap(),
                },
            })
            .await;
    }

    let settings = serde_json::json!({
        "severity": "Error",
        "rules": {
            "skills": false
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    let open_documents = service.inner().documents.read().await.len();
    assert_eq!(open_documents, document_count);
}

/// Test that empty settings object doesn't crash.
#[tokio::test]
async fn test_did_change_configuration_empty_settings() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Send empty object
    let settings = serde_json::json!({});

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test configuration with all tool versions set.
#[tokio::test]
async fn test_did_change_configuration_with_versions() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let settings = serde_json::json!({
        "versions": {
            "claude_code": "1.0.0",
            "codex": "0.1.0",
            "cursor": "0.45.0",
            "copilot": "1.2.0"
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test configuration with spec revisions.
#[tokio::test]
async fn test_did_change_configuration_with_specs() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let settings = serde_json::json!({
        "specs": {
            "mcp_protocol": "2025-11-25",
            "agent_skills_spec": "1.0",
            "agents_md_spec": "1.0"
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test configuration with tools array.
#[tokio::test]
async fn test_did_change_configuration_with_tools_array() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let settings = serde_json::json!({
        "tools": ["claude-code", "cursor", "github-copilot"]
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test configuration with disabled rules.
#[tokio::test]
async fn test_did_change_configuration_with_disabled_rules() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let settings = serde_json::json!({
        "rules": {
            "disabled_rules": ["AS-001", "PE-003", "MCP-008"]
        }
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    // Should complete without error
}

/// Test that did_change_configuration handles locale setting.
#[tokio::test]
async fn test_did_change_configuration_with_locale() {
    let (service, _socket) = {
        let _guard = crate::locale::LOCALE_MUTEX.lock().unwrap();
        LspService::new(Backend::new)
    };

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let settings = serde_json::json!({
        "severity": "Warning",
        "locale": "es"
    });

    service
        .inner()
        .did_change_configuration(DidChangeConfigurationParams { settings })
        .await;

    {
        let _guard = crate::locale::LOCALE_MUTEX.lock().unwrap();
        // Verify locale was actually changed
        assert_eq!(&*rust_i18n::locale(), "es");
    }

    // Reset locale for other tests
    rust_i18n::set_locale("en");
}

// ===== normalize_path() Unit Tests =====

/// Test that '..' components are resolved by removing the preceding normal component.
#[test]
fn test_normalize_path_resolves_parent() {
    let result = normalize_path(Path::new("/a/b/../c"));
    assert_eq!(result, PathBuf::from("/a/c"));
}

/// Test that '.' components are removed entirely.
#[test]
fn test_normalize_path_removes_curdir() {
    let result = normalize_path(Path::new("/a/./b/./c"));
    assert_eq!(result, PathBuf::from("/a/b/c"));
}

/// Test that multiple '..' components are resolved correctly.
#[test]
fn test_normalize_path_multiple_parent() {
    let result = normalize_path(Path::new("/a/b/../../c"));
    assert_eq!(result, PathBuf::from("/c"));
}

/// Test that a path without special components is returned unchanged.
#[test]
fn test_normalize_path_already_clean() {
    let result = normalize_path(Path::new("/a/b/c"));
    assert_eq!(result, PathBuf::from("/a/b/c"));
}

/// Test that '..' cannot traverse above root.
#[test]
fn test_normalize_path_cannot_escape_root() {
    let result = normalize_path(Path::new("/../a"));
    assert_eq!(result, PathBuf::from("/a"));
}

/// Test that root alone is preserved.
#[test]
fn test_normalize_path_root_only() {
    let result = normalize_path(Path::new("/"));
    assert_eq!(result, PathBuf::from("/"));
}

/// Test excessive '..' beyond root is clamped.
#[test]
fn test_normalize_path_excessive_parent_traversal() {
    let result = normalize_path(Path::new("/a/../../../b"));
    assert_eq!(result, PathBuf::from("/b"));
}

/// Test mixed '.' and '..' components together.
#[test]
fn test_normalize_path_mixed_special_components() {
    let result = normalize_path(Path::new("/a/./b/../c/./d"));
    assert_eq!(result, PathBuf::from("/a/c/d"));
}

// ===== Path Traversal Regression Tests =====

/// Regression: a URI with '..' that escapes the workspace must be rejected
/// even when the file does not exist on disk (so canonicalize() fails).
#[tokio::test]
async fn test_path_traversal_outside_workspace_rejected() {
    let (service, _socket) = LspService::new(Backend::new);

    let workspace_dir = tempfile::tempdir().unwrap();
    let outside_dir = tempfile::tempdir().unwrap();

    // Extract the outside directory name for the traversal path
    let outside_name = outside_dir
        .path()
        .file_name()
        .expect("should have a file name")
        .to_str()
        .expect("should be valid UTF-8");

    // Initialize with workspace root
    let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Construct a path that uses '..' to escape the workspace.
    // The file does not exist, so canonicalize() will fail and
    // the code must fall back to normalize_path().
    let traversal_path = workspace_dir
        .path()
        .join("..")
        .join("..")
        .join(outside_name)
        .join("SKILL.md");
    let uri = Url::from_file_path(&traversal_path).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: evil\n---\n# Evil".to_string(),
            },
        })
        .await;

    // Should complete without panic -- the file is outside the workspace
    // so it is silently rejected (warning logged, no diagnostics published).
}

/// Regression: a URI with '..' that resolves *inside* the workspace must
/// still be accepted for validation.
#[tokio::test]
async fn test_path_traversal_inside_workspace_accepted() {
    let (service, _socket) = LspService::new(Backend::new);

    let workspace_dir = tempfile::tempdir().unwrap();

    // Create subdir and a SKILL.md at the workspace root
    let subdir = workspace_dir.path().join("subdir");
    std::fs::create_dir(&subdir).unwrap();
    let skill_path = workspace_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: test-skill\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Test Skill\n",
    )
    .unwrap();

    // Initialize with workspace root
    let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // URI with '..' that resolves back into the workspace

    // URI with '..' that resolves back into the workspace
    let traversal_path = workspace_dir
        .path()
        .join("subdir")
        .join("..")
        .join("SKILL.md");
    let uri = Url::from_file_path(&traversal_path).unwrap();
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: std::fs::read_to_string(&skill_path).unwrap(),
            },
        })
        .await;

    // Should complete without error -- file resolves inside workspace
}

/// Regression: a non-existent file within the workspace boundary
/// (without any '..' components) must not be rejected.
#[tokio::test]
async fn test_nonexistent_file_in_workspace_accepted() {
    let (service, _socket) = LspService::new(Backend::new);

    let workspace_dir = tempfile::tempdir().unwrap();

    // Initialize with workspace root
    let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Non-existent file inside workspace (no '..' components)
    let nonexistent = workspace_dir.path().join("SKILL.md");
    let uri = Url::from_file_path(&nonexistent).unwrap();

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: ghost\n---\n# Ghost".to_string(),
            },
        })
        .await;

    // Should pass boundary check -- path is inside workspace
}

/// Regression: a URI with '.' components (current-dir markers) must be
/// accepted when the file is inside the workspace.
#[tokio::test]
async fn test_dot_components_in_path_accepted() {
    let (service, _socket) = LspService::new(Backend::new);

    let workspace_dir = tempfile::tempdir().unwrap();
    let skill_path = workspace_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: test-skill\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Test Skill\n",
    )
    .unwrap();

    // Initialize with workspace root
    let root_uri = Url::from_file_path(workspace_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // URI with '.' components
    let dot_path = format!("{}/./SKILL.md", workspace_dir.path().display());
    let uri = Url::parse(&format!("file://{}", dot_path)).unwrap();

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: std::fs::read_to_string(&skill_path).unwrap(),
            },
        })
        .await;

    // Should pass boundary check -- '.' resolves to the same directory
}

// ===== Project-Level Validation Tests =====

/// Test that validate_project_rules_and_publish returns early without panic
/// when no workspace root is set.
#[tokio::test]
async fn test_validate_project_rules_no_workspace() {
    let (service, _socket) = LspService::new(Backend::new);

    // Initialize without workspace root
    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    // Should return early without error (no workspace root)
    service.inner().validate_project_rules_and_publish().await;

    // Verify no project diagnostics were stored
    let proj_diags = service.inner().project_level_diagnostics.read().await;
    assert!(
        proj_diags.is_empty(),
        "No project diagnostics should be stored without workspace root"
    );
}

/// Test that project-level diagnostics are cached after running validation.
#[tokio::test]
async fn test_project_diagnostics_cached() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files to trigger AGM-006
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // initialize() now spawns project validation in the background.
    // Wait for it to complete before asserting.
    for _ in 0..80 {
        let proj_diags = service.inner().project_level_diagnostics.read().await;
        if !proj_diags.is_empty() {
            break;
        }
        drop(proj_diags);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // Verify project diagnostics are stored
    let proj_diags = service.inner().project_level_diagnostics.read().await;
    assert!(
        !proj_diags.is_empty(),
        "Project diagnostics should be cached for AGM-006"
    );

    // Verify URIs are tracked for cleanup
    let proj_uris = service.inner().project_diagnostics_uris.read().await;
    assert!(
        !proj_uris.is_empty(),
        "Project diagnostic URIs should be tracked"
    );
}

/// Test that stale project diagnostics are cleared on re-run.
#[tokio::test]
async fn test_project_diagnostics_cleared_on_rerun() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files to trigger AGM-006
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // initialize() now spawns project validation in the background.
    // Wait for it to complete before continuing.
    for _ in 0..80 {
        let proj_diags = service.inner().project_level_diagnostics.read().await;
        if !proj_diags.is_empty() {
            break;
        }
        drop(proj_diags);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    let count_before = service.inner().project_diagnostics_uris.read().await.len();
    assert!(
        count_before > 0,
        "Should have project diagnostics before cleanup"
    );

    // Remove the nested AGENTS.md to resolve the issue
    std::fs::remove_file(sub.join("AGENTS.md")).unwrap();

    // Second run: AGM-006 should no longer fire
    service.inner().validate_project_rules_and_publish().await;

    let proj_diags = service.inner().project_level_diagnostics.read().await;
    let agm006_count: usize = proj_diags
        .values()
        .flat_map(|diags| diags.iter())
        .filter(|d| {
            d.code
                .as_ref()
                .map(|c| matches!(c, NumberOrString::String(s) if s == "AGM-006"))
                .unwrap_or(false)
        })
        .count();
    assert_eq!(agm006_count, 0, "AGM-006 should be cleared after fix");
}

/// Test stale generation guard returns early without mutating cached project diagnostics.
#[tokio::test]
async fn test_project_validation_stale_generation_returns_early() {
    let (service, _socket) = LspService::new(Backend::new);
    let backend = service.inner().clone();

    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files so project validation has work to do.
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Pre-populate cache so we can verify stale run does not overwrite it.
    let sentinel_path = temp_dir.path().join("sentinel.md");
    let sentinel_uri = Url::from_file_path(&sentinel_path).unwrap();
    let sentinel_diag = Diagnostic {
        range: Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 0,
            },
        },
        severity: Some(DiagnosticSeverity::WARNING),
        code: Some(NumberOrString::String("SENTINEL".to_string())),
        code_description: None,
        source: Some("agnix".to_string()),
        message: "sentinel".to_string(),
        related_information: None,
        tags: None,
        data: None,
    };
    {
        let mut proj_diags = service.inner().project_level_diagnostics.write().await;
        proj_diags.insert(sentinel_uri.clone(), vec![sentinel_diag]);
    }
    {
        let mut proj_uris = service.inner().project_diagnostics_uris.write().await;
        proj_uris.insert(sentinel_uri.clone());
    }

    // Continuously bump generation to force stale detection in the running validation.
    let bump_backend = service.inner().clone();
    let bump = tokio::spawn(async move {
        for _ in 0..200 {
            bump_backend
                .project_validation_generation
                .store(9_999, Ordering::SeqCst);
            tokio::task::yield_now().await;
        }
    });

    backend.validate_project_rules_and_publish().await;
    bump.abort();

    let proj_diags = service.inner().project_level_diagnostics.read().await;
    assert!(
        proj_diags.contains_key(&sentinel_uri),
        "stale generation run should return before overwriting cached diagnostics"
    );

    let proj_uris = service.inner().project_diagnostics_uris.read().await;
    assert!(
        proj_uris.contains(&sentinel_uri),
        "stale generation run should return before mutating cached URI set"
    );
}

/// Test is_project_level_trigger for various file names.
#[test]
fn test_is_project_level_trigger() {
    // Instruction files should trigger
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/CLAUDE.md"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/AGENTS.md"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.clinerules"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.cursorrules"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.github/copilot-instructions.md"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.github/instructions/test.instructions.md"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.cursor/rules/test.mdc"
    )));
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/GEMINI.md"
    )));

    // .agnix.toml should trigger
    assert!(Backend::is_project_level_trigger(Path::new(
        "/project/.agnix.toml"
    )));

    // Non-instruction files should not trigger
    assert!(!Backend::is_project_level_trigger(Path::new(
        "/project/SKILL.md"
    )));
    assert!(!Backend::is_project_level_trigger(Path::new(
        "/project/README.md"
    )));
    assert!(!Backend::is_project_level_trigger(Path::new(
        "/project/settings.json"
    )));
    assert!(!Backend::is_project_level_trigger(Path::new(
        "/project/plugin.json"
    )));
}

/// Test that initialize advertises executeCommand capability.
#[tokio::test]
async fn test_initialize_advertises_execute_command() {
    let (service, _socket) = LspService::new(Backend::new);

    let result = service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    match result.capabilities.execute_command_provider {
        Some(ref opts) => {
            assert!(
                opts.commands
                    .contains(&"agnix.validateProjectRules".to_string()),
                "Expected agnix.validateProjectRules in execute commands, got: {:?}",
                opts.commands
            );
        }
        None => panic!("Expected execute command capability"),
    }
}

/// Test that execute_command handles the validateProjectRules command.
#[tokio::test]
async fn test_execute_command_validate_project_rules() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Execute the command
    let result = service
        .inner()
        .execute_command(ExecuteCommandParams {
            command: "agnix.validateProjectRules".to_string(),
            arguments: vec![],
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;

    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test that execute_command handles unknown commands gracefully.
#[tokio::test]
async fn test_execute_command_unknown() {
    let (service, _socket) = LspService::new(Backend::new);

    service
        .inner()
        .initialize(InitializeParams::default())
        .await
        .unwrap();

    let result = service
        .inner()
        .execute_command(ExecuteCommandParams {
            command: "unknown.command".to_string(),
            arguments: vec![],
            work_done_progress_params: WorkDoneProgressParams::default(),
        })
        .await;

    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test that project-level diagnostics are merged with per-file diagnostics
/// when validate_from_content_and_publish is called.
///
/// Pre-populates the project_level_diagnostics cache with a diagnostic for
/// a file URI, then opens the file so per-file validation runs and the merge
/// path in validate_from_content_and_publish is exercised.
#[tokio::test]
async fn test_project_and_file_diagnostics_merged() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    // Initialize with workspace root
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Create a CLAUDE.md that will produce per-file diagnostics (e.g. XML-001)
    let claude_path = temp_dir.path().join("CLAUDE.md");
    std::fs::write(&claude_path, "<unclosed>\n# Project\n").unwrap();
    let uri = Url::from_file_path(&claude_path).unwrap();

    // Wait for the background project validation spawned by initialize()
    // to complete before injecting fake diagnostics, to avoid a race where
    // the background run overwrites our manually inserted data.
    for _ in 0..80 {
        let generation = service
            .inner()
            .project_validation_generation
            .load(std::sync::atomic::Ordering::SeqCst);
        if generation >= 1 {
            // Give the async task a moment to finish writing results
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // Pre-populate project_level_diagnostics with a fake AGM-006 diagnostic
    // for this URI, simulating what validate_project_rules_and_publish would store.
    {
        let fake_project_diag = Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 0,
                },
            },
            severity: Some(DiagnosticSeverity::WARNING),
            code: Some(NumberOrString::String("AGM-006".to_string())),
            code_description: None,
            source: Some("agnix".to_string()),
            message: "Nested AGENTS.md detected".to_string(),
            related_information: None,
            tags: None,
            data: None,
        };
        let mut proj_diags = service.inner().project_level_diagnostics.write().await;
        proj_diags.insert(uri.clone(), vec![fake_project_diag]);
    }

    // Verify the project diagnostics are in the cache
    {
        let proj_diags = service.inner().project_level_diagnostics.read().await;
        assert!(
            proj_diags.contains_key(&uri),
            "Project diagnostics should be pre-populated for the URI"
        );
    }

    // Open the file -- this triggers validate_from_content_and_publish which
    // should merge per-file diagnostics (e.g. XML-001) with the cached
    // project-level diagnostics (AGM-006).
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: std::fs::read_to_string(&claude_path).unwrap(),
            },
        })
        .await;

    // The merge code path in validate_from_content_and_publish (lines 309-315)
    // was exercised: it reads project_level_diagnostics and extends the
    // per-file diagnostics with any matching project-level entries.
    // Verify the project cache is still intact after the merge.
    {
        let proj_diags = service.inner().project_level_diagnostics.read().await;
        let diags = proj_diags
            .get(&uri)
            .expect("Project diagnostics should still be cached");
        assert!(
            diags
                .iter()
                .any(|d| d.code == Some(NumberOrString::String("AGM-006".to_string()))),
            "Cached project diagnostic should be preserved after merge"
        );
    }
}

// ===== for_each_bounded additional tests =====

#[tokio::test]
async fn test_for_each_bounded_concurrency_limit_one() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let max_concurrent = Arc::new(AtomicUsize::new(0));
    let current = Arc::new(AtomicUsize::new(0));

    let items: Vec<usize> = (0..5).collect();

    let max_c = Arc::clone(&max_concurrent);
    let cur = Arc::clone(&current);

    let errors = for_each_bounded(items, 1, move |_item| {
        let max_c = Arc::clone(&max_c);
        let cur = Arc::clone(&cur);
        async move {
            let c = cur.fetch_add(1, Ordering::SeqCst) + 1;
            // Update max observed concurrency
            max_c.fetch_max(c, Ordering::SeqCst);
            // Yield to give other tasks a chance to run
            tokio::task::yield_now().await;
            cur.fetch_sub(1, Ordering::SeqCst);
        }
    })
    .await;

    assert!(errors.is_empty());
    assert_eq!(
        max_concurrent.load(Ordering::SeqCst),
        1,
        "With concurrency limit 1, at most 1 task should run concurrently"
    );
}

#[tokio::test]
async fn test_for_each_bounded_zero_concurrency_defaults_to_one() {
    // Passing 0 as max_concurrency should be clamped to 1 (not hang or panic)
    let items = vec![1, 2, 3];
    let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let count_clone = Arc::clone(&count);

    let errors = for_each_bounded(items, 0, move |_| {
        let count = Arc::clone(&count_clone);
        async move {
            count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
    })
    .await;

    assert!(errors.is_empty());
    assert_eq!(
        count.load(std::sync::atomic::Ordering::SeqCst),
        3,
        "All items should be processed even with concurrency 0"
    );
}

/// Test that GenericMarkdown files are not validated by the LSP.
///
/// A `.md` file that doesn't match any specific agent pattern gets classified
/// as GenericMarkdown. The LSP should skip validation for these to avoid
/// false positives on developer docs, project specs, etc.
#[tokio::test]
async fn test_generic_markdown_not_validated() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Create a generic markdown file (not a known agent config pattern).
    // "notes.md" at the project root is classified as GenericMarkdown.
    let notes_path = temp_dir.path().join("notes.md");
    let content = "<unclosed>\n# Some developer notes\n";
    std::fs::write(&notes_path, content).unwrap();

    let uri = Url::from_file_path(&notes_path).unwrap();

    // Open the file - the LSP should skip validation for GenericMarkdown
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;

    // did_open always caches the document content before calling
    // validate_from_content_and_publish. The GenericMarkdown early return
    // skips validation but does not prevent caching.
    let docs = service.inner().documents.read().await;
    assert!(
        docs.contains_key(&uri),
        "Document should be cached (did_open always caches)"
    );
}

/// Test that hover() returns None for GenericMarkdown files.
#[tokio::test]
async fn test_hover_returns_none_for_generic_markdown() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Create a generic markdown file and open it
    let notes_path = temp_dir.path().join("notes.md");
    let content = "---\nname: test\n---\n# Notes\n";
    std::fs::write(&notes_path, content).unwrap();
    let uri = Url::from_file_path(&notes_path).unwrap();

    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;

    // Hover on a GenericMarkdown file should return None
    let hover_result = service
        .inner()
        .hover(HoverParams {
            text_document_position_params: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri },
                position: Position {
                    line: 1,
                    character: 0,
                },
            },
            work_done_progress_params: Default::default(),
        })
        .await
        .unwrap();

    assert!(
        hover_result.is_none(),
        "Hover should return None for GenericMarkdown files"
    );
}

/// Test that specific agent config files ARE validated (not skipped).
///
/// Ensures the GenericMarkdown skip doesn't accidentally filter out
/// real agent configuration files.
#[tokio::test]
async fn test_agent_config_files_still_validated() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // CLAUDE.md is FileType::ClaudeMd - should be validated (not generic)
    let claude_path = temp_dir.path().join("CLAUDE.md");
    let content = "# Project\n\nSome instructions.\n";
    std::fs::write(&claude_path, content).unwrap();

    let uri = Url::from_file_path(&claude_path).unwrap();

    // Verify the file type is NOT generic
    let config = service.inner().config.load();
    let file_type = agnix_core::resolve_file_type(&claude_path, &config);
    assert!(
        !file_type.is_generic(),
        "CLAUDE.md should NOT be classified as generic (got {:?})",
        file_type
    );
    assert_eq!(file_type, agnix_core::FileType::ClaudeMd);
    drop(config);

    // Open should proceed through full validation path
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;
}

/// Test that disabled_validators from .agnix.toml config are respected
/// when validating via the LSP content path.
///
/// This verifies that the LSP uses `validate_content()` (which checks
/// disabled_validators) rather than a manual validator loop.
#[tokio::test]
async fn test_disabled_validators_respected_in_content_validation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create config that disables the XmlValidator
    let config_path = temp_dir.path().join(".agnix.toml");
    std::fs::write(
        &config_path,
        r#"
[rules]
disabled_validators = ["XmlValidator"]
"#,
    )
    .unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Verify the config was loaded with disabled validators
    let config = service.inner().config.load();
    assert!(
        config
            .rules()
            .disabled_validators
            .iter()
            .any(|v| v == "XmlValidator"),
        "XmlValidator should be in disabled_validators list"
    );
    drop(config);

    // Create a CLAUDE.md with content that would trigger XmlValidator
    let claude_path = temp_dir.path().join("CLAUDE.md");
    let content = "<unclosed>\n# Project\n";
    std::fs::write(&claude_path, content).unwrap();

    let uri = Url::from_file_path(&claude_path).unwrap();

    // Open the file - exercises validate_from_content_and_publish
    // with validate_content() that respects disabled_validators.
    // This should complete without error (the disabled validator is skipped).
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;
}

/// Test that project-level validation starts during initialize().
///
/// Previously, project validation only ran in initialized() (after the
/// client sends the initialized notification). Now it starts in
/// initialize() so diagnostics are available sooner.
#[tokio::test]
async fn test_project_validation_starts_in_initialize() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create two AGENTS.md files to trigger AGM-006
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    // Only call initialize (NOT initialized) - project validation should
    // still start because we moved spawn_project_validation() there.
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Wait for async project validation to complete
    let mut found = false;
    for _ in 0..80 {
        let proj_diags = service.inner().project_level_diagnostics.read().await;
        if !proj_diags.is_empty() {
            found = true;
            break;
        }
        drop(proj_diags);
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    assert!(
        found,
        "Project-level validation should run during initialize(), \
         producing AGM-006 diagnostics for duplicate AGENTS.md files"
    );
}

// ===== Concurrent Revalidation Stress Tests =====

/// Stress test: 20 concurrent document open/close cycles must not panic
/// or leave stale entries in the document cache.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_concurrent_document_open_close() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let doc_count = 20usize;

    // Create 20 subdirectories, each with a valid SKILL.md
    for i in 0..doc_count {
        let dir = temp_dir.path().join(format!("skill-{i}"));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("SKILL.md"),
            format!(
                "---\nname: stress-skill-{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Stress Skill {i}\n"
            ),
        )
        .unwrap();
    }

    let backend = service.inner().clone();

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut handles = Vec::new();
        for i in 0..doc_count {
            let backend = backend.clone();
            let path = temp_dir.path().join(format!("skill-{i}")).join("SKILL.md");
            // Read content before spawning: avoids running 20 concurrent blocking
            // std::fs reads inside spawned tasks (one per task in a hot loop).
            let content = std::fs::read_to_string(&path).unwrap();
            let uri = Url::from_file_path(&path).unwrap();
            handles.push(tokio::spawn(async move {
                backend
                    .did_open(DidOpenTextDocumentParams {
                        text_document: TextDocumentItem {
                            uri: uri.clone(),
                            language_id: "markdown".to_string(),
                            version: 1,
                            text: content,
                        },
                    })
                    .await;
                // did_close removes the document from the cache synchronously
                // before spawning any background I/O, so the post-join emptiness
                // assertion below is safe without a drain step.
                backend
                    .did_close(DidCloseTextDocumentParams {
                        text_document: TextDocumentIdentifier { uri },
                    })
                    .await;
            }));
        }

        for handle in handles {
            handle.await.expect("task should not panic");
        }
    })
    .await;

    assert!(result.is_ok(), "concurrent open/close timed out");

    // After all close operations, the document cache should be empty
    let docs = service.inner().documents.read().await;
    assert!(
        docs.is_empty(),
        "documents cache should be empty after all close operations, found {} entries",
        docs.len()
    );
}

/// Stress test: concurrent config_generation increments and should_publish_diagnostics
/// checks. Exercises the stale-batch generation guard under concurrent load by
/// directly driving the AtomicU64 counter while concurrently querying the
/// staleness predicate.
///
/// Note: calling did_change_configuration once works fine (see
/// test_did_change_configuration_triggers_revalidation_for_multiple_documents),
/// but calling it N times in a tight loop would fill the bounded channel
/// (capacity 1) because each call unconditionally sends a log_message via
/// send_notification_unchecked and the test socket is not consumed. This test
/// drives the same AtomicU64 counter directly to exercise N concurrent probes
/// without going through the notification path.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_rapid_config_changes_drop_stale_batches() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Insert a SKILL.md into the document cache directly (no did_open) so
    // should_publish_diagnostics has a live URI to check.
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: stress-skill\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Stress Test\n",
    )
    .unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();
    {
        let mut docs = service.inner().documents.write().await;
        docs.insert(
            uri.clone(),
            Arc::new(std::fs::read_to_string(&skill_path).unwrap()),
        );
    }

    let change_count = 50u64;
    let backend_a = service.inner().clone();
    let backend_b = service.inner().clone();
    let uri_b = uri.clone();

    // Task A: rapidly increments config_generation (simulating rapid config changes).
    let task_a = tokio::spawn(async move {
        for _ in 0..change_count {
            backend_a.config_generation.fetch_add(1, Ordering::SeqCst);
            tokio::task::yield_now().await;
        }
    });

    // Task B: concurrently queries should_publish_diagnostics with progressively
    // stale generation values. As Task A bumps the counter, more of these should
    // return false (stale detected).
    let task_b = tokio::spawn(async move {
        let mut stale_count = 0u32;
        // Each iteration probes a different generation value (0, 1, 2...).
        // Once Task A has advanced the counter past probe_gen, the check returns
        // false (stale). When probe_gen matches the current counter it returns true.
        for probe_gen in 0..change_count {
            if !backend_b
                .should_publish_diagnostics(&uri_b, Some(probe_gen), None)
                .await
            {
                stale_count += 1;
            }
            tokio::task::yield_now().await;
        }
        stale_count
    });

    let result = tokio::time::timeout(std::time::Duration::from_secs(10), async move {
        task_a.await.unwrap();
        task_b.await.unwrap()
    })
    .await;

    assert!(
        result.is_ok(),
        "concurrent config_generation stress test timed out"
    );
    // Discard the concurrent stale-count: it is scheduler-dependent and covered
    // deterministically by the post-completion loop below.
    let _ = result.unwrap();

    let final_gen = service.inner().config_generation.load(Ordering::SeqCst);
    assert_eq!(
        final_gen, change_count,
        "config_generation should be {} after {} increments, got {}",
        change_count, change_count, final_gen
    );

    // Deterministic post-completion check: with the counter now at change_count,
    // every probe value in [0, change_count) MUST be stale. The range includes
    // change_count - 1 (one-behind the final value) to catch the boundary case.
    let backend = service.inner().clone();
    for probe in 0..change_count {
        assert!(
            !backend
                .should_publish_diagnostics(&uri, Some(probe), None)
                .await,
            "probe_gen {} should be stale when config_generation is {}",
            probe,
            final_gen
        );
    }

    assert_eq!(
        service.inner().documents.read().await.len(),
        1,
        "document should still be in cache after concurrent stress"
    );
}

/// Stress test: 30 concurrent did_change calls on the same document must
/// not corrupt the cache or panic.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_concurrent_changes_same_document() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: concurrent-skill\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Concurrent\n",
    )
    .unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Open the document first
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: std::fs::read_to_string(&skill_path).unwrap(),
            },
        })
        .await;

    let backend = service.inner().clone();
    let change_count = 30usize;

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut handles = Vec::new();
        for i in 0..change_count {
            let backend = backend.clone();
            let uri = uri.clone();
            handles.push(tokio::spawn(async move {
                backend
                    .did_change(DidChangeTextDocumentParams {
                        text_document: VersionedTextDocumentIdentifier {
                            uri,
                            version: (i + 2) as i32,
                        },
                        content_changes: vec![TextDocumentContentChangeEvent {
                            range: None,
                            range_length: None,
                            text: format!(
                                "---\nname: v{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Version {i}\n"
                            ),
                        }],
                    })
                    .await;
            }));
        }

        for handle in handles {
            handle.await.expect("task should not panic");
        }
    })
    .await;

    assert!(result.is_ok(), "concurrent changes timed out");

    let docs = service.inner().documents.read().await;
    assert_eq!(
        docs.len(),
        1,
        "exactly 1 entry should be in cache for the document, found {}",
        docs.len()
    );
    assert!(
        docs.contains_key(&uri),
        "the URI should still be present in the cache"
    );
}

/// Stress test: concurrent config change and generation bump must not
/// corrupt atomic state or panic.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_config_change_during_active_validation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Open 5 SKILL.md documents
    for i in 0..5 {
        let dir = temp_dir.path().join(format!("skill-{i}"));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("SKILL.md");
        std::fs::write(
            &path,
            format!(
                "---\nname: active-skill-{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Active Skill {i}\n"
            ),
        )
        .unwrap();

        let uri = Url::from_file_path(&path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&path).unwrap(),
                },
            })
            .await;
    }

    let backend_a = service.inner().clone();
    let backend_b = service.inner().clone();

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        // Task A: fire a config change (which increments config_generation and revalidates)
        let task_a = tokio::spawn(async move {
            backend_a
                .did_change_configuration(DidChangeConfigurationParams {
                    settings: serde_json::json!({ "severity": "Warning" }),
                })
                .await;
        });

        // Task B: concurrently bump config_generation to a high value
        let task_b = tokio::spawn(async move {
            backend_b
                .config_generation
                .fetch_add(9_999, Ordering::SeqCst);
        });

        task_a.await.expect("config change task should not panic");
        task_b.await.expect("generation bump task should not panic");
    })
    .await;

    assert!(result.is_ok(), "concurrent config change timed out");

    // Task A does fetch_add(1) (config_generation 0→1) and Task B does
    // fetch_add(9_999). Both tasks always run to completion before the assertion,
    // so the total is always 0 + 1 + 9_999 = 10_000 regardless of ordering.
    let generation = service.inner().config_generation.load(Ordering::SeqCst);
    assert_eq!(
        generation, 10_000,
        "config_generation should be 10000 (1 from config change + 9999 from bump), got {}",
        generation
    );

    let open_docs = service.inner().documents.read().await.len();
    assert_eq!(
        open_docs, 5,
        "all 5 documents should still be in cache, found {}",
        open_docs
    );
}

/// Stress test: concurrent project validation and per-file validation
/// must not interfere with each other.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_concurrent_project_and_file_validation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();

    // Create 2 AGENTS.md files to trigger AGM-006
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root AGENTS").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub AGENTS").unwrap();

    // Create 5 SKILL.md files
    for i in 0..5 {
        let dir = temp_dir.path().join(format!("skill-{i}"));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("SKILL.md"),
            format!(
                "---\nname: project-skill-{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Project Skill {i}\n"
            ),
        )
        .unwrap();
    }

    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Open all 7 files: 2 AGENTS.md + 5 SKILL.md
    for path in [temp_dir.path().join("AGENTS.md"), sub.join("AGENTS.md")] {
        let uri = Url::from_file_path(&path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&path).unwrap(),
                },
            })
            .await;
    }
    for i in 0..5 {
        let path = temp_dir.path().join(format!("skill-{i}")).join("SKILL.md");
        let uri = Url::from_file_path(&path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&path).unwrap(),
                },
            })
            .await;
    }

    // Wait for the background project validation spawned by initialize() to
    // complete BEFORE starting the concurrent workload. This ensures the
    // explicit validate_project_rules_and_publish() call below is never
    // stale-dropped, making the post-run assertion deterministic.
    let sync_result = tokio::time::timeout(std::time::Duration::from_secs(10), async {
        loop {
            {
                let proj_diags = service.inner().project_level_diagnostics.read().await;
                if !proj_diags.is_empty() {
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await;
    assert!(
        sync_result.is_ok(),
        "initialize() background project validation did not complete within 10s"
    );

    let backend_project = service.inner().clone();

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut handles = Vec::new();

        // 1 task: project-level validation
        handles.push(tokio::spawn(async move {
            backend_project.validate_project_rules_and_publish().await;
        }));

        // 5 tasks: concurrent did_change on SKILL files
        for i in 0..5 {
            let backend = service.inner().clone();
            let path = temp_dir
                .path()
                .join(format!("skill-{i}"))
                .join("SKILL.md");
            let uri = Url::from_file_path(&path).unwrap();
            handles.push(tokio::spawn(async move {
                backend
                    .did_change(DidChangeTextDocumentParams {
                        text_document: VersionedTextDocumentIdentifier {
                            uri,
                            version: 2,
                        },
                        content_changes: vec![TextDocumentContentChangeEvent {
                            range: None,
                            range_length: None,
                            text: format!(
                                "---\nname: updated-skill-{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Updated {i}\n"
                            ),
                        }],
                    })
                    .await;
            }));
        }

        for handle in handles {
            handle.await.expect("task should not panic");
        }
    })
    .await;

    assert!(
        result.is_ok(),
        "concurrent project and file validation timed out"
    );

    // Because we waited for initialize()'s background validation to complete
    // before the concurrent block, the explicit validate_project_rules_and_publish
    // call above will not be stale-dropped. Assert diagnostics directly.
    let proj_diags = service.inner().project_level_diagnostics.read().await;
    assert!(
        !proj_diags.is_empty(),
        "project_level_diagnostics should be non-empty (AGM-006 from duplicate AGENTS.md)"
    );
    drop(proj_diags);

    // All 7 documents should still be in cache
    let open_docs = service.inner().documents.read().await.len();
    assert_eq!(
        open_docs, 7,
        "all 7 documents should still be in cache, found {}",
        open_docs
    );
}

/// Stress test: revalidation of many open documents after a single config
/// change must complete without panic.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_high_document_count_revalidation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let doc_count = 20usize;

    // Open 20 SKILL.md documents
    for i in 0..doc_count {
        let dir = temp_dir.path().join(format!("skill-{i}"));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("SKILL.md");
        std::fs::write(
            &path,
            format!(
                "---\nname: high-count-skill-{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# High Count {i}\n"
            ),
        )
        .unwrap();

        let uri = Url::from_file_path(&path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&path).unwrap(),
                },
            })
            .await;
    }

    // Single config change triggers revalidation of all open documents.
    // Wrapped in a timeout to catch deadlocks in for_each_bounded under load.
    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        service
            .inner()
            .did_change_configuration(DidChangeConfigurationParams {
                settings: serde_json::json!({ "severity": "Error" }),
            })
            .await;
    })
    .await;
    assert!(
        result.is_ok(),
        "high document count revalidation timed out after 30s"
    );

    let generation = service.inner().config_generation.load(Ordering::SeqCst);
    assert_eq!(
        generation, 1,
        "config_generation should be 1 after single config change, got {}",
        generation
    );

    let open_docs = service.inner().documents.read().await.len();
    assert_eq!(
        open_docs, doc_count,
        "all {} documents should still be in cache, found {}",
        doc_count, open_docs
    );
}

/// Stress test: concurrent hover requests during active validation must
/// not panic or deadlock.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_concurrent_hover_during_validation() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();
    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    let skill_path = temp_dir.path().join("SKILL.md");
    let content = "---\nname: hover-skill\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Hover Skill\n";
    std::fs::write(&skill_path, content).unwrap();

    let uri = Url::from_file_path(&skill_path).unwrap();

    // Open the document with frontmatter content
    service
        .inner()
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: content.to_string(),
            },
        })
        .await;

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut handles = Vec::new();

        // 10 tasks: concurrent did_change
        for i in 0..10 {
            let backend = service.inner().clone();
            let uri = uri.clone();
            handles.push(tokio::spawn(async move {
                backend
                    .did_change(DidChangeTextDocumentParams {
                        text_document: VersionedTextDocumentIdentifier {
                            uri,
                            version: (i + 2) as i32,
                        },
                        content_changes: vec![TextDocumentContentChangeEvent {
                            range: None,
                            range_length: None,
                            text: format!(
                                "---\nname: hover-v{i}\nversion: 1.0.0\nmodel: sonnet\n---\n\n# Hover V{i}\n"
                            ),
                        }],
                    })
                    .await;
            }));
        }

        // 10 tasks: concurrent hover at (1, 0) - the "name" key in frontmatter
        for _ in 0..10 {
            let backend = service.inner().clone();
            let uri = uri.clone();
            handles.push(tokio::spawn(async move {
                let _ = backend
                    .hover(HoverParams {
                        text_document_position_params: TextDocumentPositionParams {
                            text_document: TextDocumentIdentifier { uri },
                            position: Position {
                                line: 1,
                                character: 0,
                            },
                        },
                        work_done_progress_params: WorkDoneProgressParams::default(),
                    })
                    .await;
            }));
        }

        for handle in handles {
            handle.await.expect("task should not panic");
        }
    })
    .await;

    assert!(
        result.is_ok(),
        "concurrent hover during validation timed out"
    );

    let docs = service.inner().documents.read().await;
    assert!(
        docs.contains_key(&uri),
        "document should still be in cache after concurrent hover and changes"
    );
}

/// Stress test: 10 concurrent project validation runs must not corrupt
/// the generation counter or panic.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn test_stress_rapid_project_validation_generation_guard() {
    let (service, _socket) = LspService::new(Backend::new);

    let temp_dir = tempfile::tempdir().unwrap();

    // Create 2 AGENTS.md files to trigger AGM-006
    std::fs::write(temp_dir.path().join("AGENTS.md"), "# Root AGENTS").unwrap();
    let sub = temp_dir.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    std::fs::write(sub.join("AGENTS.md"), "# Sub AGENTS").unwrap();

    let root_uri = Url::from_file_path(temp_dir.path()).unwrap();
    service
        .inner()
        .initialize(InitializeParams {
            root_uri: Some(root_uri),
            ..Default::default()
        })
        .await
        .unwrap();

    // Wait for the initial background project validation to complete before
    // spawning concurrent runs. Assert the wait succeeded so a stalled
    // background task causes an explicit failure rather than a silent race.
    let init_sync = tokio::time::timeout(std::time::Duration::from_secs(10), async {
        loop {
            {
                let proj_diags = service.inner().project_level_diagnostics.read().await;
                if !proj_diags.is_empty() {
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
    })
    .await;
    assert!(
        init_sync.is_ok(),
        "initialize() background project validation did not complete within 10s"
    );

    // Open both AGENTS.md files
    for path in [temp_dir.path().join("AGENTS.md"), sub.join("AGENTS.md")] {
        let uri = Url::from_file_path(&path).unwrap();
        service
            .inner()
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri,
                    language_id: "markdown".to_string(),
                    version: 1,
                    text: std::fs::read_to_string(&path).unwrap(),
                },
            })
            .await;
    }

    let validation_count = 10usize;

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut handles = Vec::new();

        for _ in 0..validation_count {
            let backend = service.inner().clone();
            handles.push(tokio::spawn(async move {
                backend.validate_project_rules_and_publish().await;
            }));
        }

        for handle in handles {
            handle.await.expect("task should not panic");
        }
    })
    .await;

    assert!(result.is_ok(), "rapid project validation timed out");

    // Each call to validate_project_rules_and_publish does fetch_add(1),
    // plus the initial background run from initialize(). The generation
    // should be at least validation_count (10) but could be higher due to
    // the initial background run.
    let generation = service
        .inner()
        .project_validation_generation
        .load(Ordering::SeqCst);
    assert!(
        generation >= validation_count as u64,
        "project_validation_generation should be >= {}, got {}",
        validation_count,
        generation
    );
}

// ===== Document Version Tracking Tests =====

/// Test that document version is tracked when a document is opened.
#[tokio::test]
async fn test_document_version_tracked_on_open() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test").unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Test".to_string(),
            },
        })
        .await;

    let version = backend.get_document_version(&uri).await;
    assert_eq!(version, Some(1));
}

/// Test that document version is updated when a document changes.
#[tokio::test]
async fn test_document_version_updated_on_change() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test").unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Test".to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(1));

    backend
        .handle_did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "# Updated".to_string(),
            }],
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(2));
}

/// Test that document version is cleared when a document is closed.
#[tokio::test]
async fn test_document_version_cleared_on_close() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test").unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Test".to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(1));

    backend
        .handle_did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, None);
}

/// Test that get_document_version returns None for a URI that was never opened.
#[tokio::test]
async fn test_document_version_returns_none_for_unknown_uri() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let never_opened = temp_dir.path().join("never-opened.md");
    let uri = Url::from_file_path(&never_opened).unwrap();
    assert_eq!(backend.get_document_version(&uri).await, None);
}

/// Test that the version is updated even when content_changes is empty.
///
/// Per LSP spec, VersionedTextDocumentIdentifier.version is the authoritative
/// post-change version regardless of content. The version must always be stored
/// so that published diagnostics carry the correct version tag.
#[tokio::test]
async fn test_document_version_updated_even_on_empty_content_changes() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(&skill_path, "# Test").unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    // Open with version 1
    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "# Test".to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(1));

    // Send did_change with version 2 but an empty content_changes vec
    backend
        .handle_did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version: 2,
            },
            content_changes: vec![],
        })
        .await;

    // Version should be 2 because the version from VersionedTextDocumentIdentifier
    // is always authoritative per LSP spec.
    assert_eq!(backend.get_document_version(&uri).await, Some(2));
}

/// Test that multiple documents track independent versions.
#[tokio::test]
async fn test_multiple_documents_track_independent_versions() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();

    let path_a = temp_dir.path().join("a").join("SKILL.md");
    let path_b = temp_dir.path().join("b").join("SKILL.md");
    std::fs::create_dir_all(path_a.parent().unwrap()).unwrap();
    std::fs::create_dir_all(path_b.parent().unwrap()).unwrap();
    std::fs::write(&path_a, "# A").unwrap();
    std::fs::write(&path_b, "# B").unwrap();

    let uri_a = Url::from_file_path(&path_a).unwrap();
    let uri_b = Url::from_file_path(&path_b).unwrap();

    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri_a.clone(),
                language_id: "markdown".to_string(),
                version: 5,
                text: "# A".to_string(),
            },
        })
        .await;

    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri_b.clone(),
                language_id: "markdown".to_string(),
                version: 10,
                text: "# B".to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri_a).await, Some(5));
    assert_eq!(backend.get_document_version(&uri_b).await, Some(10));

    // Update only document A
    backend
        .handle_did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri_a.clone(),
                version: 6,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "# A updated".to_string(),
            }],
        })
        .await;

    assert_eq!(backend.get_document_version(&uri_a).await, Some(6));
    assert_eq!(backend.get_document_version(&uri_b).await, Some(10));
}

/// Integration-style test: open, change, and close a document and verify
/// the version state tracks correctly through the full lifecycle.
#[tokio::test]
async fn test_document_version_lifecycle_through_events() {
    let backend = Backend::new_test();

    let temp_dir = tempfile::tempdir().unwrap();
    let skill_path = temp_dir.path().join("SKILL.md");
    std::fs::write(
        &skill_path,
        "---\nname: lifecycle\nversion: 1.0.0\nmodel: sonnet\n---\n# Lifecycle Test\n",
    )
    .unwrap();
    let uri = Url::from_file_path(&skill_path).unwrap();

    // Phase 1: Not opened yet - no version tracked
    assert_eq!(backend.get_document_version(&uri).await, None);

    // Phase 2: Open with version 1
    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text:
                    "---\nname: lifecycle\nversion: 1.0.0\nmodel: sonnet\n---\n# Lifecycle Test\n"
                        .to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(1));

    // Phase 3: Change to version 2
    backend
        .handle_did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version: 2,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "---\nname: lifecycle\nversion: 2.0.0\nmodel: sonnet\n---\n# Lifecycle Test v2\n".to_string(),
            }],
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(2));

    // Phase 4: Another change to version 5 (versions may skip)
    backend
        .handle_did_change(DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version: 5,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: "---\nname: lifecycle\nversion: 3.0.0\nmodel: sonnet\n---\n# Lifecycle Test v3\n".to_string(),
            }],
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(5));

    // Phase 5: Close the document
    backend
        .handle_did_close(DidCloseTextDocumentParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, None);

    // Phase 6: Re-open with a new version - simulates client re-opening
    backend
        .handle_did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "markdown".to_string(),
                version: 1,
                text: "---\nname: lifecycle\nversion: 1.0.0\nmodel: sonnet\n---\n# Lifecycle Reopened\n".to_string(),
            },
        })
        .await;

    assert_eq!(backend.get_document_version(&uri).await, Some(1));
}