bynk-lsp 0.230.0

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

pub mod capability_fixes;
pub mod code_actions;
pub mod completion;
mod document_symbols;
pub mod documentation_request;
mod extract;
pub mod hover;
pub mod index_queries;
mod inlay_hints;
mod locals_nav;
pub mod position;
mod project;
mod publish;
pub mod sequence_request;
mod signature_help;
mod structure;
pub mod symbols;

use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::RwLock;
use tower_lsp::jsonrpc::Result as JsonRpcResult;
use tower_lsp::lsp_types::request::{
    GotoImplementationParams, GotoImplementationResponse, GotoTypeDefinitionParams,
    GotoTypeDefinitionResponse,
};
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server};

use crate::project::ProjectConfig;

const SERVER_NAME: &str = "bynkc-lsp";
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");

/// In-memory document state.
#[derive(Debug, Clone)]
struct DocumentState {
    text: String,
    version: i32,
}

/// v0.25 (ADR 0053): one analysis round's retained outputs — the binding
/// index plus the snapshots its spans are offsets into, and the open-doc
/// versions captured when the overlay was built (rename emits versioned
/// edits against exactly these versions).
#[derive(Debug)]
struct Analysis {
    /// Slice A: the canonicalised **project root** every path in this round
    /// resolves against. Was the single `src` directory; the round now covers
    /// every `include` tree, and ADR 0198 makes each file's path
    /// project-relative — so this is the one base that resolves all of them.
    project_root: PathBuf,
    index: bynk_check::index::ProjectIndex,
    /// Project-relative path → the analysed text.
    snapshots: std::collections::HashMap<PathBuf, String>,
    /// Project-relative path → the open document's version at analysis
    /// time (absent for files read from disk).
    versions: std::collections::HashMap<PathBuf, i32>,
    /// v0.26 (ADR 0054): project-relative path → the round's diagnostics,
    /// full `CompileError`s included — the suggestions `codeAction` serves
    /// ride on them. Every analysed file has an entry (clean files an empty
    /// one). Replaces the v0.25 categories-only field; the rename baseline
    /// derives from these via [`Self::diag_categories`].
    diagnostics: std::collections::HashMap<PathBuf, Vec<bynk_ide::Diagnostic>>,
    /// v0.27 (ADR 0056): project-relative path → the round's harvested
    /// inferred-type hints, spans against the analysed snapshots.
    hints: bynk_check::hints::FileHints,
    /// v0.99: project-relative path → the round's capability-requirement ledger,
    /// driving the materializable ghost `given` inlay hint, spans against the
    /// analysed snapshots.
    requirements: bynk_check::requirements::FileRequirements,
    /// v0.31 (ADR 0064): project-relative path → the round's local bindings
    /// with scope ranges, for locals navigation (references/definition/
    /// highlight), spans against the analysed snapshots.
    locals: bynk_check::locals::FileLocals,
    /// Slice 6: project-relative path → the round's expression types, spans
    /// against the analysed snapshots — backs go-to-type-definition.
    expr_types: bynk_check::expr_types::FileExprTypes,
    /// Slice 6b (ADR 0095): qualified unit name → its project source file(s),
    /// project-relative — backs document links (`uses`/`consumes` → source).
    unit_sources: std::collections::HashMap<String, Vec<PathBuf>>,
    /// #846: qualified context/adapter unit name → the cross-context/agent
    /// tables the `bynk/sequenceModel` request classifies handler calls
    /// against.
    sequence_info: std::collections::HashMap<String, bynk_ide::ContextSequenceInfo>,
    /// #848: qualified unit name → its doc-comment intra-doc-link search
    /// order — itself first, then its `uses` targets, then its `consumes`
    /// targets — backs intra-doc-link resolution in `document_link` and
    /// `hover`. See `bynk_ide::ProjectDiagnostics::doc_scope`.
    doc_scope: std::collections::HashMap<String, Vec<String>>,
}

impl Analysis {
    /// Per-file diagnostic categories — the rename validator's baseline,
    /// derived from the retained diagnostics.
    fn diag_categories(&self) -> Vec<(PathBuf, String)> {
        self.diagnostics
            .iter()
            .flat_map(|(path, diags)| {
                diags
                    .iter()
                    .map(|d| (path.clone(), d.error.category.to_string()))
            })
            .collect()
    }
}

/// One project's mutable state — the fields that were flat on `State` before
/// slice D, now one set per discovered project root. Every request routes by
/// URI (via `resolve_root`) to its owning entry, so two projects analyse,
/// version, and publish independently.
#[derive(Debug, Default)]
struct ProjectState {
    /// Parsed `bynk.toml` configuration for this root. Defaults for missing
    /// fields. Read live for the diagnostics mode/debounce and formatting;
    /// reloaded on a `bynk.toml` change (`did_change_watched_files`).
    config: ProjectConfig,
    /// v0.25: the latest analysis round's index + snapshots. References,
    /// rename, and the re-pointed definition/hover read this; positions
    /// convert against the analysed snapshots (v0.24 rule).
    analysis: Option<Arc<Analysis>>,
    /// v0.24: URIs that currently carry published project diagnostics — the
    /// previous round's dirty set, so newly-clean files get a clearing
    /// (empty) publish. Per-project (slice D): a round for this root must only
    /// clear its own files, never another project's.
    published: std::collections::HashSet<Url>,
    /// v0.24: debounce generation. Each change bumps it; a scheduled
    /// analysis runs only if it is still the latest when the delay elapses.
    /// Per-project: two projects debounce independently.
    analysis_generation: u64,
    /// Monotonic id handed to each analysis round as it *starts*. Together
    /// with `analysis_round_committed` this orders round completions: an old
    /// slow round must never overwrite a newer round's results (#513).
    /// Per-project (slice D): a global counter would let one project's round
    /// discard another's.
    analysis_round_started: u64,
    /// The id of the newest round whose results have been committed.
    analysis_round_committed: u64,
}

/// #733: the client's `workspace/*/refresh` support, per pull-based decoration,
/// captured at `initialize`. Each flag gates the corresponding round-commit
/// nudge in [`Backend::run_project_diagnostics`].
#[derive(Debug, Clone, Copy, Default)]
struct RefreshSupport {
    semantic_tokens: bool,
    inlay_hints: bool,
    code_lens: bool,
}

/// Mutable server state. Slice D: a map of projects (was one flat project),
/// plus the open buffers (client-global) and the workspace-folder seeds.
#[derive(Debug, Default)]
struct State {
    /// Discovered projects, keyed by **canonical project root** (Q4: the
    /// directory a file's `resolve_root` walk lands on — a `bynk.toml`, else an
    /// implicit `src/` parent). Empty in single-file mode. A request routes to
    /// its entry by URI; the entry is created lazily on first touch (open or
    /// request) and pruned when no folder covers it and it holds no open buffer.
    projects: std::collections::HashMap<PathBuf, ProjectState>,
    /// The workspace-folder roots the client has open (slice D). **Discovery
    /// seeds, not routing owners** (Q4): they bound where
    /// `did_change_workspace_folders` prunes, but a URI routes by its nearest
    /// enclosing `bynk.toml`, which may sit above every folder.
    folders: Vec<PathBuf>,
    /// Open documents keyed by URI — a client-global set; each doc routes to
    /// its project via `resolve_root`.
    docs: std::collections::HashMap<Url, DocumentState>,
    /// Slice E: whether the client advertised `didChangeWatchedFiles`
    /// **dynamic registration** at `initialize`. When set, `initialized`
    /// registers the file watchers server-side (so any client is notified);
    /// when not, the client is expected to supply them itself (as VS Code did
    /// before the extension's client-side watchers were removed).
    supports_dynamic_watchers: bool,
    /// #733: whether the client advertised `refresh_support` for each pull-based
    /// decoration at `initialize`. When set, a committed round asks the client to
    /// re-pull that decoration (`workspace/*/refresh`) — the "revalidate" half of
    /// serving `committed_analysis` stale while typing. Only sent when advertised,
    /// so a client that never supported it is never spammed with unknown requests.
    supports_refresh: RefreshSupport,
    /// Slice F: debounce generation for **single-file** buffers (no project),
    /// keyed by URI. The project path holds its generation in `ProjectState`;
    /// this is the same coalescing for a buffer that has no entry — a burst runs
    /// one `diagnose`, not one per keystroke. Cleared on `did_close`.
    single_file_generations: std::collections::HashMap<Url, u64>,
    /// #682: memoised URI → canonical project root routing (`None` for
    /// single-file mode is itself a cached answer), so the hot request path
    /// stops re-walking the filesystem and `canonicalize()`ing on every call.
    /// For a URI whose own path is fixed, routing depends only on `bynk.toml`
    /// presence among its ancestors — `find_source_root`'s `src`-ancestor
    /// fallback is a pure string match against that fixed path, with no
    /// filesystem I/O of its own, so it can't drift independently. That makes
    /// a `bynk.toml` create/delete/change the only event that can move an
    /// already-cached URI's route, and this is invalidated wholesale on it
    /// (`did_change_watched_files`). A workspace-folder change also clears it
    /// (`did_change_workspace_folders`) even though `resolve_canonical` never
    /// consults `folders` today — a defensive, effectively-free no-op kept in
    /// case that ever changes, not a correctness requirement. Bounded entries
    /// are never individually evicted (e.g. on `did_close`); only ever
    /// wholesale-cleared, which is judged an acceptable tradeoff — bounded by
    /// the distinct files touched in a session. See [`Backend::root_for_uri`].
    root_cache: std::collections::HashMap<Url, Option<PathBuf>>,
    /// #682: bumped every time `root_cache` is wholesale-cleared. `root_for_uri`
    /// resolves a cache miss off the `state` lock (a filesystem walk must not
    /// run while holding it); this closes the race where an invalidating clear
    /// lands *during* that walk — the write-back re-checks the generation and
    /// drops a stale answer instead of resurrecting it into the freshly-cleared
    /// cache.
    root_cache_generation: u64,
}

#[derive(Clone)]
pub struct Backend {
    client: Client,
    state: Arc<RwLock<State>>,
    /// Slice B (the freshness contract): serialises request-driven refreshes so
    /// concurrent index-backed requests after one edit coalesce onto a single
    /// round instead of each spawning its own. Held only across `analysis_for`'s
    /// refresh; never across a `state` lock.
    refresh_lock: Arc<tokio::sync::Mutex<()>>,
}

impl Backend {
    fn new(client: Client) -> Self {
        Self {
            client,
            state: Arc::new(RwLock::new(State::default())),
            refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
        }
    }

    /// Locate `bynk.toml` walking upward from the given path. Returns the
    /// project root (the directory containing `bynk.toml`) on success.
    fn find_project_root(start: &std::path::Path) -> Option<PathBuf> {
        let mut current = if start.is_file() {
            start.parent()?.to_path_buf()
        } else {
            start.to_path_buf()
        };
        loop {
            let candidate = current.join("bynk.toml");
            if candidate.is_file() {
                return Some(current);
            }
            current = current.parent()?.to_path_buf();
        }
    }

    /// Locate the nearest ancestor directory named `src`, walking upward from
    /// `start`. This is the implicit source root of a *rootless* tree — the
    /// same `src/`-without-`bynk.toml` layout `bynkc` compiles in its legacy
    /// single-tree mode (`bynkc/tests/e2e.rs` `compile_fixture`), which the
    /// compiler fixtures use. Returns that `src` directory.
    fn find_source_root(start: &std::path::Path) -> Option<PathBuf> {
        let mut current = if start.is_file() {
            start.parent()?.to_path_buf()
        } else {
            start.to_path_buf()
        };
        loop {
            if current.file_name().and_then(|n| n.to_str()) == Some("src") {
                return Some(current);
            }
            current = current.parent()?.to_path_buf();
        }
    }

    /// Resolve the analysis root for a path, with its config. A real
    /// `bynk.toml` project (config loaded from disk) takes precedence;
    /// otherwise (#485) fall back to the nearest enclosing `src/` as an
    /// implicit project so a multi-file commons in a rootless tree still
    /// analyses cross-file instead of dropping to sibling-blind single-file
    /// mode. `None` when neither is found — the caller stays single-file.
    fn resolve_root(start: &std::path::Path) -> Option<(PathBuf, project::ProjectConfig)> {
        if let Some(root) = Self::find_project_root(start) {
            let config = project::load_config(&root).unwrap_or_default();
            return Some((root, config));
        }
        // The implicit project root is the parent of `src`: with the default
        // `src_dir` ("src"), `run_project_diagnostics` re-derives exactly this
        // `src` tree as the analysis root, so every project-mode feature works
        // with no further plumbing.
        let src = Self::find_source_root(start)?;
        let root = src.parent()?.to_path_buf();
        Some((root, project::ProjectConfig::default()))
    }

    /// Slice D (Q4): the **canonical** project root that owns `uri`, with its
    /// config, or `None` for a file under no project (single-file mode). Routing
    /// is `resolve_root`'s walk-up — the same project `bynkc` attributes the file
    /// to — canonicalised so it matches the `projects` map key and every
    /// `Analysis.project_root`. Workspace folders do not enter here: a URI routes
    /// by its nearest enclosing `bynk.toml`, whatever folder it sits in.
    fn resolve_canonical(uri: &Url) -> Option<(PathBuf, project::ProjectConfig)> {
        let path = uri.to_file_path().ok()?;
        let (root, config) = Self::resolve_root(&path)?;
        Some((root.canonicalize().unwrap_or(root), config))
    }

    /// The canonical project root owning `uri`, or `None` in single-file mode.
    /// Uncached — walks the filesystem and `canonicalize()`s on every call.
    /// Kept for the one caller that must route off the `state` lock
    /// (`prune_orphaned_projects`, #682 DECISION B) and for tests exercising
    /// routing directly; every other caller wants the memoised
    /// [`Self::root_for_uri`].
    fn root_for_uri_uncached(uri: &Url) -> Option<PathBuf> {
        Self::resolve_canonical(uri).map(|(root, _)| root)
    }

    /// #682: the cached counterpart of `root_for_uri_uncached` — the canonical
    /// project root owning `uri`, memoised in `State.root_cache` so a repeated
    /// request for the same URI does not re-walk the filesystem. A miss runs
    /// the uncached walk and stores the result (`None` included — a file that
    /// routes to no project is itself a stable answer worth caching).
    ///
    /// The walk runs off the `state` lock (it is synchronous filesystem I/O),
    /// so a wholesale `root_cache.clear()` can land between the read that
    /// found the miss and the write that stores its answer — a `bynk.toml`
    /// created mid-walk would otherwise have this write resurrect the
    /// pre-creation (stale) route into the just-cleared cache, and unlike
    /// `prune_orphaned_projects`'s TOCTOU window this one would never
    /// self-heal. `root_cache_generation` closes it: the write-back only
    /// applies if no clear happened while the walk was in flight; otherwise
    /// the fresh answer is simply not cached (correct either way — just an
    /// uncached hit for that one request).
    async fn root_for_uri(&self, uri: &Url) -> Option<PathBuf> {
        let generation = {
            let state = self.state.read().await;
            if let Some(cached) = state.root_cache.get(uri) {
                return cached.clone();
            }
            state.root_cache_generation
        };
        let root = Self::root_for_uri_uncached(uri);
        let mut state = self.state.write().await;
        if Self::root_cache_write_is_current(generation, state.root_cache_generation) {
            state.root_cache.insert(uri.clone(), root.clone());
        }
        root
    }

    /// #682: whether a `root_for_uri` write-back computed while the cache was
    /// at `read_generation` should still be applied, given the cache is now at
    /// `current_generation` — `false` once an invalidating clear has bumped it
    /// past the read, meaning the walk's answer may already be stale. Pulled
    /// out of `root_for_uri` so the guard itself — the one thing standing
    /// between the fix and the TOCTOU it closes — is unit-testable without
    /// needing to actually win the race in real time.
    fn root_cache_write_is_current(read_generation: u64, current_generation: u64) -> bool {
        read_generation == current_generation
    }

    /// Slice E: every project root under `folder` — the folder's own
    /// `resolve_root` (a manifest at or above it, the folder-inside-a-project
    /// case) plus a bounded recursive walk collecting each directory that holds
    /// a `bynk.toml`. Roots are **canonical** (the `projects` map key). The walk
    /// skips the caches and heavy dirs it should never descend (`out`,
    /// `node_modules`, `target`, `.git`, and dot-dirs), and a **visited-set of
    /// canonicalised dirs** stops a symlink cycle (`ln -s . loop`) from recursing
    /// forever. Synchronous FS I/O — callers run it via `spawn_blocking`, off the
    /// executor. This is the "one tree-walk"
    /// [ADR 0204](../decisions/0204-per-workspace-project-state.md) §C named —
    /// shared by startup warming and added-folder warming.
    fn discover_projects_under(folder: &std::path::Path) -> Vec<PathBuf> {
        fn should_skip(name: &std::ffi::OsStr) -> bool {
            let name = name.to_string_lossy();
            matches!(name.as_ref(), "out" | "node_modules" | "target" | ".git")
                || name.starts_with('.')
        }
        fn walk(
            dir: &std::path::Path,
            out: &mut Vec<PathBuf>,
            visited: &mut std::collections::HashSet<PathBuf>,
        ) {
            // Guard against symlink cycles: a directory reached twice (by its
            // canonical path) is not descended again.
            let canon_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
            if !visited.insert(canon_dir.clone()) {
                return;
            }
            if dir.join("bynk.toml").is_file() && !out.contains(&canon_dir) {
                out.push(canon_dir);
            }
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() && !should_skip(&entry.file_name()) {
                    walk(&path, out, visited);
                }
            }
        }
        let mut roots = Vec::new();
        // A manifest at or above the folder (the folder sits inside a project).
        if let Some((root, _)) = Self::resolve_root(folder) {
            let canon = root.canonicalize().unwrap_or(root);
            roots.push(canon);
        }
        // The implicit-`src/` shape (#485): a `src/` tree with no `bynk.toml`.
        // `resolve_root` only finds a `src/` *ancestor*, so the folder-is-the-root
        // case (folder holds `src/`, no manifest) needs an explicit check — else
        // a rootless project would warm only lazily on first open, not at startup.
        if folder.join("src").is_dir() && !folder.join("bynk.toml").is_file() {
            let canon = folder
                .canonicalize()
                .unwrap_or_else(|_| folder.to_path_buf());
            if !roots.contains(&canon) {
                roots.push(canon);
            }
        }
        let mut visited = std::collections::HashSet::new();
        walk(folder, &mut roots, &mut visited);
        roots
    }

    /// Slice F: the single diagnostics-scheduler entry point. Route `uri` to its
    /// owning project (a debounced project round) or, if none, single-file mode
    /// (a debounced buffer `diagnose`). **One** generation-based debounce at the
    /// configured delay covers both — a burst coalesces to one analysis. Replaces
    /// `recompile_and_publish`, whose route + second hardcoded debounce stacked
    /// on `did_change`'s own sleep.
    async fn schedule_diagnostics(&self, uri: &Url) {
        // Slice D: route by URI to the owning project, creating its entry on
        // first touch (a file opened before any folder scan). Q4: the root is
        // the file's nearest enclosing `bynk.toml`, not its workspace folder.
        // #682: routing goes through the cache; the config is only loaded from
        // disk when the entry doesn't exist yet, not on every call.
        if let Some(root) = self.root_for_uri(uri).await {
            {
                let mut state = self.state.write().await;
                if !state.projects.contains_key(&root) {
                    let config = project::load_config(&root).unwrap_or_default();
                    state.projects.insert(
                        root.clone(),
                        ProjectState {
                            config,
                            ..Default::default()
                        },
                    );
                }
            }
            self.schedule_project_diagnostics(root).await;
        } else {
            self.schedule_single_file(uri.clone()).await;
        }
    }

    /// v0.24: debounce a project-wide analysis — each call bumps the project's
    /// generation; the spawned task runs only if still the latest after the
    /// delay, so a typing burst produces one analysis. Slice D: keyed on one
    /// project root, so two projects debounce independently. A no-op if the
    /// root's entry is gone (its folder was removed mid-debounce).
    ///
    /// Slice F: the delay is the project's **configured** `diagnostics_debounce_ms`
    /// (was a hardcoded 200 ms stacked on `did_change`'s own sleep — the two are
    /// now one debounce).
    async fn schedule_project_diagnostics(&self, root: PathBuf) {
        let (generation, debounce) = {
            let mut state = self.state.write().await;
            let Some(ps) = state.projects.get_mut(&root) else {
                return;
            };
            ps.analysis_generation += 1;
            (ps.analysis_generation, ps.config.diagnostics_debounce_ms)
        };
        let this = self.clone();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(debounce)).await;
            let superseded = match this.state.read().await.projects.get(&root) {
                Some(ps) => ps.analysis_generation != generation,
                None => true, // entry pruned — nothing to analyse
            };
            if superseded {
                return;
            }
            this.run_project_diagnostics(root).await;
        });
    }

    /// Slice F: the single-file counterpart to `schedule_project_diagnostics` —
    /// a buffer with no project. Bump the URI's generation, sleep the (default)
    /// configured delay, and run one `diagnose` only if still latest, so a burst
    /// coalesces to one run (before slice F single-file had no generation and ran
    /// once per keystroke).
    async fn schedule_single_file(&self, uri: Url) {
        let debounce = ProjectConfig::default().diagnostics_debounce_ms;
        let generation = {
            let mut state = self.state.write().await;
            let g = state
                .single_file_generations
                .entry(uri.clone())
                .or_insert(0);
            *g += 1;
            *g
        };
        let this = self.clone();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(debounce)).await;
            let current = this
                .state
                .read()
                .await
                .single_file_generations
                .get(&uri)
                .copied();
            if current != Some(generation) {
                return;
            }
            this.diagnose_single_file(&uri).await;
        });
    }

    /// Slice F: run `bynk_ide::diagnose` on one buffer and publish — the
    /// single-file leaf of the scheduler (extracted from `recompile_and_publish`).
    /// Best-effort: a malformed file produces diagnostics, not a hard failure.
    async fn diagnose_single_file(&self, uri: &Url) {
        let (text, version) = {
            let state = self.state.read().await;
            match state.docs.get(uri) {
                Some(d) => (d.text.clone(), d.version),
                None => return,
            }
        };
        let positions = crate::position::PositionMap::new(&text);
        let lsp_diags: Vec<Diagnostic> = bynk_ide::diagnose(&text)
            .into_iter()
            .map(|d| make_diagnostic(&d, &positions, uri))
            .collect();
        self.client
            .publish_diagnostics(uri.clone(), lsp_diags, Some(version))
            .await;
    }

    /// v0.24 (ADR 0052): one project-wide diagnostics round — overlay the
    /// open buffers over disk, analyse off the async runtime, convert spans
    /// against the **analysed snapshots**, and publish via the pure
    /// publish-plan (clears included).
    async fn run_project_diagnostics(&self, root: PathBuf) {
        let (round, root, canonical_root, overlay, versions, previously_dirty) = {
            let mut state = self.state.write().await;
            // Slice D: the round is for one project's entry. If it was pruned
            // (its folder removed) between scheduling and now, there is nothing
            // to analyse — bail.
            let Some(ps) = state.projects.get_mut(&root) else {
                return;
            };
            ps.analysis_round_started += 1;
            let round = ps.analysis_round_started;
            // Slice A: the analysis is rooted at the *project*, not at one
            // `include` tree, and every path it returns is project-relative
            // (ADR 0198) — so this is the base the overlay keys against too.
            let canonical_root = root.canonicalize().unwrap_or_else(|_| root.clone());
            let previously_dirty = ps.published.clone();
            let mut overlay = std::collections::HashMap::new();
            let mut versions = std::collections::HashMap::new();
            // Every open buffer overlays disk. A buffer belonging to another
            // project keys to an absolute path outside this root, so it is inert
            // here — discovery never matches it — and its `versions` entry is
            // skipped by the `strip_prefix` guard. So the round stays scoped to
            // this project without filtering the doc set.
            for (uri, doc) in &state.docs {
                if let Ok(p) = uri.to_file_path() {
                    let canonical = p.canonicalize().unwrap_or(p);
                    // v0.25: capture the version the overlay snapshot came
                    // from, keyed project-relative like the analysis output.
                    if let Ok(rel) = canonical.strip_prefix(&canonical_root) {
                        versions.insert(rel.to_path_buf(), doc.version);
                    }
                    overlay.insert(canonical, doc.text.clone());
                }
            }
            (
                round,
                root,
                canonical_root,
                overlay,
                versions,
                previously_dirty,
            )
        };

        // Slice A: manifest-aware, multi-root — the same trees `bynkc` compiles.
        let roots = bynk_ide::AnalysisRoots::Project(root.clone());
        let Ok(result) =
            tokio::task::spawn_blocking(move || bynk_ide::diagnose_project_with(&roots, &overlay))
                .await
        else {
            return;
        };

        let mut new_by_uri: std::collections::HashMap<Url, Vec<Diagnostic>> =
            std::collections::HashMap::new();
        // Slice B (DECISION C): the document version each file was analysed at,
        // keyed by URI — so the publish can carry it and the client can drop a
        // range computed against a buffer it has already edited past. `None` for
        // a file read from disk (no open buffer, no version).
        let mut version_by_uri: std::collections::HashMap<Url, Option<i32>> =
            std::collections::HashMap::new();
        let mut snapshots = std::collections::HashMap::new();
        let mut diagnostics: std::collections::HashMap<PathBuf, Vec<bynk_ide::Diagnostic>> =
            std::collections::HashMap::new();
        for file in &result.files {
            let abs = canonical_root.join(&file.source_path);
            let abs = abs.canonicalize().unwrap_or(abs);
            let Ok(uri) = Url::from_file_path(&abs) else {
                continue;
            };
            // Spans convert against the snapshot the analysis saw — never a
            // newer buffer (Settled, v0.24 proposal).
            let positions = crate::position::PositionMap::new(&file.text);
            let diags: Vec<Diagnostic> = file
                .diagnostics
                .iter()
                .map(|d| make_diagnostic(d, &positions, &uri))
                .collect();
            version_by_uri.insert(uri.clone(), versions.get(&file.source_path).copied());
            new_by_uri.insert(uri, diags);
            diagnostics.insert(file.source_path.clone(), file.diagnostics.clone());
            snapshots.insert(file.source_path.clone(), file.text.clone());
        }
        // v0.25: retain the round's index + snapshots for references/rename
        // and the binding-correct definition/hover. v0.26: plus the raw
        // diagnostics, for `codeAction` (the suggestions ride on them).
        {
            let analysis = Arc::new(Analysis {
                project_root: canonical_root.clone(),
                index: result.index.clone(),
                snapshots,
                versions,
                diagnostics,
                hints: result.hints,
                requirements: result.requirements,
                locals: result.locals,
                expr_types: result.expr_types,
                unit_sources: result.unit_sources,
                sequence_info: result.sequence_info,
                doc_scope: result.doc_scope,
            });
            let mut state = self.state.write().await;
            let Some(ps) = state.projects.get_mut(&root) else {
                return; // pruned mid-round
            };
            // Completion order is not start order: a slow old round finishing
            // after a newer one must be dropped, not committed (#513).
            if ps.analysis_round_committed >= round {
                return;
            }
            ps.analysis_round_committed = round;
            ps.analysis = Some(analysis);
        }
        // Project-level diagnostics with no single owning file surface at
        // position 0:0 rather than vanishing — on `bynk.toml` when it exists,
        // else (#485, implicit `src/` mode has no manifest) on the first
        // analysed file, so they anchor to a real, openable document.
        let unattributed_anchor = {
            let toml = root.join("bynk.toml");
            if toml.is_file() {
                Url::from_file_path(toml).ok()
            } else {
                result.files.first().and_then(|f| {
                    let abs = canonical_root.join(&f.source_path);
                    let abs = abs.canonicalize().unwrap_or(abs);
                    Url::from_file_path(abs).ok()
                })
            }
        };
        if !result.unattributed.is_empty()
            && let Some(anchor_uri) = unattributed_anchor
        {
            let entry = new_by_uri.entry(anchor_uri).or_default();
            for d in &result.unattributed {
                entry.push(Diagnostic {
                    range: Default::default(),
                    severity: Some(match d.severity {
                        bynk_syntax::Severity::Error => DiagnosticSeverity::ERROR,
                        bynk_syntax::Severity::Warning => DiagnosticSeverity::WARNING,
                    }),
                    code: Some(tower_lsp::lsp_types::NumberOrString::String(
                        d.error.category.to_string(),
                    )),
                    message: d.error.message.clone(),
                    ..Default::default()
                });
            }
        }

        let (publishes, dirty) = publish::publish_plan(&previously_dirty, new_by_uri);
        for (uri, diags) in publishes {
            // Slice B (DECISION C): stamp the publish with the version the round
            // analysed this file at (was `None`), so a client can reject a range
            // its buffer has moved past. A clearing publish for a now-absent file
            // carries no version — it has no entry in `version_by_uri`.
            let version = version_by_uri.get(&uri).copied().flatten();
            self.client.publish_diagnostics(uri, diags, version).await;
        }
        let still_current = {
            let mut state = self.state.write().await;
            if let Some(ps) = state.projects.get_mut(&root)
                && ps.analysis_round_committed == round
            {
                ps.published = dirty;
                true
            } else {
                false
            }
        };
        // #733: revalidate. Pull-based decorations are served from the committed
        // round (`committed_analysis`) without a forced re-analysis, so a fresh
        // round is invisible to the client until it re-pulls. Nudge it to — but
        // only for this round if a newer one has not already superseded it (that
        // one sends its own nudge), and only for decorations the client can
        // refresh. Fired on a detached task: `run_project_diagnostics` also runs
        // on the *request* path (a cursor request's forced refresh), and a
        // `workspace/*/refresh` awaits a client round-trip — spawning keeps that
        // off the request's critical path. Best-effort: a failed nudge just
        // leaves the client on the previous pull until its next request.
        if still_current {
            let refresh = self.state.read().await.supports_refresh;
            if refresh.semantic_tokens || refresh.inlay_hints || refresh.code_lens {
                let client = self.client.clone();
                tokio::spawn(async move {
                    if refresh.semantic_tokens {
                        let _ = client.semantic_tokens_refresh().await;
                    }
                    if refresh.inlay_hints {
                        let _ = client.inlay_hint_refresh().await;
                    }
                    if refresh.code_lens {
                        let _ = client.code_lens_refresh().await;
                    }
                });
            }
        }
    }

    /// Slice A: the analysis roots for the project that owns `uri` — the
    /// manifest's, resolved by the compiler's own discovery. `None` in
    /// single-file mode (no project root), where cross-file lookups are skipped.
    /// Slice D: routes by URI (Q4), so a completion in project B enumerates B's
    /// units, not the first project's.
    ///
    /// Replaces `project_src_root`, which returned `root.join(config.src_dir)`:
    /// one tree, chosen by reducing `[paths] include` to its first entry and
    /// ignoring `exclude`. That reduction is the defect slice A removed.
    async fn analysis_roots_for(&self, uri: &Url) -> Option<bynk_ide::AnalysisRoots> {
        Some(bynk_ide::AnalysisRoots::Project(
            self.root_for_uri(uri).await?,
        ))
    }

    /// The owning project's `.bynk` files, from the compiler's discovery —
    /// `exclude` and the `out`/`node_modules` caches honoured. Backs the unit
    /// enumeration completion does; `None` in single-file mode.
    async fn project_files(&self, uri: &Url) -> Option<Vec<PathBuf>> {
        let roots = self.analysis_roots_for(uri).await?;
        tokio::task::spawn_blocking(move || bynk_ide::discover_files(&roots))
            .await
            .ok()
    }

    /// v0.31: the def + use spans of the local under the cursor (def first), or
    /// `None` if the cursor is not on a local.
    fn local_sites(
        &self,
        analysis: &Analysis,
        rel: &std::path::Path,
        offset: usize,
    ) -> Option<Vec<bynk_syntax::span::Span>> {
        let text = analysis.snapshots.get(rel)?;
        let locals = analysis.locals.get(rel)?;
        crate::locals_nav::local_sites_at(locals, text, offset)
    }

    /// v0.31 (ADR 0064): the in-scope local bindings at the cursor, as
    /// `variable` completions, read from the **cached** analysis — so they
    /// survive the mid-edit buffer the current keystroke produced (the last
    /// good round's bindings around the cursor are what's wanted). Positions
    /// convert against the cached snapshot, like the other cached-round reads.
    async fn locals_completions(&self, uri: &Url, pos: Position) -> Vec<CompletionItem> {
        // Slice B: completion's locals sub-path resolves `pos` against the
        // round's snapshot (like `index_position`), so it refreshes too — the
        // one exposed reader the §4.2 table missed.
        let analysis = self.analysis_for(uri).await;
        let Some(analysis) = analysis else {
            return Vec::new();
        };
        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
            return Vec::new();
        };
        let (Some(text), Some(locals)) = (analysis.snapshots.get(&rel), analysis.locals.get(&rel))
        else {
            return Vec::new();
        };
        let Some(offset) = crate::position::position_to_offset(text, pos) else {
            return Vec::new();
        };
        bynk_check::locals::locals_at(locals, offset)
            .into_iter()
            .map(|b| CompletionItem {
                label: b.name.clone(),
                kind: Some(CompletionItemKind::VARIABLE),
                detail: Some(b.ty.clone()),
                ..Default::default()
            })
            .collect()
    }

    /// Convert same-file local spans to LSP `Location`s.
    fn local_locations(
        &self,
        analysis: &Analysis,
        rel: &std::path::Path,
        spans: &[bynk_syntax::span::Span],
    ) -> Vec<Location> {
        let Some(text) = analysis.snapshots.get(rel) else {
            return Vec::new();
        };
        let Ok(uri) = Url::from_file_path(analysis.project_root.join(rel)) else {
            return Vec::new();
        };
        spans
            .iter()
            .map(|s| Location {
                uri: uri.clone(),
                range: crate::position::span_to_range(text, *s),
            })
            .collect()
    }

    /// Slice 3 (ADR 0063): complete the members of a typed **value** receiver.
    /// Re-analyses the buffer rewritten so the receiver parses (the trailing
    /// `.partial` dropped), types the receiver via the retained `expr_types`,
    /// and maps its type to kernel methods + record fields. Silent (not
    /// necessarily empty — see below) when the receiver can't be typed (the
    /// file has errors — the clean-file ceiling).
    ///
    /// #596: additionally merges a bare `store` field receiver's own
    /// vocabulary (entry ops, and for `Map` the `.entries`/`.keys`/`.values`
    /// accessors) — dispatched by receiver *provenance* in the checker, which
    /// the typed `ty` alone can't distinguish from an ordinary `Query`-typed
    /// local (a bare store `Map` widens to `Ty::Query` too, ADR 0120). This
    /// half runs **independently of whether `type_receiver` succeeded**: it
    /// re-parses the buffer itself and needs no typed `ty` at all, so a `store`
    /// field still offers its entry ops/accessors even when an unresolved name
    /// *elsewhere* in the file bails the checker before it runs (the one
    /// clean-file-ceiling gap ADR 0094 didn't close) — a review on #812 flagged
    /// the earlier draft's single early return as undercutting that motivation.
    async fn value_member_completions(
        &self,
        uri: &Url,
        text: &str,
        offset: usize,
    ) -> Vec<CompletionItem> {
        let Some((rewritten, recv_offset)) = completion::value_receiver_rewrite(text, offset)
        else {
            return Vec::new();
        };
        let mut items: Vec<CompletionItem> = Vec::new();
        if let Some(ty) = self
            .type_receiver(uri, rewritten.clone(), recv_offset)
            .await
        {
            let files = self.project_files(uri).await;
            items.extend(
                completion::value_member_candidates(&ty, text, files.as_deref())
                    .into_iter()
                    .map(to_completion_item),
            );
        }
        let locals = self.fast_path_locals(uri, &rewritten).await;
        items.extend(
            completion::store_field_member_candidates(&rewritten, recv_offset, &locals)
                .into_iter()
                .map(to_completion_item),
        );
        items
    }

    /// #596: the current analysed round's locals for `uri`, only when its
    /// snapshot exactly matches `rewritten` — the same fast-path match
    /// [`Self::type_receiver`] uses. Empty (rather than forcing a synchronous
    /// re-analysis) when the round is stale or absent, so the store-field
    /// shadowing check degrades to "no local shadows the name".
    async fn fast_path_locals(
        &self,
        uri: &Url,
        rewritten: &str,
    ) -> Vec<bynk_check::locals::LocalBinding> {
        let Some(analysis) = self.project_analysis_for(uri).await else {
            return Vec::new();
        };
        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
            return Vec::new();
        };
        if analysis.snapshots.get(&rel).map(String::as_str) != Some(rewritten) {
            return Vec::new();
        }
        analysis.locals.get(&rel).cloned().unwrap_or_default()
    }

    /// v0.124 (slice 3): at `<expr> is <cursor>`, the scrutinee sum type's
    /// variants. The scrutinee is typed via `expr_types` (re-analysing through
    /// `type_receiver`, the value-member path), so it is subject to the clean-
    /// file ceiling and goes silent — never wrong — on a broken buffer.
    async fn is_pattern_completions(
        &self,
        uri: &Url,
        text: &str,
        offset: usize,
    ) -> Vec<CompletionItem> {
        let Some(scrut_off) = is_scrutinee_offset(text, offset) else {
            return Vec::new();
        };
        self.scrutinee_variant_completions(uri, text, scrut_off)
            .await
    }

    /// v0.128: at an arm-pattern-start inside a `match <expr> { … }`, the
    /// scrutinee sum type's variants — the deferred half of slice 3's
    /// `is`-pattern completion, sharing its scrutinee typing and candidate set.
    async fn match_arm_completions(
        &self,
        uri: &Url,
        text: &str,
        offset: usize,
    ) -> Vec<CompletionItem> {
        let Some(scrut_off) = match_scrutinee_offset(text, offset) else {
            return Vec::new();
        };
        self.scrutinee_variant_completions(uri, text, scrut_off)
            .await
    }

    /// The variants of the scrutinee whose last character is at `scrut_off` — the
    /// shared tail of `is`/`match` pattern completion. Types the scrutinee via
    /// `expr_types` (the clean-file ceiling; silent, never wrong, on a broken
    /// buffer) and offers its variants; empty for a non-sum, non-`Result`/`Option`
    /// scrutinee. v0.145 (ADR 0169): `Result`/`Option` scrutinees now fire too
    /// (`variants_for_ty`), not only user-declared sums.
    async fn scrutinee_variant_completions(
        &self,
        uri: &Url,
        text: &str,
        scrut_off: usize,
    ) -> Vec<CompletionItem> {
        let Some(ty) = self.type_receiver(uri, text.to_string(), scrut_off).await else {
            return Vec::new();
        };
        let files = self.project_files(uri).await;
        completion::variants_for_ty(&ty, text, files.as_deref())
            .into_iter()
            .map(to_completion_item)
            .collect()
    }

    /// v0.145 (ADR 0169): at `OuterVariant(‸` inside a match arm-pattern, the
    /// payload field type's variants — e.g. `Ok`/`Err` inside `Some(‸)` on an
    /// `Option[Result[…]]` scrutinee. `match_scrutinee_offset` deliberately bails
    /// on a nested constructor; `nested_pattern_offset` targets exactly it,
    /// yielding the scrutinee offset and the outer variant. Types the scrutinee
    /// via the same clean-file ceiling and resolves the payload type.
    async fn nested_pattern_completions(
        &self,
        uri: &Url,
        text: &str,
        offset: usize,
    ) -> Vec<CompletionItem> {
        let Some((scrut_off, variant)) = nested_pattern_offset(text, offset) else {
            return Vec::new();
        };
        let Some(ty) = self.type_receiver(uri, text.to_string(), scrut_off).await else {
            return Vec::new();
        };
        let files = self.project_files(uri).await;
        completion::nested_variant_completions(&ty, &variant, text, files.as_deref())
            .into_iter()
            .map(to_completion_item)
            .collect()
    }

    /// v0.32 (ADR 0065): the type of a receiver expression at `recv_offset` in a
    /// buffer `rewritten` so it parses — re-analyse the overlay and query the
    /// retained `expr_types`. Shared by value-member completion and signature
    /// help; `None` when the file doesn't check clean (the clean-file ceiling).
    async fn type_receiver(
        &self,
        uri: &Url,
        rewritten: String,
        recv_offset: usize,
    ) -> Option<bynk_check::checker::Ty> {
        let roots = self.analysis_roots_for(uri).await?;
        let project_root = roots.project_root().to_path_buf();
        let canonical_root = project_root
            .canonicalize()
            .unwrap_or_else(|_| project_root.clone());
        let cur = uri.to_file_path().ok()?;
        let cur = cur.canonicalize().unwrap_or(cur);
        // Slice A: project-relative, matching the round's identity (ADR 0198).
        let rel = cur.strip_prefix(&canonical_root).ok()?.to_path_buf();
        // Overlay every open doc, with this one rewritten so it parses.
        let overlay = {
            let state = self.state.read().await;
            let mut ov = std::collections::HashMap::new();
            for (u, doc) in &state.docs {
                if let Ok(p) = u.to_file_path() {
                    let canonical = p.canonicalize().unwrap_or(p);
                    let t = if u == uri {
                        rewritten.clone()
                    } else {
                        doc.text.clone()
                    };
                    ov.insert(canonical, t);
                }
            }
            ov
        };
        // Fast path (#513): completion fires on every `.` keystroke, and the
        // rewritten buffer (the trailing `.`-segment removed so it parses) is
        // usually byte-identical to the snapshot the last debounced round
        // analysed. Reuse that round's expression types instead of running a
        // synchronous whole-project re-analysis on the request path.
        if let Some(analysis) = self.project_analysis_for(uri).await
            && analysis.snapshots.get(&rel).map(String::as_str) == Some(rewritten.as_str())
            && let Some((_, entries)) = analysis.expr_types.iter().find(|(p, _)| **p == rel)
        {
            return bynk_check::expr_types::type_at_offset(entries, recv_offset).cloned();
        }
        let result =
            tokio::task::spawn_blocking(move || bynk_ide::diagnose_project_with(&roots, &overlay))
                .await
                .ok()?;
        let (_, entries) = result.expr_types.iter().find(|(p, _)| **p == rel)?;
        bynk_check::expr_types::type_at_offset(entries, recv_offset).cloned()
    }

    /// Slice D: the committed analysis for one project root, ungated — the raw
    /// last round, or `None` if the root has no entry or has not analysed yet.
    async fn project_analysis(&self, root: &std::path::Path) -> Option<Arc<Analysis>> {
        self.state.read().await.projects.get(root)?.analysis.clone()
    }

    /// The owning project's committed analysis for `uri`, ungated. For callers
    /// that reuse a round opportunistically (completion's receiver-typing fast
    /// path); the freshness gate is [`Self::analysis_for`].
    async fn project_analysis_for(&self, uri: &Url) -> Option<Arc<Analysis>> {
        let root = self.root_for_uri(uri).await?;
        self.project_analysis(&root).await
    }

    /// Ensure `root` has an entry (created with `config` if absent) and a
    /// committed analysis (one round run if none yet), and return it. For the
    /// cross-project workspace-symbol scan, which must answer over every project
    /// including ones no request has warmed. `None` if the round produced none.
    async fn ensure_project_analysed(
        &self,
        root: PathBuf,
        config: ProjectConfig,
    ) -> Option<Arc<Analysis>> {
        {
            let mut state = self.state.write().await;
            state
                .projects
                .entry(root.clone())
                .or_insert_with(|| ProjectState {
                    config,
                    ..Default::default()
                });
        }
        if let Some(a) = self.project_analysis(&root).await {
            return Some(a);
        }
        self.refresh_now(root.clone()).await;
        self.project_analysis(&root).await
    }

    /// Slice D (Q4 lifecycle): drop every project no longer reachable from a
    /// workspace folder **and** holding no open buffer, clearing its published
    /// diagnostics. A project is retained while some remaining folder relates to
    /// it (one is a path-prefix of the other — a file under that folder can still
    /// route to the root) or while any open buffer routes to it. Shared by the
    /// two events that can orphan a project: a folder leaving
    /// (`did_change_workspace_folders`) and its last buffer closing (`did_close`)
    /// — a project falls only when *both* its seed and its buffers are gone.
    /// Returns the URIs whose diagnostics were cleared so the caller can publish
    /// the clears (done outside the lock).
    async fn prune_orphaned_projects(&self) -> Vec<Url> {
        // #733: `root_for_uri_uncached` canonicalises and walks the filesystem
        // up to a `bynk.toml` for every open buffer — syscalls that must not run
        // while holding `state.write()`. Snapshot the inputs under a short read
        // lock, resolve the open roots off the lock, then take the write lock
        // only to mutate `projects`.
        //
        // #682 (DECISION B): this stays on the *uncached* router rather than
        // `root_for_uri` — pruning is not hot (it fires only on folder-removal
        // or close), and it runs inside a synchronous `filter_map` off the
        // lock, where an async, cache-consulting router can't be called inline
        // without either re-locking `state` here (defeating the point of
        // computing `open_roots` off-lock) or restructuring this into an async
        // stream. This opens a small TOCTOU window: `orphaned` is
        // computed against live `state.projects` under the write lock but against
        // the *snapshot's* `folders`/`open_roots`, so a `did_open` that lands in
        // between — newly covering a root — is not yet in `open_roots` and that
        // root could be pruned here. It is self-healing: the pruning callers
        // (`did_close`, `did_change_workspace_folders`) only ever *remove*
        // coverage, so a racing `did_open` re-creates the entry the moment that
        // buffer routes/analyses (`schedule_diagnostics` → a lazily-created
        // `ProjectState`) — its diagnostics clear-then-repopulate, never a
        // permanently-dropped project.
        let (folders, open_uris) = {
            let state = self.state.read().await;
            (
                state.folders.clone(),
                state.docs.keys().cloned().collect::<Vec<_>>(),
            )
        };
        let open_roots: std::collections::HashSet<PathBuf> = open_uris
            .iter()
            .filter_map(Self::root_for_uri_uncached)
            .collect();
        let covered = |root: &std::path::Path| {
            folders
                .iter()
                .any(|f| f.starts_with(root) || root.starts_with(f))
                || open_roots.contains(root)
        };
        let mut state = self.state.write().await;
        let orphaned: Vec<PathBuf> = state
            .projects
            .keys()
            .filter(|r| !covered(r))
            .cloned()
            .collect();
        let mut to_clear = Vec::new();
        for root in orphaned {
            if let Some(ps) = state.projects.remove(&root) {
                to_clear.extend(ps.published);
            }
        }
        to_clear
    }

    /// Slice E: discover and warm every project under `folders` — create each
    /// entry (idempotent, keyed by canonical root) and schedule its round — so a
    /// workspace shows diagnostics without a file being opened. Non-blocking:
    /// entries are created synchronously (routing is immediately correct) and the
    /// rounds run on the debounce path. Shared by `initialized` (all folders) and
    /// the `did_change_workspace_folders` added branch (the new folders).
    async fn warm_projects(&self, folders: &[PathBuf]) {
        if folders.is_empty() {
            return;
        }
        // Discover off the lock **and** off the executor: the walk is synchronous
        // FS I/O, so run it on a blocking thread rather than stalling an async
        // worker while a workspace tree is scanned.
        let folders = folders.to_vec();
        let roots = tokio::task::spawn_blocking(move || {
            let mut roots: Vec<PathBuf> = Vec::new();
            for folder in &folders {
                for root in Self::discover_projects_under(folder) {
                    if !roots.contains(&root) {
                        roots.push(root);
                    }
                }
            }
            roots
        })
        .await
        .unwrap_or_default();
        for root in roots {
            let config = project::load_config(&root).unwrap_or_default();
            {
                let mut state = self.state.write().await;
                state
                    .projects
                    .entry(root.clone())
                    .or_insert_with(|| ProjectState {
                        config,
                        ..Default::default()
                    });
            }
            self.schedule_project_diagnostics(root).await;
        }
    }

    /// Slice E: register the `workspace/didChangeWatchedFiles` capability with
    /// the client — once, with folder-independent globs (`**/*.bynk`,
    /// `**/bynk.toml`), per Q4 (ADR 0204 §D). So a client that supports dynamic
    /// registration is notified of source and manifest changes without watching
    /// files itself. Best-effort: a registration failure is logged, not fatal.
    async fn register_file_watchers(&self) {
        use tower_lsp::lsp_types::{
            DidChangeWatchedFilesRegistrationOptions, FileSystemWatcher, GlobPattern, Registration,
        };
        let watchers = ["**/*.bynk", "**/bynk.toml"]
            .into_iter()
            .map(|g| FileSystemWatcher {
                glob_pattern: GlobPattern::String(g.to_string()),
                kind: None, // create | change | delete
            })
            .collect();
        let registration = Registration {
            id: "bynk-watched-files".to_string(),
            method: "workspace/didChangeWatchedFiles".to_string(),
            register_options: serde_json::to_value(DidChangeWatchedFilesRegistrationOptions {
                watchers,
            })
            .ok(),
        };
        if let Err(e) = self.client.register_capability(vec![registration]).await {
            self.client
                .log_message(
                    MessageType::WARNING,
                    format!("bynkc-lsp: file-watcher registration failed: {e}"),
                )
                .await;
        }
    }

    /// The `bynk.toml` config governing `uri` — its project's, or the default
    /// (single-file mode). Backs the per-file diagnostics mode/debounce and the
    /// formatting options, which now differ by project.
    async fn config_for(&self, uri: &Url) -> ProjectConfig {
        let Some(root) = self.root_for_uri(uri).await else {
            return ProjectConfig::default();
        };
        self.state
            .read()
            .await
            .projects
            .get(&root)
            .map(|p| p.config.clone())
            .unwrap_or_default()
    }

    /// Slice B — the freshness contract (Q3, settled #663). The analysis a
    /// request must answer from, **current for `uri`**: cold start triggers a
    /// round; a round that predates `uri`'s buffer triggers a refresh.
    ///
    /// The client's request position refers to `uri`'s current document
    /// version — messages are ordered, so `docs[uri].version` reflects every
    /// `didChange` sent before the request. The returned analysis is guaranteed
    /// to have analysed *that* version of `uri`, so `position_to_offset` against
    /// its snapshot is never resolved against text the user edited past.
    ///
    /// Slice D: routes to the project that owns `uri` (Q4) before gating, so the
    /// freshness check is against *that* project's round. A file under no
    /// project (single-file mode) is never index-answerable — decline.
    ///
    /// Returns `None` — decline, per Q3 — only when the request cannot be
    /// answered at the version the client holds: single-file mode (no project),
    /// a file outside every `include` root (never a snapshot key), or a
    /// concurrent edit that moved past the refresh (rare; the next request is
    /// current). Never returns an analysis whose snapshot for `uri` is stale.
    async fn analysis_for(&self, uri: &Url) -> Option<Arc<Analysis>> {
        let root = self.root_for_uri(uri).await?;
        // The version the request's position is stated against. `None` when the
        // file is not an open buffer — then any round is as authoritative as it
        // gets (nothing newer to be stale against), so the freshness gate is a
        // no-op and only cold start matters.
        let want = self.state.read().await.docs.get(uri).map(|d| d.version);
        let current = |a: &Arc<Analysis>| {
            let Some(rel) = Self::uri_to_rel(a, uri) else {
                return false; // unmappable URI — cannot be answered
            };
            // The file must actually be *analysed* (a snapshot key), not merely
            // have a version entry: `versions` is built from open docs, so a
            // file open but outside every `include` root has a version and no
            // snapshot. Such a file is never answerable — decline.
            if !a.snapshots.contains_key(&rel) {
                return false;
            }
            match want {
                // Open buffer: the analysed snapshot must be at the client's
                // version, or the position resolves against text edited past.
                Some(v) => a.versions.get(&rel) == Some(&v),
                // Not an open buffer (a closed/disk file, e.g. a goto target):
                // the analysed round is authoritative — nothing newer to lag.
                None => true,
            }
        };

        if let Some(a) = self.project_analysis(&root).await
            && current(&a)
        {
            return Some(a);
        }

        // Refresh. The lock serialises concurrent requests: the first runs the
        // round, the rest wait and then find it already current below — so N
        // requests after one edit share one round, not N. (One lock across all
        // projects is fine — a refresh holds it only across its own round.)
        let _guard = self.refresh_lock.lock().await;
        if let Some(a) = self.project_analysis(&root).await
            && current(&a)
        {
            return Some(a);
        }
        self.refresh_now(root.clone()).await;
        let a = self.project_analysis(&root).await?;
        // Strict: only answer if the fresh round is actually current for `uri`.
        // An edit that landed during the round leaves us behind — decline, and
        // the next request refreshes again. Never a position against stale text.
        current(&a).then_some(a)
    }

    /// #733 — the non-refreshing gate for **pull-based decoration requests**
    /// (`semanticTokens`, `inlayHint`, `codeLens`, `documentLink`, `codeAction`).
    /// Returns the last committed round for `uri`'s project **as-is**, without
    /// forcing a synchronous re-analysis on the request path.
    ///
    /// Why this is safe where [`Self::analysis_for`] is not: these handlers
    /// resolve nothing against the client's *live* cursor — every range and span
    /// they emit converts against the round's own `snapshots` (or, for
    /// `document_link`, against live text plus the project-level `unit_sources`
    /// map). So a committed round lagging the buffer by at most one debounce
    /// cycle is internally consistent; the strict version match `analysis_for`
    /// demands is stronger than a decoration needs. The editor auto-fires these
    /// on every `didChange`, so forcing a whole-project round here is exactly
    /// what defeated the debounce (#733).
    ///
    /// This is stale-while-revalidate: serve the committed round now; the
    /// already-scheduled debounce round is the revalidation, and on its commit
    /// [`Self::run_project_diagnostics`] nudges the client to re-pull via
    /// `workspace/*/refresh`. Cursor requests keep the strict gate.
    ///
    /// `None` — the handler returns empty — when the file is under no project, is
    /// outside every `include` root (never a snapshot key), or no round has
    /// committed yet (cold start; the scheduled round will produce one and the
    /// client re-pulls on the refresh nudge).
    async fn committed_analysis(&self, uri: &Url) -> Option<Arc<Analysis>> {
        let root = self.root_for_uri(uri).await?;
        let a = self.project_analysis(&root).await?;
        // Must actually be analysed (a snapshot key), not merely version-tracked
        // — the handler converts its spans against this snapshot.
        let rel = Self::uri_to_rel(&a, uri)?;
        a.snapshots.contains_key(&rel).then_some(a)
    }

    /// Slice B: the analysis for a handler that emits **multi-file versioned
    /// edits** — today, `rename`. Per-URI freshness ([`Self::analysis_for`]) is
    /// not enough here: a rename touches every file that references the symbol,
    /// and each edit is stamped with *that* file's analysed version, so the
    /// round must be current for **every open buffer**, not just the cursor's.
    ///
    /// Without this, a buffer edited since the last round but not under the
    /// cursor keeps its stale version in the round; `rename`'s edit for it is
    /// then stamped with that old version and the client rejects the whole
    /// operation (VS Code: "document changed since the refactoring was
    /// requested"). This restores the whole-project guarantee the pre-v0.179
    /// `fresh_analysis` gave — as a version-aware refresh, not an unconditional
    /// one. Returns `None` on the same terms as `analysis_for` (no project, or a
    /// concurrent edit that raced the refresh).
    ///
    /// Slice D: takes the rename's project `root` — a rename spans one project
    /// (the symbol and its references live under one root), so the round must
    /// cover *that* project's open buffers. A buffer in another project strips
    /// against a different `project_root`, so `uri_to_rel` returns `None` for it
    /// and it does not gate this rename.
    async fn analysis_covering_open_buffers(
        &self,
        root: &std::path::Path,
    ) -> Option<Arc<Analysis>> {
        // Every open buffer that maps into the project must be analysed at its
        // current version. A buffer outside the project (no snapshot key) is not
        // part of a project rename and does not gate it.
        let all_current =
            |a: &Arc<Analysis>, docs: &std::collections::HashMap<Url, DocumentState>| {
                docs.iter()
                    .all(|(uri, doc)| match Self::uri_to_rel(a, uri) {
                        Some(rel) if a.snapshots.contains_key(&rel) => {
                            a.versions.get(&rel) == Some(&doc.version)
                        }
                        _ => true,
                    })
            };

        {
            let state = self.state.read().await;
            if let Some(a) = state.projects.get(root).and_then(|p| p.analysis.clone())
                && all_current(&a, &state.docs)
            {
                return Some(a);
            }
        }
        let _guard = self.refresh_lock.lock().await;
        {
            let state = self.state.read().await;
            if let Some(a) = state.projects.get(root).and_then(|p| p.analysis.clone())
                && all_current(&a, &state.docs)
            {
                return Some(a);
            }
        }
        self.refresh_now(root.to_path_buf()).await;
        let state = self.state.read().await;
        let a = state.projects.get(root).and_then(|p| p.analysis.clone())?;
        all_current(&a, &state.docs).then_some(a)
    }

    /// Run a round now for one project, superseding any pending debounced one.
    /// Bumping the project's generation makes a scheduled round (which checks it
    /// before running) bail, so a request-driven refresh does not race a
    /// redundant debounce round that would produce the same result 200 ms later.
    async fn refresh_now(&self, root: PathBuf) {
        if let Some(ps) = self.state.write().await.projects.get_mut(&root) {
            ps.analysis_generation += 1;
        }
        self.run_project_diagnostics(root).await;
    }

    /// Map a request URI to the analysis' project-relative path.
    fn uri_to_rel(analysis: &Analysis, uri: &Url) -> Option<PathBuf> {
        let p = uri.to_file_path().ok()?;
        let canonical = p.canonicalize().unwrap_or(p);
        // Slice A: one `strip_prefix` still, but against the *project* root —
        // which is total across `include` trees, where the old `src` base could
        // only ever name files in one of them. A file under no root strips fine
        // and simply misses every lookup, which is correct: it was not analysed.
        canonical
            .strip_prefix(&analysis.project_root)
            .ok()
            .map(|r| r.to_path_buf())
    }

    /// #302: like [`Self::uri_to_rel`], but for a URI whose file does not
    /// exist yet — `willRenameFiles`' `new_uri`, named before the physical
    /// move happens. `Path::canonicalize` requires the path to exist, so
    /// `uri_to_rel`'s fallback (`unwrap_or(p)`, dead code for every other
    /// caller, which only ever resolves existing files) would silently keep
    /// the client's raw, non-canonical path — mismatching `project_root`
    /// (always canonical) whenever the workspace sits behind a symlink (macOS
    /// `/tmp` → `/private/tmp` being the common case), and the rename would
    /// quietly produce no edit. Canonicalizing the *parent* directory
    /// instead — it does exist — and rejoining the file name sidesteps that.
    fn uri_to_rel_for_new_path(analysis: &Analysis, uri: &Url) -> Option<PathBuf> {
        let p = uri.to_file_path().ok()?;
        let file_name = p.file_name()?;
        let parent = p.parent()?;
        let canonical_parent = parent
            .canonicalize()
            .unwrap_or_else(|_| parent.to_path_buf());
        canonical_parent
            .join(file_name)
            .strip_prefix(&analysis.project_root)
            .ok()
            .map(|r| r.to_path_buf())
    }

    /// Slice 6a follow-up (ADR 0095): if `pos` sits on a `uses`/`consumes` unit
    /// name, the location of that unit's source (its first file, at the top —
    /// units aren't index symbols, so there is no finer def span to land on).
    /// Spans come from the live buffer; the target from the round's unit→source
    /// map. `None` for a first-party/unresolved unit or a non-unit position.
    async fn unit_reference_definition(&self, uri: &Url, pos: Position) -> Option<Location> {
        // Slice B: the position is resolved against *live* text (no stale-offset
        // risk), but the `uses`/`consumes` → source lookup reads the round's
        // `unit_sources`, so route that through the gate — fresh or decline,
        // never a stale unit map. Cheap here: `goto_definition` already
        // refreshed via `index_position`, so this hits the current-round path.
        let analysis = self.analysis_for(uri).await;
        let text = self
            .state
            .read()
            .await
            .docs
            .get(uri)
            .map(|d| d.text.clone());
        let (text, analysis) = (text?, analysis?);
        let offset = cursor_offset(&text, pos);
        for (unit, span) in crate::symbols::unit_reference_spans(&text) {
            if span.start <= offset && offset <= span.end {
                let rel = analysis.unit_sources.get(&unit)?.first()?;
                let target = Url::from_file_path(analysis.project_root.join(rel)).ok()?;
                return Some(Location {
                    uri: target,
                    range: Range::default(),
                });
            }
        }
        None
    }

    /// Convert an index site to an LSP location, spans against the analysed
    /// snapshot (v0.24 rule).
    fn site_to_location(
        analysis: &Analysis,
        site: &bynk_check::index::SiteRef,
    ) -> Option<Location> {
        let text = analysis.snapshots.get(&site.path)?;
        let abs = analysis.project_root.join(&site.path);
        let uri = Url::from_file_path(abs).ok()?;
        Some(Location {
            uri,
            range: crate::position::span_to_range(text, site.span),
        })
    }

    /// v0.34 (ADR 0067): build a `CallHierarchyItem` for an index symbol from
    /// its key + definition site. The key is round-tripped through `data` so
    /// the incoming/outgoing follow-ups resolve straight off it, never
    /// re-inferring from a position.
    fn call_hierarchy_item(
        analysis: &Analysis,
        key: &bynk_check::index::SymbolKey,
        def: &bynk_check::index::SiteRef,
    ) -> Option<CallHierarchyItem> {
        let location = Self::site_to_location(analysis, def)?;
        Some(CallHierarchyItem {
            name: key.name.clone(),
            kind: lsp_symbol_kind(key.kind),
            tags: None,
            detail: Some(key.unit.clone()),
            uri: location.uri,
            range: location.range,
            selection_range: location.range,
            data: serde_json::to_value(SerKey::from(key)).ok(),
        })
    }

    /// The call-site ranges (`fromRanges`) for a call relation, each converted
    /// against its file's analysed snapshot.
    fn call_ranges(analysis: &Analysis, sites: &[&bynk_check::index::SiteRef]) -> Vec<Range> {
        sites
            .iter()
            .filter_map(|s| {
                let text = analysis.snapshots.get(&s.path)?;
                Some(crate::position::span_to_range(text, s.span))
            })
            .collect()
    }

    /// v0.28 (ADR 0057): the shared body of both semantic-tokens requests —
    /// resolve the cached round, convert the optional range against the
    /// analysed snapshot, and run the pure producer. Empty when no round is
    /// cached or the file is outside the project.
    async fn semantic_tokens_for(&self, uri: &Url, range: Option<Range>) -> Vec<SemanticToken> {
        // #733: serve the last committed round without forcing a re-analysis —
        // tokens convert against the round's own snapshot, so a one-cycle lag is
        // consistent, and the client re-pulls on the round-commit refresh nudge.
        let analysis = self.committed_analysis(uri).await;
        let Some(analysis) = analysis else {
            return Vec::new();
        };
        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
            return Vec::new();
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Vec::new();
        };
        let span = match range {
            None => None,
            // The requested range converts against the analysed snapshot,
            // like the spans it is intersected with.
            Some(r) => {
                let (Some(start), Some(end)) = (
                    crate::position::position_to_offset(text, r.start),
                    crate::position::position_to_offset(text, r.end),
                ) else {
                    return Vec::new();
                };
                Some(bynk_syntax::span::Span::new(start, end))
            }
        };
        let lt = analysis
            .locals
            .get(&rel)
            .map(|l| crate::locals_nav::local_token_sites(l, text))
            .unwrap_or_default();
        // v0.140 (ADR 0163): handler-annotation spans (`@cache` name + argument
        // labels), classified as `decorator`. Parsed from the snapshot here, off
        // the index-read path (mirroring how locals are precomputed).
        let dt = crate::symbols::handler_annotation_token_spans(text);
        crate::index_queries::semantic_tokens(&analysis.index, &lt, &dt, &rel, text, span)
    }

    /// The (analysis, rel-path, snapshot byte offset) for a request
    /// position — the shared front half of every index-backed handler.
    async fn index_position(
        &self,
        uri: &Url,
        position: Position,
    ) -> Option<(Arc<Analysis>, PathBuf, usize)> {
        // Slice B: `analysis_for` guarantees the round analysed `uri`'s current
        // version, so `position_to_offset` resolves against the same text the
        // client's position refers to — the `fresh` flag every caller used to
        // pass is gone (freshness is the contract now, not a per-call choice).
        let analysis = self.analysis_for(uri).await?;
        let rel = Self::uri_to_rel(&analysis, uri)?;
        let text = analysis.snapshots.get(&rel)?;
        let offset = crate::position::position_to_offset(text, position)?;
        Some((analysis, rel, offset))
    }

    /// Locate the AST node at the given cursor position by re-parsing the
    /// document. Returns the textual identifier (if any) and its span.
    /// Used by hover and definition handlers.
    async fn identifier_at(
        &self,
        uri: &Url,
        position: Position,
    ) -> Option<(String, bynk_syntax::span::Span, String)> {
        let text = {
            let state = self.state.read().await;
            state.docs.get(uri)?.text.clone()
        };
        let offset = crate::position::position_to_offset(&text, position)?;
        // Hole-aware (issue #473): interpolation holes are expanded so a cursor
        // inside `"… \(name) …"` lands on the hole's identifier token, not the
        // opaque `InterpStr` token.
        let tokens = bynk_syntax::lexer::tokenize_expanding_holes(&text).ok()?;
        // Find the token whose span covers `offset`.
        for t in &tokens {
            if t.span.start <= offset
                && offset < t.span.end
                && matches!(
                    t.kind,
                    bynk_syntax::lexer::TokenKind::Ident
                        | bynk_syntax::lexer::TokenKind::Int
                        | bynk_syntax::lexer::TokenKind::String
                        | bynk_syntax::lexer::TokenKind::Bool
                        | bynk_syntax::lexer::TokenKind::Float
                        | bynk_syntax::lexer::TokenKind::Result
                        | bynk_syntax::lexer::TokenKind::Option
                        | bynk_syntax::lexer::TokenKind::Effect
                )
            {
                let name = text[t.span.start..t.span.end].to_string();
                return Some((name, t.span, text));
            }
        }
        None
    }

    /// #846: `bynk/sequenceModel` — the sequence-diagram query for the
    /// handler under the cursor. This server's first custom (non-standard)
    /// request, registered via `custom_method` in [`run`] rather than a
    /// `LanguageServer` trait slot. Served from the committed round (#733),
    /// like `code_lens`; no refresh nudge (see the `sequence_request` module
    /// doc for why one isn't needed).
    async fn sequence_model(
        &self,
        params: sequence_request::SequenceModelParams,
    ) -> JsonRpcResult<Option<sequence_request::WireSequenceModel>> {
        let uri = params.text_document.uri;
        let Some(analysis) = self.committed_analysis(&uri).await else {
            return Ok(None);
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(None);
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(None);
        };
        let Some(offset) = crate::position::position_to_offset(text, params.position) else {
            return Ok(None);
        };
        let info = bynk_ide::symbols::own_declaration_name(text)
            .and_then(|(name, _)| analysis.sequence_info.get(&name));
        let model = sequence_request::sequence_model_at(text, offset, info);
        Ok(model.map(|m| sequence_request::to_wire(&m, text)))
    }

    /// #847: `bynk/documentationModel` — the documentation-view query for the
    /// whole file under the request. This server's second custom request,
    /// registered via `custom_method` in [`run`] (like `sequence_model`).
    /// Served from the committed round (#733), on-demand: no cursor position
    /// (the page is the whole file, Decision A) and no refresh nudge (Decision
    /// D — see the `documentation_request` module doc, and #846's for why a
    /// custom method needs none). A non-project file / no committed round →
    /// `None` (empty page).
    async fn documentation_model(
        &self,
        params: documentation_request::DocumentationModelParams,
    ) -> JsonRpcResult<Option<documentation_request::WireDocModel>> {
        let uri = params.text_document.uri;
        let Some(analysis) = self.committed_analysis(&uri).await else {
            return Ok(None);
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(None);
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(None);
        };
        let model = documentation_request::documentation_model_at(text);
        Ok(model.map(|m| documentation_request::to_wire(&m, text)))
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, params: InitializeParams) -> JsonRpcResult<InitializeResult> {
        // Slice D (Q4): record **every** workspace folder as a discovery seed
        // (was `folders.first()` only). Folders do not own URIs — a request
        // routes by its nearest enclosing `bynk.toml` (`resolve_root`) — so this
        // seeds where `did_change_workspace_folders` prunes and where slice E's
        // startup scan looks. Slice E: also capture whether the client accepts a
        // server-side `didChangeWatchedFiles` registration, used in `initialized`.
        let dynamic_watchers = params
            .capabilities
            .workspace
            .as_ref()
            .and_then(|w| w.did_change_watched_files.as_ref())
            .and_then(|d| d.dynamic_registration)
            .unwrap_or(false);
        // #733: whether the client can be nudged to re-pull each pull-based
        // decoration after a round commits (the "revalidate" of stale-while-
        // revalidate). Absent → the flag stays false and no nudge is sent.
        let ws = params.capabilities.workspace.as_ref();
        let supports_refresh = RefreshSupport {
            semantic_tokens: ws
                .and_then(|w| w.semantic_tokens.as_ref())
                .and_then(|s| s.refresh_support)
                .unwrap_or(false),
            inlay_hints: ws
                .and_then(|w| w.inlay_hint.as_ref())
                .and_then(|i| i.refresh_support)
                .unwrap_or(false),
            code_lens: ws
                .and_then(|w| w.code_lens.as_ref())
                .and_then(|c| c.refresh_support)
                .unwrap_or(false),
        };
        {
            let mut state = self.state.write().await;
            state.supports_dynamic_watchers = dynamic_watchers;
            state.supports_refresh = supports_refresh;
            if let Some(folders) = &params.workspace_folders {
                state.folders = folders
                    .iter()
                    .filter_map(|f| f.uri.to_file_path().ok())
                    .map(|p| p.canonicalize().unwrap_or(p))
                    .collect();
            }
        }
        Ok(InitializeResult {
            capabilities: server_capabilities(),
            server_info: Some(ServerInfo {
                name: SERVER_NAME.into(),
                version: Some(SERVER_VERSION.into()),
            }),
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        let (folders, dynamic) = {
            let s = self.state.read().await;
            (s.folders.clone(), s.supports_dynamic_watchers)
        };
        // Slice E (Q4/ADR 0204 §D): register the file watchers server-side, once,
        // with folder-independent globs — so any client is notified, and the VS
        // Code extension no longer supplies them (avoiding a double
        // notification). Only when the client accepts dynamic registration;
        // otherwise it is expected to watch files itself.
        if dynamic {
            self.register_file_watchers().await;
        }
        // Slice E: warm every project under the workspace folders, so diagnostics
        // appear at activation without a file being opened (spec §2.3).
        self.warm_projects(&folders).await;
        let msg = if folders.is_empty() {
            "bynkc-lsp: no workspace folders; single-file mode".to_string()
        } else {
            format!(
                "bynkc-lsp: {} workspace folder(s); projects resolved per file",
                folders.len()
            )
        };
        self.client.log_message(MessageType::INFO, msg).await;
    }

    async fn shutdown(&self) -> JsonRpcResult<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri.clone();
        {
            let mut state = self.state.write().await;
            state.docs.insert(
                uri.clone(),
                DocumentState {
                    text: params.text_document.text,
                    version: params.text_document.version,
                },
            );
        }
        // Slice D/F: `schedule_diagnostics` routes the URI to its project and
        // creates the entry on first touch — no separate root-setting step.
        self.schedule_diagnostics(&uri).await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri.clone();
        {
            let mut state = self.state.write().await;
            if let Some(doc) = state.docs.get_mut(&uri)
                && let Some(change) = params.content_changes.into_iter().next_back()
            {
                doc.text = change.text;
                doc.version = params.text_document.version;
            }
        }
        // `[lsp] diagnostics_mode = "on_save"`: no per-keystroke rounds — the
        // buffer state is updated above and diagnosis waits for `didSave`.
        // Slice D: the mode is the *owning project's* (config differs per
        // project); a single-file buffer uses the defaults.
        if self.config_for(&uri).await.diagnostics_mode == crate::project::DiagnosticsMode::OnSave {
            return;
        }
        // Slice F: hand off to the one scheduler — it debounces once, at the
        // configured delay (no manual pre-sleep stacked on the round's own
        // debounce), and coalesces a burst to a single analysis.
        self.schedule_diagnostics(&uri).await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        // The live path already diagnosed on change; this matters for
        // `diagnostics_mode = "on_save"`, where saves are the only trigger.
        self.schedule_diagnostics(&params.text_document.uri).await;
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri;
        {
            let mut state = self.state.write().await;
            state.docs.remove(&uri);
            // Slice F: drop the buffer's single-file debounce generation (a no-op
            // for a project file, which never had one).
            state.single_file_generations.remove(&uri);
        }
        // Slice D (Q4 §C): closing the last buffer can orphan a project whose
        // folder was already removed — it was retained *because* a buffer held
        // it. Prune it now and clear its diagnostics, the mirror of the folder
        // path, so a fully-orphaned project never lingers with stale squiggles.
        for cleared in self.prune_orphaned_projects().await {
            self.client
                .publish_diagnostics(cleared, Vec::new(), None)
                .await;
        }
    }

    /// Transport only: resolve the position, gather the round's tables and the
    /// live buffer, and package the result. The resolution *order* — which is the
    /// behaviour — lives in [`crate::hover::hover_content`], so it has one
    /// definition a test can pin (ADR 0190; #611's gap B was a fall-through bug).
    async fn hover(&self, params: HoverParams) -> JsonRpcResult<Option<Hover>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        // The analysed round, positioned — absent for a file outside it.
        let positioned = self.index_position(&uri, pos).await;
        // The live buffer — absent when the document is not open. Distinct from
        // the snapshot above, which lags while the user types.
        let doc_text = {
            let state = self.state.read().await;
            state.docs.get(&uri).map(|d| d.text.clone())
        };
        let doc = doc_text
            .as_deref()
            .and_then(|t| Some((t, crate::position::position_to_offset(t, pos)?)));
        let files = self.project_files(&uri).await;
        let analysis = positioned
            .as_ref()
            .map(|(a, rel, offset)| crate::hover::HoverAnalysis {
                index: &a.index,
                snapshots: &a.snapshots,
                locals: &a.locals,
                expr_types: &a.expr_types,
                rel,
                offset: *offset,
                project_root: &a.project_root,
                doc_scope: &a.doc_scope,
            });
        let content = crate::hover::hover_content(&crate::hover::HoverInput {
            analysis,
            doc,
            uri: &uri,
            files: files.as_deref(),
        });
        Ok(content.map(|value| Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value,
            }),
            range: None,
        }))
    }

    /// v0.32 (ADR 0065): signature help for the call under the cursor.
    async fn signature_help(
        &self,
        params: SignatureHelpParams,
    ) -> JsonRpcResult<Option<SignatureHelp>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        let offset = cursor_offset(&text, pos);
        let Some(ctx) = crate::signature_help::call_context(&text, offset) else {
            return Ok(None);
        };
        let files = self.project_files(&uri).await;
        // Name callees (free fns, statics, capability ops, of/unsafe) — lexical.
        // #733: `resolve_label` enumerates the project's units (file stats +
        // recovery parse of the cache-missed ones), so run it on the blocking
        // pool — signature help fires on every `(`/`,` while typing a call.
        let resolved_label = {
            let callee = ctx.callee.clone();
            let text = text.clone();
            let files = files.clone();
            match tokio::task::spawn_blocking(move || {
                crate::signature_help::resolve_label(&callee, &text, files.as_deref())
            })
            .await
            {
                Ok(l) => l,
                Err(e) => {
                    tracing::error!("signature-help label task failed: {e}");
                    None
                }
            }
        };
        let label = match resolved_label {
            Some(l) => Some(l),
            // v0.32 slice 2: a value-receiver method (`xs.fold(`) — type the
            // receiver via the rewrite + re-analyse, then the kernel signature.
            None => match crate::signature_help::value_receiver_method(&ctx.callee) {
                Some((_, method)) => {
                    if let Some((rewritten, recv_offset)) =
                        crate::signature_help::value_receiver_rewrite(
                            &text,
                            &ctx.callee,
                            ctx.open_paren,
                            offset,
                        )
                        && let Some(ty) = self.type_receiver(&uri, rewritten, recv_offset).await
                    {
                        crate::signature_help::kernel_method_signature(&ty, method)
                    } else {
                        None
                    }
                }
                None => None,
            },
        };
        let Some(label) = label else { return Ok(None) };
        let active = ctx.active_param as u32;
        let parameters: Vec<ParameterInformation> = crate::signature_help::param_ranges(&label)
            .into_iter()
            .map(|(s, e)| ParameterInformation {
                label: ParameterLabel::LabelOffsets([s as u32, e as u32]),
                documentation: None,
            })
            .collect();
        Ok(Some(SignatureHelp {
            signatures: vec![SignatureInformation {
                label,
                documentation: None,
                parameters: Some(parameters),
                active_parameter: Some(active),
            }],
            active_signature: Some(0),
            active_parameter: Some(active),
        }))
    }

    /// v0.33 (ADR 0066): a reference-count lens above each top-level definition,
    /// clickable to peek the references. Served from the cached round.
    async fn code_lens(&self, params: CodeLensParams) -> JsonRpcResult<Option<Vec<CodeLens>>> {
        let uri = params.text_document.uri;
        // #733: committed round, no forced re-analysis (see `committed_analysis`).
        let analysis = self.committed_analysis(&uri).await;
        let Some(analysis) = analysis else {
            return Ok(Some(Vec::new()));
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(Some(Vec::new()));
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(Some(Vec::new()));
        };
        // Peek the references/providers on click — a standard client command,
        // so no extension support is required (the client middleware hydrates the
        // three-argument shape). Shared by both the reference and provider lenses.
        let show_references = |range: Range, locations: Vec<Location>, title: String| CodeLens {
            range,
            command: Some(Command {
                title,
                command: "editor.action.showReferences".to_string(),
                arguments: Some(vec![
                    serde_json::to_value(&uri).unwrap_or_default(),
                    serde_json::to_value(range.start).unwrap_or_default(),
                    serde_json::to_value(&locations).unwrap_or_default(),
                ]),
            }),
            data: None,
        };
        let mut lenses: Vec<CodeLens> = crate::index_queries::code_lenses(&analysis.index, &rel)
            .into_iter()
            .map(|(def, refs)| {
                let range = crate::position::span_to_range(text, def.span);
                let locations: Vec<Location> = refs
                    .iter()
                    .filter_map(|r| Self::site_to_location(&analysis, r))
                    .collect();
                let n = refs.len();
                show_references(
                    range,
                    locations,
                    format!("{n} reference{}", if n == 1 { "" } else { "s" }),
                )
            })
            .collect();
        // v0.127 (editor-currency slice 6): a `N provider(s)` lens on each
        // capability, listing the services that `provides` it. Stacks below the
        // reference lens, as a referenced test stacks a reference + test lens.
        lenses.extend(
            crate::index_queries::capability_provider_lenses(&analysis.index, &rel)
                .into_iter()
                .map(|(def, providers)| {
                    let range = crate::position::span_to_range(text, def.span);
                    let locations: Vec<Location> = providers
                        .iter()
                        .filter_map(|r| Self::site_to_location(&analysis, r))
                        .collect();
                    let n = providers.len();
                    show_references(
                        range,
                        locations,
                        format!("{n} provider{}", if n == 1 { "" } else { "s" }),
                    )
                }),
        );
        // v0.129 (#259): a `N refinements of <Base>` lens on each refined/opaque
        // type, listing its family — every type over the same builtin base. Stacks
        // below the reference lens, like the provider lens on a capability.
        lenses.extend(
            crate::index_queries::refinement_family_lenses(&analysis.index, &rel)
                .into_iter()
                .map(|(def, base, family)| {
                    let range = crate::position::span_to_range(text, def.span);
                    let locations: Vec<Location> = family
                        .iter()
                        .filter_map(|r| Self::site_to_location(&analysis, r))
                        .collect();
                    let n = family.len();
                    show_references(
                        range,
                        locations,
                        format!("{n} refinements of {}", base.name()),
                    )
                }),
        );
        // #846: a "Show Sequence" lens above every handler declaration —
        // `bynk.showSequenceDiagram` is a plain extension command (not a
        // built-in VS Code command), so its arguments travel as plain JSON
        // with no `codelens.ts` hydration needed, unlike `show_references`
        // above. A direct AST walk (`handler_lens_sites`), not
        // `index_queries::code_lenses` — that only indexes agent handlers
        // (`SymbolKind::Handler`; service handlers have no per-handler name)
        // and would silently drop the lens for every service handler.
        lenses.extend(
            crate::sequence_request::handler_lens_sites(text)
                .into_iter()
                .map(|span| {
                    let range = crate::position::span_to_range(text, span);
                    CodeLens {
                        range,
                        command: Some(Command {
                            title: "Show Sequence".to_string(),
                            command: "bynk.showSequenceDiagram".to_string(),
                            arguments: Some(vec![
                                serde_json::to_value(&uri).unwrap_or_default(),
                                serde_json::to_value(range.start).unwrap_or_default(),
                            ]),
                        }),
                        data: None,
                    }
                }),
        );
        Ok(Some(lenses))
    }

    async fn prepare_call_hierarchy(
        &self,
        params: CallHierarchyPrepareParams,
    ) -> JsonRpcResult<Option<Vec<CallHierarchyItem>>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let Some((key, def)) =
            crate::index_queries::prepare_call_hierarchy(&analysis.index, &rel, offset)
        else {
            return Ok(None);
        };
        Ok(Self::call_hierarchy_item(&analysis, key, def).map(|item| vec![item]))
    }

    async fn incoming_calls(
        &self,
        params: CallHierarchyIncomingCallsParams,
    ) -> JsonRpcResult<Option<Vec<CallHierarchyIncomingCall>>> {
        let analysis = self.analysis_for(&params.item.uri).await;
        let Some(analysis) = analysis else {
            return Ok(Some(Vec::new()));
        };
        let Some(key) = SerKey::read(&params.item.data) else {
            return Ok(Some(Vec::new()));
        };
        let calls = crate::index_queries::incoming_calls(&analysis.index, &key)
            .into_iter()
            .filter_map(|rel| {
                let from = Self::call_hierarchy_item(&analysis, rel.key, rel.def)?;
                let from_ranges = Self::call_ranges(&analysis, &rel.sites);
                Some(CallHierarchyIncomingCall { from, from_ranges })
            })
            .collect();
        Ok(Some(calls))
    }

    async fn outgoing_calls(
        &self,
        params: CallHierarchyOutgoingCallsParams,
    ) -> JsonRpcResult<Option<Vec<CallHierarchyOutgoingCall>>> {
        let analysis = self.analysis_for(&params.item.uri).await;
        let Some(analysis) = analysis else {
            return Ok(Some(Vec::new()));
        };
        let Some(key) = SerKey::read(&params.item.data) else {
            return Ok(Some(Vec::new()));
        };
        let calls = crate::index_queries::outgoing_calls(&analysis.index, &key)
            .into_iter()
            .filter_map(|rel| {
                let to = Self::call_hierarchy_item(&analysis, rel.key, rel.def)?;
                let from_ranges = Self::call_ranges(&analysis, &rel.sites);
                Some(CallHierarchyOutgoingCall { to, from_ranges })
            })
            .collect();
        Ok(Some(calls))
    }

    /// v0.35 (ADR 0068): `textDocument/implementation` — on a capability
    /// symbol (its declaration, a `given Cap` use, or a `provides Cap` use),
    /// the providers that implement it. `None` for any other symbol (the
    /// reverse, provider → capability, is served by goto-definition).
    async fn goto_implementation(
        &self,
        params: GotoImplementationParams,
    ) -> JsonRpcResult<Option<GotoImplementationResponse>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let Some((key, _)) = analysis.index.symbol_at(&rel, offset) else {
            return Ok(None);
        };
        if key.kind != bynk_check::index::SymbolKind::Capability {
            return Ok(None);
        }
        let locations: Vec<Location> = crate::index_queries::implementations(&analysis.index, key)
            .into_iter()
            .filter_map(|d| Self::site_to_location(&analysis, d))
            .collect();
        if locations.is_empty() {
            return Ok(None);
        }
        Ok(Some(GotoDefinitionResponse::Array(locations)))
    }

    /// Slice 6: `textDocument/typeDefinition` — from a value at the cursor to the
    /// definition of its (user-declared) type. Reads the value's type from the
    /// round's `expr_types`, unwraps it to a `Named` target, and returns that
    /// type's definition site(s). `None` for a built-in/function/actor type, or
    /// a cursor not on a typed expression in a clean round.
    async fn goto_type_definition(
        &self,
        params: GotoTypeDefinitionParams,
    ) -> JsonRpcResult<Option<GotoTypeDefinitionResponse>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let Some(entries) = analysis.expr_types.get(&rel) else {
            return Ok(None);
        };
        let Some(ty) = bynk_check::expr_types::type_at_offset(entries, offset) else {
            return Ok(None);
        };
        let Some(name) = crate::index_queries::named_type_target(ty) else {
            return Ok(None);
        };
        let locations: Vec<Location> =
            crate::index_queries::type_definitions_named(&analysis.index, name)
                .into_iter()
                .filter_map(|d| Self::site_to_location(&analysis, d))
                .collect();
        if locations.is_empty() {
            return Ok(None);
        }
        Ok(Some(GotoDefinitionResponse::Array(locations)))
    }

    /// Slice 6b (ADR 0095): `textDocument/documentLink` — `uses`/`consumes` unit
    /// names are clickable to the unit's source. Spans come from parsing the live
    /// buffer; the target is the unit's first source file from the round's
    /// unit→source map. A first-party `uses` (embedded, no on-disk file) or an
    /// unresolved unit yields no link.
    ///
    /// #848: plus intra-doc links inside the file's own `--- … ---` doc
    /// comments — `[Name]`/`[Owner.member]` resolved against the declaring
    /// unit's `doc_scope`. Resolves against the full `analysis.index` under
    /// the same `committed_analysis` gate as the unit-reference links above;
    /// consistent with `code_lens`/`capability_provider_lenses`, which
    /// already resolve full-index cross-references under this gate.
    async fn document_link(
        &self,
        params: DocumentLinkParams,
    ) -> JsonRpcResult<Option<Vec<DocumentLink>>> {
        let uri = params.text_document.uri;
        // #733: committed round. Link ranges convert against live `text` here and
        // the round only supplies the project-level `unit_sources` map (it changes
        // only on a `uses`/`consumes` edit), so a committed round is safe.
        let analysis = self.committed_analysis(&uri).await;
        let text = self
            .state
            .read()
            .await
            .docs
            .get(&uri)
            .map(|d| d.text.clone());
        let (Some(text), Some(analysis)) = (text, analysis) else {
            return Ok(None);
        };
        let mut links: Vec<DocumentLink> = crate::symbols::unit_reference_spans(&text)
            .into_iter()
            .filter_map(|(unit, span)| {
                let rel = analysis.unit_sources.get(&unit)?.first()?;
                let target = Url::from_file_path(analysis.project_root.join(rel)).ok()?;
                Some(DocumentLink {
                    range: crate::position::span_to_range(&text, span),
                    target: Some(target),
                    tooltip: Some(format!("Open unit `{unit}`")),
                    data: None,
                })
            })
            .collect();
        // #848: a suite file's own doc comments are out of scope this
        // increment (own_declaration_name returns None for a suite; its
        // uses-clause links above are unaffected).
        if let Some((owner_unit, _)) = crate::symbols::own_declaration_name(&text) {
            for (name, span) in crate::symbols::doc_link_spans(&text) {
                let Some(def) = crate::index_queries::resolve_doc_link(
                    &analysis.index,
                    &analysis.doc_scope,
                    &owner_unit,
                    &name,
                ) else {
                    continue;
                };
                let Ok(target) = Url::from_file_path(analysis.project_root.join(&def.path)) else {
                    continue;
                };
                links.push(DocumentLink {
                    range: crate::position::span_to_range(&text, span),
                    target: Some(target),
                    tooltip: Some(format!("Go to `{name}`")),
                    data: None,
                });
            }
        }
        Ok((!links.is_empty()).then_some(links))
    }

    async fn completion(
        &self,
        params: CompletionParams,
    ) -> JsonRpcResult<Option<CompletionResponse>> {
        let uri = params.text_document_position.text_document.uri;
        let pos = params.text_document_position.position;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        let offset = cursor_offset(&text, pos);
        // The line up to the cursor — the context the completion keys off.
        // Derived from the converted offset (always a char boundary), not by
        // slicing the line at `pos.character` bytes.
        let line_prefix = text[..offset].rsplit('\n').next().unwrap_or("").to_string();
        let files = self.project_files(&uri).await;
        // `complete()` enumerates the project's units — file stats and CPU-bound
        // recovery parsing (of the buffer, and any project file whose parse cache
        // missed). Run it on the blocking pool so a keystroke on a large project
        // never stalls the async runtime (#733).
        let candidates = {
            let line_prefix = line_prefix.clone();
            let text = text.clone();
            match tokio::task::spawn_blocking(move || {
                completion::complete(&line_prefix, &text, files.as_deref())
            })
            .await
            {
                Ok(c) => c,
                // A panic (or cancellation) inside `complete()` degrades to empty
                // completions rather than a failed request — but log the
                // `JoinError` so the underlying bug is not silently swallowed
                // (#776 review).
                Err(e) => {
                    tracing::error!("completion enumeration task failed: {e}");
                    Vec::new()
                }
            }
        };
        let mut items: Vec<CompletionItem> =
            candidates.into_iter().map(to_completion_item).collect();
        // ADR 0064/0093 D3: offer in-scope locals/params at keyword position
        // (alongside keywords) and at expression position (alongside the
        // constructors + type names `complete()` now yields there). Both are
        // places a value or name can begin; the two positions are disjoint.
        if completion::is_keyword_position(&line_prefix)
            || completion::is_expression_position(&line_prefix)
        {
            items.extend(self.locals_completions(&uri, pos).await);
        }
        // v0.124 (slice 3): inside a `requires`/`ensures` predicate, offer the
        // enclosing function's parameters (and `result` in an `ensures`),
        // merged with whatever the lexical cell yields there — the same
        // append-in-scope-names posture as locals above.
        items.extend(contract_param_completions(&text, offset, &line_prefix));
        // v0.131: inside a `cors { }` block, offer the policy field names; at a
        // service-body item start, offer the `cors` section keyword alongside the
        // handler-kind keywords the keyword-position cell already yields.
        items.extend(cors_completions(&text, offset, &line_prefix));
        // v0.141 (ADR 0164): inside a `security { }` block, offer the policy field
        // names; at a service-body item start, offer the `security` section keyword.
        items.extend(security_completions(&text, offset, &line_prefix));
        // v0.140 (ADR 0163): inside `@cache( … )`, offer the annotation argument
        // names; at a service-body item start, offer the `@cache` snippet alongside
        // the `cors` keyword and handler kinds.
        items.extend(cache_completions(&text, offset, &line_prefix));
        // v0.142 (ADR 0165): inside a `limits { }` block, offer the policy field
        // names; at a service-body item start, offer the `limits` section keyword.
        items.extend(limits_completions(&text, offset, &line_prefix));
        // v0.142 (ADR 0165): inside `@limit( … )`, offer the annotation argument
        // names; at a service-body item start, offer the `@limit` snippet.
        items.extend(limit_completions(&text, offset, &line_prefix));
        // v0.128: at a `match` arm-pattern-start, prepend the scrutinee's
        // variants — the most relevant candidate there. Unlike an `is` position, a
        // fresh-line or after-comma arm already looks like a keyword/expression
        // position (so `items` is non-empty and the `is_empty` path below never
        // fires), hence the merge. The expensive scrutinee typing is gated behind
        // the cheap lexical `match_scrutinee_offset` check inside, so ordinary
        // keyword-position completion pays only a string scan.
        // v0.145 (ADR 0169): a nested constructor position (`Some(‸`) offers the
        // payload type's variants; it and the arm-start position are mutually
        // exclusive (one is inside a `(`, the other before any), so the two lists
        // never overlap. Nested is the more specific position, so it leads.
        let mut pattern_items = self.nested_pattern_completions(&uri, &text, offset).await;
        pattern_items.extend(self.match_arm_completions(&uri, &text, offset).await);
        if !pattern_items.is_empty() {
            let mut merged = pattern_items;
            merged.extend(items);
            stamp_resolve_data(&mut merged, &uri);
            return Ok(Some(CompletionResponse::Array(merged)));
        }
        if items.is_empty() {
            // Slice 3: `<expr> is <cursor>` — offer the scrutinee sum type's
            // variants, resolved from `expr_types` (the ADR 0063 ceiling).
            let is_items = self.is_pattern_completions(&uri, &text, offset).await;
            if !is_items.is_empty() {
                return Ok(Some(CompletionResponse::Array(is_items)));
            }
            // A lowercase `receiver.` is a value receiver — type it by
            // re-analysing the rewritten buffer and offer its members. (Value
            // members name no declared symbol, so they carry no resolve data.)
            let value_items = self.value_member_completions(&uri, &text, offset).await;
            return Ok((!value_items.is_empty()).then_some(CompletionResponse::Array(value_items)));
        }
        // Slice 5: stash the doc URI so `completion_resolve` can attach lazy docs.
        stamp_resolve_data(&mut items, &uri);
        Ok(Some(CompletionResponse::Array(items)))
    }

    /// Slice 5: fill in hover-quality `documentation` for the focused completion
    /// item, reusing the hover renderer (`symbols::describe_symbol`, local then
    /// cross-file — §3.4). The originating doc URI is read from the item's
    /// `data` (a resolve request carries only the item, not a position). A no-op
    /// for an item that names no declared symbol (a keyword, kernel method, or
    /// local) — its one-line `detail` already suffices.
    async fn completion_resolve(&self, mut item: CompletionItem) -> JsonRpcResult<CompletionItem> {
        if item.documentation.is_some() {
            return Ok(item);
        }
        let Some(uri) = item
            .data
            .as_ref()
            .and_then(|d| d.get("uri"))
            .and_then(serde_json::Value::as_str)
            .and_then(|s| Url::parse(s).ok())
        else {
            return Ok(item);
        };
        let local = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let doc = match local
            .as_deref()
            .and_then(|t| crate::symbols::describe_symbol(t, &item.label))
        {
            Some(md) => Some(md),
            // #733: the cross-file fallback enumerates the project's units (file
            // stats + recovery parse of the cache-missed ones); the firstparty
            // fallback parses the embedded surface. Both read/parse off the
            // blocking pool — completion-item resolve fires as the user arrows
            // through the completion list.
            None => {
                let files = self.project_files(&uri).await;
                let uri = uri.clone();
                let label = item.label.clone();
                match tokio::task::spawn_blocking(move || {
                    files
                        .and_then(|files| {
                            crate::symbols::describe_symbol_cross_file(&files, &uri, &label)
                        })
                        .map(|(_uri, md)| md)
                        // Slice 9: stdlib/surface symbols (e.g. a `uses bynk.list`
                        // combinator) live in the embedded first-party sources,
                        // not the project's files.
                        .or_else(|| crate::symbols::describe_firstparty_symbol(&label))
                })
                .await
                {
                    Ok(md) => md,
                    Err(e) => {
                        tracing::error!("completion-resolve describe task failed: {e}");
                        None
                    }
                }
            }
        };
        if let Some(md) = doc {
            item.documentation = Some(Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: md,
            }));
        }
        Ok(item)
    }

    async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> JsonRpcResult<Option<GotoDefinitionResponse>> {
        let uri = params
            .text_document_position_params
            .text_document
            .uri
            .clone();
        let pos = params.text_document_position_params.position;
        // v0.25 rider: binding-correct definition via the index (fixes the
        // name-collision mis-navigation of the string-matching path). The
        // legacy path remains as fallback for not-yet-indexed symbol kinds
        // (locals, methods, fields, ops).
        if let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await {
            if let Some((_, def)) =
                crate::index_queries::definition_at(&analysis.index, &rel, offset)
                && let Some(location) = Self::site_to_location(&analysis, def)
            {
                return Ok(Some(GotoDefinitionResponse::Scalar(location)));
            }
            // v0.31: a local binding — scope-correct definition (before the
            // string-matching fallback, which can't tell scopes apart).
            if let Some(text) = analysis.snapshots.get(&rel)
                && let Some(locals) = analysis.locals.get(&rel)
                && let Some(def) = crate::locals_nav::local_definition_at(locals, text, offset)
                && let Some(location) = self
                    .local_locations(&analysis, &rel, &[def])
                    .into_iter()
                    .next()
            {
                return Ok(Some(GotoDefinitionResponse::Scalar(location)));
            }
        }
        // Slice 6a follow-up (ADR 0095): the cursor on a `uses`/`consumes` unit
        // name jumps to that unit's source. Units aren't index symbols, so the
        // unit→source map resolves them; runs before the name-matching path so a
        // unit segment can't be mistaken for a like-named type.
        if let Some(location) = self.unit_reference_definition(&uri, pos).await {
            return Ok(Some(GotoDefinitionResponse::Scalar(location)));
        }
        let Some((name, _span, text)) = self.identifier_at(&uri, pos).await else {
            return Ok(None);
        };
        if let Some(decl_span) = crate::symbols::find_declaration_span(&text, &name) {
            let range = crate::position::span_to_range(&text, decl_span);
            return Ok(Some(GotoDefinitionResponse::Scalar(Location {
                uri,
                range,
            })));
        }
        // Cross-file fallback (v1.1; LSP spec §3.4).
        if let Some(files) = self.project_files(&uri).await
            && let Some(found) = crate::symbols::find_declaration_cross_file(&files, &uri, &name)
        {
            let range = crate::position::span_to_range(&found.source, found.span);
            return Ok(Some(GotoDefinitionResponse::Scalar(Location {
                uri: found.uri,
                range,
            })));
        }
        Ok(None)
    }

    async fn formatting(
        &self,
        params: DocumentFormattingParams,
    ) -> JsonRpcResult<Option<Vec<TextEdit>>> {
        let uri = params.text_document.uri;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        // Slice D: the format options are the owning project's (or the defaults
        // in single-file mode).
        let opts = self.config_for(&uri).await.format_options();
        match bynk_fmt::format_source(&text, &opts) {
            Ok(formatted) => {
                if formatted == text {
                    Ok(Some(Vec::new()))
                } else {
                    // Replace the entire document.
                    let end_pos = crate::position::end_position(&text);
                    Ok(Some(vec![TextEdit {
                        range: Range {
                            start: Position::new(0, 0),
                            end: end_pos,
                        },
                        new_text: formatted,
                    }]))
                }
            }
            Err(_) => {
                // Formatting failed (parse error). Return no edits; the
                // diagnostics flow will surface the parse error.
                Ok(Some(Vec::new()))
            }
        }
    }

    async fn range_formatting(
        &self,
        params: DocumentRangeFormattingParams,
    ) -> JsonRpcResult<Option<Vec<TextEdit>>> {
        // Best-effort: format the whole document. Per spec, range
        // formatting may return edits wider than the requested range.
        self.formatting(DocumentFormattingParams {
            text_document: params.text_document,
            options: params.options,
            work_done_progress_params: params.work_done_progress_params,
        })
        .await
    }

    async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> JsonRpcResult<Option<DocumentSymbolResponse>> {
        // v1.1 — outline view + Cmd-Shift-O. See `design/bynk-lsp-spec.md` §3.7.
        let uri = params.text_document.uri;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        let syms = crate::document_symbols::outline(&text);
        if syms.is_empty() {
            return Ok(None);
        }
        Ok(Some(DocumentSymbolResponse::Nested(syms)))
    }

    /// v0.37 (ADR 0070): `textDocument/foldingRange` — structural folds + comment
    /// runs from the recovered AST (no analysis round).
    async fn folding_range(
        &self,
        params: FoldingRangeParams,
    ) -> JsonRpcResult<Option<Vec<FoldingRange>>> {
        let uri = params.text_document.uri;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        Ok(Some(crate::structure::folding_ranges(&text)))
    }

    /// v0.37 (ADR 0070): `textDocument/selectionRange` — the enclosing-node
    /// chain (innermost first) for each requested position.
    async fn selection_range(
        &self,
        params: SelectionRangeParams,
    ) -> JsonRpcResult<Option<Vec<SelectionRange>>> {
        let uri = params.text_document.uri;
        let text = {
            let s = self.state.read().await;
            s.docs.get(&uri).map(|d| d.text.clone())
        };
        let Some(text) = text else { return Ok(None) };
        Ok(Some(crate::structure::selection_ranges(
            &text,
            &params.positions,
        )))
    }

    async fn references(&self, params: ReferenceParams) -> JsonRpcResult<Option<Vec<Location>>> {
        let uri = params.text_document_position.text_document.uri;
        let pos = params.text_document_position.position;
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let include_decl = params.context.include_declaration;
        if let Some(sites) =
            crate::index_queries::sites_for(&analysis.index, &rel, offset, include_decl)
        {
            let locations: Vec<Location> = sites
                .into_iter()
                .filter_map(|site| Self::site_to_location(&analysis, site))
                .collect();
            return Ok(Some(locations));
        }
        // v0.31: a local binding — its def + uses, resolved from the snapshot.
        if let Some(spans) = self.local_sites(&analysis, &rel, offset) {
            let spans = if include_decl {
                &spans[..]
            } else {
                &spans[1..]
            }; // def first
            let locations = self.local_locations(&analysis, &rel, spans);
            return Ok(Some(locations));
        }
        Ok(None)
    }

    /// v0.26 (ADR 0054): quick-fixes from structured suggestions. v0.213
    /// (ADR 0239) adds the extract-variable refactor
    /// (`CodeActionKind::REFACTOR_EXTRACT`), computed from the same snapshot.
    /// Track #800 adds the sibling extract-function refactor, additionally
    /// fed the round's `requirements`/`locals`/`expr_types` (the
    /// capability-free-only gate and the parameter/return type synthesis).
    /// Served from the **cached** analysis round only (never a fresh run —
    /// slow, and it could disagree with the squiggles the client is
    /// showing): a request before the first round, or for a file outside
    /// the project, returns the empty list. #804: the combined list is then
    /// filtered against `params.context.only`, if the client set it.
    async fn code_action(
        &self,
        params: CodeActionParams,
    ) -> JsonRpcResult<Option<CodeActionResponse>> {
        let uri = params.text_document.uri;
        // #733: committed round. The request range and the diagnostics the fixes
        // ride on both convert against the round's snapshot, and the emitted edits
        // carry the round's version, so a committed round is self-consistent.
        let analysis = self.committed_analysis(&uri).await;
        let Some(analysis) = analysis else {
            return Ok(Some(Vec::new()));
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(Some(Vec::new()));
        };
        let (Some(text), Some(diags)) =
            (analysis.snapshots.get(&rel), analysis.diagnostics.get(&rel))
        else {
            return Ok(Some(Vec::new()));
        };
        // The request range converts against the analysed snapshot (the
        // v0.24 rule), like the spans it is intersected with.
        let (Some(start), Some(end)) = (
            crate::position::position_to_offset(text, params.range.start),
            crate::position::position_to_offset(text, params.range.end),
        ) else {
            return Ok(Some(Vec::new()));
        };
        let version = analysis.versions.get(&rel).copied();
        let span = bynk_syntax::span::Span::new(start, end);
        let mut actions = crate::code_actions::quick_fixes(text, diags, span, &uri, version);
        // #852: capability-aware header fixes (`add consumes`, auto-`uses`/
        // `consumes`), computed from the committed index + a fresh reparse.
        actions.extend(crate::capability_fixes::header_quick_fixes(
            text,
            diags,
            span,
            &uri,
            version,
            &analysis.index,
        ));
        actions.extend(crate::extract::extract_variable(text, span, &uri, version));
        let empty_reqs = Vec::new();
        let empty_locals = Vec::new();
        let empty_types = Vec::new();
        actions.extend(crate::extract::extract_function(
            text,
            span,
            &uri,
            version,
            analysis.requirements.get(&rel).unwrap_or(&empty_reqs),
            analysis.locals.get(&rel).unwrap_or(&empty_locals),
            analysis.expr_types.get(&rel).unwrap_or(&empty_types),
        ));
        // #804: honour the client's requested action kinds, if any.
        let actions = crate::code_actions::filter_by_only(actions, params.context.only.as_deref());
        Ok(Some(actions))
    }

    /// v0.27 (ADR 0056): inferred-type inlay hints for the visible range,
    /// served from the cached round only — no cached round (pre-first-
    /// analysis, non-project file) returns the empty list. Positions
    /// convert against the analysed snapshot (the v0.24 rule).
    async fn inlay_hint(&self, params: InlayHintParams) -> JsonRpcResult<Option<Vec<InlayHint>>> {
        let uri = params.text_document.uri;
        // #733: committed round, no forced re-analysis (see `committed_analysis`).
        let analysis = self.committed_analysis(&uri).await;
        let Some(analysis) = analysis else {
            return Ok(Some(Vec::new()));
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(Some(Vec::new()));
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(Some(Vec::new()));
        };
        // The visible range converts against the analysed snapshot, like
        // the hint spans it is intersected with.
        let (Some(start), Some(end)) = (
            crate::position::position_to_offset(text, params.range.start),
            crate::position::position_to_offset(text, params.range.end),
        ) else {
            return Ok(Some(Vec::new()));
        };
        let visible = bynk_syntax::span::Span::new(start, end);
        // v0.27: inferred-type hints. v0.99: plus the materializable ghost
        // `given` hints for uncovered capability requirements. A file may carry
        // one set without the other, so each defaults to empty independently.
        let mut hints = analysis
            .hints
            .get(&rel)
            .map(|h| crate::inlay_hints::inlay_hints(text, h, visible))
            .unwrap_or_default();
        if let Some(reqs) = analysis.requirements.get(&rel) {
            hints.extend(crate::inlay_hints::given_hints(text, reqs, visible));
        }
        Ok(Some(hints))
    }

    /// v0.28 (ADR 0057): semantic tokens for the whole document, served
    /// from the cached round only (no cached round / non-project file →
    /// empty), positions against the analysed snapshot (the v0.24 rule).
    async fn semantic_tokens_full(
        &self,
        params: SemanticTokensParams,
    ) -> JsonRpcResult<Option<SemanticTokensResult>> {
        let data = self
            .semantic_tokens_for(&params.text_document.uri, None)
            .await;
        Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        })))
    }

    /// v0.28 (ADR 0057): the `…/range` variant — the same pure read,
    /// filtered to tokens overlapping the requested range.
    async fn semantic_tokens_range(
        &self,
        params: SemanticTokensRangeParams,
    ) -> JsonRpcResult<Option<SemanticTokensRangeResult>> {
        let data = self
            .semantic_tokens_for(&params.text_document.uri, Some(params.range))
            .await;
        Ok(Some(SemanticTokensRangeResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        })))
    }

    /// v0.26 rider (ADR 0055): workspace-wide symbol search — the index's
    /// definitions, filtered by the query. Slice D (Q4): one server, many
    /// projects — aggregate across **every** project. Candidates are the
    /// **already-warmed** projects (slice E warms every project under the folders
    /// at `initialized`, and the watcher warms one created later), plus each
    /// folder's own `resolve_root` — a cheap bounded walk-*up*, the pre-slice-E
    /// seeding. No full tree-walk on this request path: a `workspace/symbol`
    /// query can fire per keystroke, and the warmed set already holds the nested
    /// monorepo projects a walk would rediscover.
    async fn symbol(
        &self,
        params: WorkspaceSymbolParams,
    ) -> JsonRpcResult<Option<Vec<SymbolInformation>>> {
        let candidates: Vec<(PathBuf, ProjectConfig)> = {
            // Snapshot warmed projects + folders under the lock; resolve the
            // folders' own roots off it (a bounded walk-up, but still FS I/O).
            let (mut set, folders) = {
                let state = self.state.read().await;
                let known: std::collections::HashMap<PathBuf, ProjectConfig> = state
                    .projects
                    .iter()
                    .map(|(r, p)| (r.clone(), p.config.clone()))
                    .collect();
                (known, state.folders.clone())
            };
            for folder in &folders {
                if let Some((root, config)) = Self::resolve_root(folder) {
                    let root = root.canonicalize().unwrap_or(root);
                    set.entry(root).or_insert(config);
                }
            }
            set.into_iter().collect()
        };
        let mut symbols: Vec<SymbolInformation> = Vec::new();
        for (root, config) in candidates {
            let Some(analysis) = self.ensure_project_analysed(root, config).await else {
                continue;
            };
            for (key, def) in
                crate::index_queries::workspace_symbols(&analysis.index, &params.query)
            {
                let Some(location) = Self::site_to_location(&analysis, def) else {
                    continue;
                };
                #[allow(deprecated)]
                symbols.push(SymbolInformation {
                    name: key.name.clone(),
                    kind: lsp_symbol_kind(key.kind),
                    tags: None,
                    deprecated: None,
                    location,
                    container_name: Some(key.unit.clone()),
                });
            }
        }
        // Aggregating across projects (a `HashMap`-derived candidate list) groups
        // matches by project in arbitrary order; the spec (§3.11) promises a
        // stable `(name, unit)` ordering, so sort the merged result. `unit` is
        // the container name.
        symbols.sort_by(|a, b| {
            a.name
                .cmp(&b.name)
                .then_with(|| a.container_name.cmp(&b.container_name))
        });
        Ok(Some(symbols))
    }

    /// v0.26 rider (ADR 0055): the symbol-at-cursor's occurrences in the
    /// active file. `kind` is omitted — the index does not distinguish read
    /// from write references.
    async fn document_highlight(
        &self,
        params: DocumentHighlightParams,
    ) -> JsonRpcResult<Option<Vec<DocumentHighlight>>> {
        let uri = params.text_document_position_params.text_document.uri;
        let pos = params.text_document_position_params.position;
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(None);
        };
        if let Some(sites) =
            crate::index_queries::document_highlights(&analysis.index, &rel, offset)
        {
            let highlights: Vec<DocumentHighlight> = sites
                .into_iter()
                .map(|s| DocumentHighlight {
                    range: crate::position::span_to_range(text, s.span),
                    kind: None,
                })
                .collect();
            return Ok(Some(highlights));
        }
        // v0.31: a local binding's occurrences (def + uses) in the file.
        if let Some(spans) = self.local_sites(&analysis, &rel, offset) {
            let highlights = spans
                .iter()
                .map(|s| DocumentHighlight {
                    range: crate::position::span_to_range(text, *s),
                    kind: None,
                })
                .collect();
            return Ok(Some(highlights));
        }
        Ok(None)
    }

    async fn prepare_rename(
        &self,
        params: TextDocumentPositionParams,
    ) -> JsonRpcResult<Option<PrepareRenameResponse>> {
        let uri = params.text_document.uri;
        let pos = params.position;
        // Refuse (None) for anything the index does not cover — locals,
        // methods, record fields, capability ops, unit names — rather than
        // falling through to a partial or name-matched rename.
        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
            return Ok(None);
        };
        let Some((key, site)) = crate::index_queries::prepare_rename(&analysis.index, &rel, offset)
        else {
            return Ok(None);
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(None);
        };
        Ok(Some(PrepareRenameResponse::RangeWithPlaceholder {
            range: crate::position::span_to_range(text, site.span),
            placeholder: key.name.clone(),
        }))
    }

    async fn rename(&self, params: RenameParams) -> JsonRpcResult<Option<WorkspaceEdit>> {
        let uri = params.text_document_position.text_document.uri;
        let pos = params.text_document_position.position;
        let new_name = params.new_name;
        let refused = |msg: String| tower_lsp::jsonrpc::Error {
            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
            message: msg.into(),
            data: None,
        };
        // Slice B: rename emits versioned edits across *every* file that
        // references the symbol, so it needs the round current for **all** open
        // buffers, not just the cursor's (`analysis_for` would leave a dirty
        // non-cursor file stale and its edit would be stamped with an old
        // version, which the client rejects). `analysis_covering_open_buffers`
        // restores the whole-project freshness the pre-v0.179 `fresh_analysis`
        // gave. The cursor's file is one of those buffers, so it is current too;
        // resolve `rel`/`offset` against it here (what `index_position` did).
        // Slice D (Q4): route by the cursor's project — a rename spans one
        // project, so the round need only cover *that* project's buffers.
        let Some(root) = self.root_for_uri(&uri).await else {
            return Err(refused("rename requires a project (bynk.toml)".into()));
        };
        let Some(analysis) = self.analysis_covering_open_buffers(&root).await else {
            return Err(refused("rename requires a project (bynk.toml)".into()));
        };
        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
            return Ok(None);
        };
        let Some(text) = analysis.snapshots.get(&rel) else {
            return Ok(None);
        };
        let Some(offset) = crate::position::position_to_offset(text, pos) else {
            return Ok(None);
        };
        let plan = crate::index_queries::plan_rename(&analysis.index, &rel, offset, &new_name)
            .map_err(refused)?;

        // Validator 1 + 2 input: re-analyse with the edits applied. Every
        // snapshot is pinned via the overlay so the re-analysis differs from
        // the plan's baseline only by the edits themselves.
        //
        // Slice A: this must re-analyse over the **same roots** the baseline
        // round used (`AnalysisRoots::Project`, manifest-aware), not the
        // single-tree `diagnose_project`. `diagnose_project(project_root)`
        // resolves to `Roots::Single`, which walks the whole tree with **no
        // `exclude`** and no `out`/`node_modules` skip — so `post` would cover a
        // superset of the baseline's files, and validators 1 and 2 (which
        // compare `post` against baselines from the manifest-aware round) would
        // read a diagnostic or index site in an excluded tree as *new* and
        // refuse a valid rename.
        let mut overlay = std::collections::HashMap::new();
        for (rel_path, text) in &analysis.snapshots {
            let edited = match plan.edits.get(rel_path) {
                Some(spans) => crate::index_queries::apply_edits(text, spans, &plan.new_name),
                None => text.clone(),
            };
            let abs = analysis.project_root.join(rel_path);
            let abs = abs.canonicalize().unwrap_or(abs);
            overlay.insert(abs, edited);
        }
        let roots = bynk_ide::AnalysisRoots::Project(analysis.project_root.clone());
        let Ok(post) =
            tokio::task::spawn_blocking(move || bynk_ide::diagnose_project_with(&roots, &overlay))
                .await
        else {
            return Err(refused("rename validation failed to run".into()));
        };

        // Validator 1 — collisions: refuse on any new diagnostic.
        let post_diags: Vec<(PathBuf, String)> = post
            .files
            .iter()
            .flat_map(|f| {
                f.diagnostics
                    .iter()
                    .map(|d| (f.source_path.clone(), d.error.category.to_string()))
            })
            .collect();
        crate::index_queries::no_new_diagnostics(&analysis.diag_categories(), &post_diags)
            .map_err(refused)?;

        // Validator 2 — capture/escape: the re-built index must be the old
        // index modulo the rename; a silent re-binding has no diagnostic.
        if !crate::index_queries::index_unchanged_modulo_rename(&analysis.index, &post.index, &plan)
        {
            return Err(refused(format!(
                "renaming `{}` to `{new_name}` would silently re-bind another name — refused",
                plan.key.name
            )));
        }

        // Versioned edits: the client rejects the rename if a buffer drifted
        // past the analysed version rather than mis-applying it.
        let mut document_edits: Vec<TextDocumentEdit> = Vec::new();
        for (rel_path, spans) in &plan.edits {
            let Some(text) = analysis.snapshots.get(rel_path) else {
                continue;
            };
            let abs = analysis.project_root.join(rel_path);
            let Ok(file_uri) = Url::from_file_path(&abs) else {
                continue;
            };
            let edits: Vec<OneOf<TextEdit, AnnotatedTextEdit>> = spans
                .iter()
                .map(|span| {
                    OneOf::Left(TextEdit {
                        range: crate::position::span_to_range(text, *span),
                        new_text: plan.new_name.clone(),
                    })
                })
                .collect();
            document_edits.push(TextDocumentEdit {
                text_document: OptionalVersionedTextDocumentIdentifier {
                    uri: file_uri,
                    version: analysis.versions.get(rel_path).copied(),
                },
                edits,
            });
        }
        Ok(Some(WorkspaceEdit {
            changes: None,
            document_changes: Some(DocumentChanges::Edits(document_edits)),
            change_annotations: None,
        }))
    }

    /// #302: `workspace/willRenameFiles` — when a `.bynk` file is renamed or
    /// moved, keep `uses`/`consumes` references pointing at its unit in sync.
    /// Uses `analysis_covering_open_buffers`, the same gate `rename`
    /// uses: this handler emits multi-file **versioned** edits too, so a
    /// stale open buffer must be refreshed first or the client rejects the
    /// whole edit — unlike `documentLink`'s read-only decoration, which
    /// tolerates a round lagging by one debounce cycle.
    ///
    /// Never refuses: a filesystem rename isn't something this soft,
    /// edit-only hook can block (the response is just an optional edit), so
    /// anything this can't confidently resolve — an unparseable file, a
    /// `suite` (addressed by no one), a rename that preserves the unit's
    /// arrangement, a cross-project move, a name collision with an existing
    /// unit — is simply skipped rather than erroring the whole batch. The
    /// collision check is a lightweight `unit_sources` lookup, not `rename`'s
    /// full re-analysis: good enough to avoid handing back an edit that is
    /// *known in advance* to break the build, without paying for a second
    /// analysis round on every file move.
    ///
    /// Edits for the moved file's own declaration target `old_uri`, not
    /// `new_uri`: the client applies the returned edit against files at
    /// their current (pre-move) locations, then performs the actual rename,
    /// so the file lands at its new path already carrying the new name.
    /// Single-file rename only (the capability filter matches files, not
    /// folders) — a folder move is a follow-up.
    async fn will_rename_files(
        &self,
        params: RenameFilesParams,
    ) -> JsonRpcResult<Option<WorkspaceEdit>> {
        let mut combined: std::collections::HashMap<Url, (Option<i32>, Vec<TextEdit>)> =
            std::collections::HashMap::new();
        for fr in &params.files {
            let (Ok(old_uri), Ok(new_uri)) = (Url::parse(&fr.old_uri), Url::parse(&fr.new_uri))
            else {
                continue;
            };
            let Some(root) = self.root_for_uri(&old_uri).await else {
                continue;
            };
            let Some(analysis) = self.analysis_covering_open_buffers(&root).await else {
                continue;
            };
            let Some(old_rel) = Self::uri_to_rel(&analysis, &old_uri) else {
                continue;
            };
            // `new_uri` names a file that doesn't exist yet (`willRenameFiles`
            // fires before the physical move) — `uri_to_rel`'s canonicalize
            // would silently fail and fall back to the client's raw,
            // non-canonical path, which can mismatch `project_root` (always
            // canonical) whenever the workspace sits behind a symlink (macOS
            // `/tmp` → `/private/tmp` being the common case). Canonicalize the
            // *parent* directory instead — it does exist — and rejoin the
            // file name.
            let Some(new_rel) = Self::uri_to_rel_for_new_path(&analysis, &new_uri) else {
                continue;
            };
            let Some(text) = analysis.snapshots.get(&old_rel) else {
                continue;
            };
            let Some((old_name, name_span)) = crate::symbols::own_declaration_name(text) else {
                continue;
            };
            let Some(new_name) = bynk_ide::renamed_unit_name(&old_rel, &old_name, &new_rel) else {
                continue;
            };
            if new_name == old_name {
                continue;
            }
            // Refuse to hand back an edit that would create a duplicate unit
            // name — some other file already declares `new_name`.
            if analysis.unit_sources.contains_key(&new_name) {
                continue;
            }
            // Every file's Url is reconstructed the same way (never the
            // client's raw `old_uri`/`new_uri` strings) so the moved file's
            // own edit and a referencer's edit merge into the same
            // `TextDocumentEdit` when they're the same file — a raw client
            // string and a `from_file_path` reconstruction aren't guaranteed
            // byte-identical (percent-encoding, trailing slashes).
            let Ok(old_file_uri) = Url::from_file_path(analysis.project_root.join(&old_rel)) else {
                continue;
            };
            // The moved file's own declaration header — edited at its old
            // (still current) location.
            combined
                .entry(old_file_uri)
                .or_insert_with(|| (analysis.versions.get(&old_rel).copied(), Vec::new()))
                .1
                .push(TextEdit {
                    range: crate::position::span_to_range(text, name_span),
                    new_text: new_name.clone(),
                });
            // Every other file's `uses`/`consumes` references to the old name.
            for (rel, snap_text) in &analysis.snapshots {
                if *rel == old_rel {
                    continue;
                }
                let edits: Vec<TextEdit> = crate::symbols::unit_reference_spans(snap_text)
                    .into_iter()
                    .filter(|(unit, _)| *unit == old_name)
                    .map(|(_, span)| TextEdit {
                        range: crate::position::span_to_range(snap_text, span),
                        new_text: new_name.clone(),
                    })
                    .collect();
                if edits.is_empty() {
                    continue;
                }
                let Ok(file_uri) = Url::from_file_path(analysis.project_root.join(rel)) else {
                    continue;
                };
                combined
                    .entry(file_uri)
                    .or_insert_with(|| (analysis.versions.get(rel).copied(), Vec::new()))
                    .1
                    .extend(edits);
            }
        }
        if combined.is_empty() {
            return Ok(None);
        }
        let document_edits: Vec<TextDocumentEdit> = combined
            .into_iter()
            .map(|(uri, (version, edits))| TextDocumentEdit {
                text_document: OptionalVersionedTextDocumentIdentifier { uri, version },
                edits: edits.into_iter().map(OneOf::Left).collect(),
            })
            .collect();
        Ok(Some(WorkspaceEdit {
            changes: None,
            document_changes: Some(DocumentChanges::Edits(document_edits)),
            change_annotations: None,
        }))
    }

    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
        // #682: a `bynk.toml` create/delete/change is the one event that can
        // move an already-cached URI's route (see `State.root_cache`'s doc) —
        // invalidate the whole cache before this batch's lookups consult it,
        // so a manifest that just appeared/vanished is reflected within the
        // same round rather than one event late. The generation bump closes
        // `root_for_uri`'s TOCTOU window against a walk already in flight.
        if params.changes.iter().any(|ev| is_bynk_toml(&ev.uri)) {
            let mut state = self.state.write().await;
            state.root_cache.clear();
            state.root_cache_generation += 1;
        }
        // For every changed `.bynk` file we have open, refresh diagnostics.
        // Changes to files we do *not* have open (a git checkout, an external
        // edit) still invalidate the project index — schedule a project round
        // so cross-file state doesn't go stale (#513).
        let mut uris_to_refresh = Vec::new();
        // Slice D: route each change to its owning project root, so a change in
        // project A never re-analyses project B.
        let mut roots_to_reanalyse: std::collections::HashSet<PathBuf> =
            std::collections::HashSet::new();
        // A `bynk.toml` edit changes the formatting style, the diagnostics
        // mode/debounce, and the source root — none of which were re-read after
        // the initial load, so the settings only took effect on an LSP restart.
        // Detect the change here and reload that project's config before
        // re-analysing it.
        let mut config_changed_roots: std::collections::HashSet<PathBuf> =
            std::collections::HashSet::new();
        // #682: snapshotted off the lock — the loop below calls the
        // cache-consulting `root_for_uri`, which itself locks `state`, so it
        // must not run while a read lock from this function is still held.
        let open_docs: std::collections::HashSet<Url> =
            self.state.read().await.docs.keys().cloned().collect();
        for ev in &params.changes {
            if is_bynk_toml(&ev.uri) {
                // The manifest's own directory is the project root.
                if let Ok(p) = ev.uri.to_file_path()
                    && let Some(dir) = p.parent()
                {
                    let root = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
                    config_changed_roots.insert(root.clone());
                    roots_to_reanalyse.insert(root);
                }
            } else if open_docs.contains(&ev.uri) {
                uris_to_refresh.push(ev.uri.clone());
            } else if ev.uri.path().ends_with(".bynk")
                && let Some(root) = self.root_for_uri(&ev.uri).await
            {
                roots_to_reanalyse.insert(root);
            }
        }
        // A `bynk.toml` change reloads its project's config — and, if the
        // manifest was just *created*, warms the new project (create the entry).
        // Slice E: this is how a project added after startup is picked up now
        // that `workspace/symbol` no longer walks the tree per query.
        for root in &config_changed_roots {
            let config = project::load_config(root).unwrap_or_default();
            let mut state = self.state.write().await;
            state
                .projects
                .entry(root.clone())
                .and_modify(|ps| ps.config = config.clone())
                .or_insert_with(|| ProjectState {
                    config,
                    ..Default::default()
                });
        }
        for uri in uris_to_refresh {
            self.schedule_diagnostics(&uri).await;
        }
        // A reloaded config re-derives the diagnostics behaviour, so re-analyse
        // each affected project against it — the same debounced round a non-open
        // `.bynk` change schedules. A no-op for a root with no entry (a project
        // no file has opened): nothing is published there to go stale.
        for root in roots_to_reanalyse {
            self.schedule_project_diagnostics(root).await;
        }
    }

    async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
        // Slice D (Q4): folders are discovery seeds, not routing owners.
        // Added folders extend the seed set; removed folders shrink it, then any
        // project a removed folder orphaned — no remaining folder, no open
        // buffer — is pruned.
        let added_dirs: Vec<PathBuf> = {
            let mut state = self.state.write().await;
            let mut added = Vec::new();
            for a in &params.event.added {
                if let Ok(p) = a.uri.to_file_path() {
                    let dir = p.canonicalize().unwrap_or(p);
                    if !state.folders.contains(&dir) {
                        state.folders.push(dir.clone());
                        added.push(dir);
                    }
                }
            }
            for removed in &params.event.removed {
                if let Ok(p) = removed.uri.to_file_path() {
                    let dir = p.canonicalize().unwrap_or(p);
                    state.folders.retain(|f| f != &dir);
                }
            }
            // #682: `resolve_canonical` never consults `folders` — a folder
            // change cannot actually move any URI's route today — but clear
            // (and bump the generation, same as the `bynk.toml` case) as a
            // defensive, effectively-free no-op against that ever changing,
            // rather than relying on routing's independence from folders
            // staying true forever.
            state.root_cache.clear();
            state.root_cache_generation += 1;
            added
        };
        // Slice E: warm the added folders proactively — the analysis D deferred
        // to here, using the same discovery walk as startup.
        self.warm_projects(&added_dirs).await;
        // Clear the dropped projects' diagnostics so the client does not keep
        // showing stale squiggles for a folder that is gone.
        for uri in self.prune_orphaned_projects().await {
            self.client.publish_diagnostics(uri, Vec::new(), None).await;
        }
    }
}

/// The advertised capability set — `design/bynk-lsp-spec.md` §4.3. Split out
/// of `initialize` so the advertisement is unit-testable without transport.
fn server_capabilities() -> ServerCapabilities {
    ServerCapabilities {
        // Full-text sync, with save notifications explicitly opted in — the
        // `on_save` diagnostics mode is driven by `didSave` (#513).
        text_document_sync: Some(TextDocumentSyncCapability::Options(
            TextDocumentSyncOptions {
                open_close: Some(true),
                change: Some(TextDocumentSyncKind::FULL),
                save: Some(TextDocumentSyncSaveOptions::Supported(true)),
                ..Default::default()
            },
        )),
        hover_provider: Some(HoverProviderCapability::Simple(true)),
        definition_provider: Some(OneOf::Left(true)),
        // v0.17: completion for `consumes` units and `given` /
        // `consumes U { … }` capabilities. Trigger on the space after a
        // keyword, the `{` of a selected-capability list, and `,`. The `.`
        // auto-fires the name- and value-receiver member contexts (ADR 0093 D1).
        completion_provider: Some(CompletionOptions {
            trigger_characters: Some(vec![
                " ".to_string(),
                "{".to_string(),
                ",".to_string(),
                ".".to_string(),
            ]),
            // Slice 5: resolve fills in hover-quality `documentation` lazily, on
            // the focused item only, so the initial list stays cheap.
            resolve_provider: Some(true),
            ..Default::default()
        }),
        // v0.32 (ADR 0065): signature help while typing a call's arguments.
        signature_help_provider: Some(SignatureHelpOptions {
            trigger_characters: Some(vec!["(".to_string(), ",".to_string()]),
            retrigger_characters: Some(vec![",".to_string()]),
            ..Default::default()
        }),
        // v0.33 (ADR 0066): reference-count lenses above top-level definitions.
        code_lens_provider: Some(CodeLensOptions {
            resolve_provider: Some(false),
        }),
        // v0.34 (ADR 0067): call hierarchy over the binding index's call graph.
        call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
        // v0.35 (ADR 0068): implementation nav — capability → its providers.
        implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
        // Slice 6: go-to-type-definition (value → its type's declaration).
        type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
        // Slice 6b: `uses`/`consumes` unit names link to their source.
        document_link_provider: Some(DocumentLinkOptions {
            resolve_provider: Some(false),
            work_done_progress_options: Default::default(),
        }),
        document_formatting_provider: Some(OneOf::Left(true)),
        document_range_formatting_provider: Some(OneOf::Left(true)),
        document_symbol_provider: Some(OneOf::Left(true)),
        // v0.37 (ADR 0070): structural folding + selection ranges (AST-driven).
        folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
        selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
        // v0.25 (ADR 0053): references + rename over the binding
        // index; prepareRename refuses out-of-scope symbols.
        references_provider: Some(OneOf::Left(true)),
        rename_provider: Some(OneOf::Right(RenameOptions {
            prepare_provider: Some(true),
            work_done_progress_options: Default::default(),
        })),
        // v0.26 (ADR 0054): quick-fixes from the diagnostics' structured
        // suggestions. v0.213 (ADR 0239) adds the extract-variable refactor.
        code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
            code_action_kinds: Some(vec![
                CodeActionKind::QUICKFIX,
                CodeActionKind::REFACTOR,
                CodeActionKind::REFACTOR_EXTRACT,
            ]),
            ..Default::default()
        })),
        // v0.27 (ADR 0056): inferred-type inlay hints from the retained
        // analysis round's harvested hint set.
        inlay_hint_provider: Some(OneOf::Left(true)),
        // v0.28 (ADR 0057): semantic tokens over the frozen legend — a
        // pure read of the cached index (`symbols` + `foreign_refs`),
        // additive over the client's syntactic layer. `delta` deferred.
        semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
            SemanticTokensOptions {
                legend: crate::index_queries::semantic_tokens_legend(),
                full: Some(SemanticTokensFullOptions::Bool(true)),
                range: Some(true),
                ..Default::default()
            },
        )),
        // v0.26 riders (ADR 0055): both are `ProjectIndex` queries.
        workspace_symbol_provider: Some(OneOf::Left(true)),
        document_highlight_provider: Some(OneOf::Left(true)),
        workspace: Some(WorkspaceServerCapabilities {
            workspace_folders: Some(WorkspaceFoldersServerCapabilities {
                supported: Some(true),
                change_notifications: Some(OneOf::Left(true)),
            }),
            // #302: `willRenameFiles` over `.bynk` files only (not folders) —
            // keeps `uses`/`consumes` references in sync on a single-file
            // rename/move; a folder move is a follow-up.
            file_operations: Some(WorkspaceFileOperationsServerCapabilities {
                will_rename: Some(FileOperationRegistrationOptions {
                    filters: vec![FileOperationFilter {
                        scheme: Some("file".to_string()),
                        pattern: FileOperationPattern {
                            glob: "**/*.bynk".to_string(),
                            matches: Some(FileOperationPatternKind::File),
                            options: None,
                        },
                    }],
                }),
                ..Default::default()
            }),
        }),
        // #846/#847: no standard `ServerCapabilities` field exists for a custom
        // request — `experimental` is the only feature-detection surface a
        // client has for `bynk/sequenceModel` and `bynk/documentationModel`.
        experimental: Some(serde_json::json!({
            "sequenceModel": true,
            "documentationModel": true,
        })),
        ..Default::default()
    }
}

/// Index symbol kind → LSP symbol kind, aligned with the document-symbol
/// outline's choices (capability=INTERFACE, service/agent=CLASS,
/// provider=OBJECT). The index does not distinguish type shapes, so every
/// type maps to STRUCT.
/// Map a `completion::Completion` to an LSP `CompletionItem`.
/// Stash the document URI in each item's `data` so `completion_resolve` can look
/// the symbol up — a resolve request carries only the item, not a position.
fn stamp_resolve_data(items: &mut [CompletionItem], uri: &Url) {
    let data = serde_json::json!({ "uri": uri.to_string() });
    for item in items.iter_mut() {
        item.data = Some(data.clone());
    }
}

/// v0.124 (slice 3): the enclosing function's parameters (and `result` for an
/// `ensures`) as completions, when `offset` sits in a `requires`/`ensures`
/// predicate. Empty when not in a contract clause or no enclosing `fn` is
/// found. A pure parse — the params are read straight off the recovered AST.
/// v0.131: the CORS completion cells. Inside a `cors { }` block at a field-name
/// position, offer the closed field set; at a service-body item start, offer the
/// `cors` section keyword. Both are lexical (offset-based), matching the
/// `contract_param_completions` posture.
fn cors_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    if completion::in_cors_field_position(text, offset) {
        return completion::CORS_FIELDS
            .iter()
            .map(|(name, doc)| CompletionItem {
                label: name.to_string(),
                kind: Some(CompletionItemKind::FIELD),
                detail: Some((*doc).to_string()),
                insert_text: Some(format!("{name}: ")),
                ..Default::default()
            })
            .collect();
    }
    if completion::in_service_body_item_position(text, offset, line) {
        return vec![CompletionItem {
            label: "cors".to_string(),
            kind: Some(CompletionItemKind::KEYWORD),
            detail: Some("a cross-origin (CORS) policy for this HTTP service".to_string()),
            insert_text: Some("cors {\n\torigins: [$0],\n}".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }];
    }
    Vec::new()
}

/// v0.141 (ADR 0164): the security-headers completion cells. Inside a
/// `security { }` block at a field-name position, offer the closed field set
/// (`nosniff`/`hsts`); at a service-body item start, offer the `security` section
/// keyword. Both are lexical (offset-based), mirroring `cors_completions`.
fn security_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    if completion::in_security_field_position(text, offset) {
        return completion::SECURITY_FIELDS
            .iter()
            .map(|(name, doc)| CompletionItem {
                label: name.to_string(),
                kind: Some(CompletionItemKind::FIELD),
                detail: Some((*doc).to_string()),
                insert_text: Some(format!("{name}: ")),
                ..Default::default()
            })
            .collect();
    }
    if completion::in_service_body_item_position(text, offset, line) {
        return vec![CompletionItem {
            label: "security".to_string(),
            kind: Some(CompletionItemKind::KEYWORD),
            detail: Some("security response headers for this HTTP service".to_string()),
            insert_text: Some("security {\n\tnosniff: $0,\n}".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }];
    }
    Vec::new()
}

/// v0.140 (ADR 0163): the `@cache` completion cells. Inside `@cache( … )` at an
/// argument-name position, offer the closed argument set (`maxAge`/`scope`); at a
/// service-body item start, offer the `@cache` annotation snippet. Both are lexical
/// (offset-based), mirroring `cors_completions`.
fn cache_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    if completion::in_cache_arg_position(text, offset) {
        return completion::CACHE_ARGS
            .iter()
            .map(|(name, doc)| CompletionItem {
                label: name.to_string(),
                kind: Some(CompletionItemKind::FIELD),
                detail: Some((*doc).to_string()),
                insert_text: Some(format!("{name}: ")),
                ..Default::default()
            })
            .collect();
    }
    if completion::in_service_body_item_position(text, offset, line) {
        return vec![CompletionItem {
            label: "@cache".to_string(),
            kind: Some(CompletionItemKind::SNIPPET),
            detail: Some(
                "cache a GET read — a synthesised ETag/304 revalidation with a freshness window"
                    .to_string(),
            ),
            insert_text: Some("@cache(maxAge: ${1:5.minutes})".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }];
    }
    Vec::new()
}

/// v0.142 (ADR 0165): the request-limits completion cells. Inside a `limits { }`
/// block at a field-name position, offer the closed field set (`maxBody`); at a
/// service-body item start, offer the `limits` section keyword. Both are lexical
/// (offset-based), mirroring `security_completions`.
fn limits_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    if completion::in_limits_field_position(text, offset) {
        return completion::LIMITS_FIELDS
            .iter()
            .map(|(name, doc)| CompletionItem {
                label: name.to_string(),
                kind: Some(CompletionItemKind::FIELD),
                detail: Some((*doc).to_string()),
                insert_text: Some(format!("{name}: ")),
                ..Default::default()
            })
            .collect();
    }
    if completion::in_service_body_item_position(text, offset, line) {
        return vec![CompletionItem {
            label: "limits".to_string(),
            kind: Some(CompletionItemKind::KEYWORD),
            detail: Some("request limits for this HTTP service".to_string()),
            insert_text: Some("limits {\n\tmaxBody: $0,\n}".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }];
    }
    Vec::new()
}

/// v0.142 (ADR 0165): the `@limit` completion cells. Inside `@limit( … )` at an
/// argument-name position, offer the closed argument set (`maxBody`); at a
/// service-body item start, offer the `@limit` annotation snippet. Both are lexical
/// (offset-based), mirroring `cache_completions`.
fn limit_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    if completion::in_limit_arg_position(text, offset) {
        return completion::LIMIT_ARGS
            .iter()
            .map(|(name, doc)| CompletionItem {
                label: name.to_string(),
                kind: Some(CompletionItemKind::FIELD),
                detail: Some((*doc).to_string()),
                insert_text: Some(format!("{name}: ")),
                ..Default::default()
            })
            .collect();
    }
    if completion::in_service_body_item_position(text, offset, line) {
        return vec![CompletionItem {
            label: "@limit".to_string(),
            kind: Some(CompletionItemKind::SNIPPET),
            detail: Some(
                "cap the request body size — a `413` synthesised before the body is read"
                    .to_string(),
            ),
            insert_text: Some("@limit(maxBody: ${1:1048576})".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }];
    }
    Vec::new()
}

fn contract_param_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
    use bynk_syntax::ast::{CommonsItem, SourceUnit};
    let Some(is_ensures) = completion::contract_clause_kind(line) else {
        return Vec::new();
    };
    let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
        return Vec::new();
    };
    let (Some(unit), _) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text) else {
        return Vec::new();
    };
    let items = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        _ => return Vec::new(),
    };
    for item in items {
        // The cursor sits in a fn's signature/contract region: between the fn's
        // start and the `{` that opens its body.
        if let CommonsItem::Fn(f) = item
            && f.span.start <= offset
            && offset <= f.body.span.start
        {
            // Built directly as VARIABLE items, matching `locals_completions`
            // (in-scope names carry no resolve data).
            let mut out: Vec<CompletionItem> = f
                .params
                .iter()
                .filter(|p| p.name.name != "_")
                .map(|p| CompletionItem {
                    label: p.name.name.clone(),
                    kind: Some(CompletionItemKind::VARIABLE),
                    detail: Some(format!(
                        "parameter: {}",
                        crate::symbols::type_ref_str(&p.type_ref)
                    )),
                    ..Default::default()
                })
                .collect();
            if is_ensures {
                out.push(CompletionItem {
                    label: "result".to_string(),
                    kind: Some(CompletionItemKind::VARIABLE),
                    detail: Some("the function's return value".to_string()),
                    ..Default::default()
                });
            }
            return out;
        }
    }
    Vec::new()
}

/// v0.124 (slice 3): the byte offset of the scrutinee's last character in
/// `<scrutinee> is <partial>` ending at `cursor`, or `None` if the cursor is
/// not at an `is`-pattern position. `is` must be a standalone word (so `basis`
/// does not trigger it).
fn is_scrutinee_offset(text: &str, cursor: usize) -> Option<usize> {
    let before = text.get(..cursor)?;
    // Drop the partial variant being typed, then the whitespace before it.
    let before = before
        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
        .trim_end();
    let before = before.strip_suffix("is")?;
    if !before.ends_with(char::is_whitespace) {
        return None;
    }
    let before = before.trim_end();
    (!before.is_empty()).then(|| before.len() - 1)
}

/// v0.128: the byte offset of the scrutinee's last character in a
/// `match <scrutinee> { … <partial>` whose cursor sits at an **arm-pattern-start**
/// position, or `None` otherwise — the deferred half of slice 3's `is`-pattern
/// completion. Conservative: it fires only at the *start* of an arm's pattern
/// (after the `{` or a top-level `,`, before any `=>`), never inside an arm body
/// or a nested constructor pattern, so it stays honest mid-edit.
fn match_scrutinee_offset(text: &str, cursor: usize) -> Option<usize> {
    let before = text.get(..cursor)?;
    // The innermost `{` still open at the cursor — the block the cursor is in.
    let brace = innermost_open_brace(before)?;
    // The current arm: from the last top-level `,` after the brace (or the brace
    // itself) to the cursor. A `=>` in it means the cursor is in the arm body.
    let arm_start = arm_start_offset(before, brace);
    let arm = before.get(arm_start..)?;
    if arm.contains("=>") {
        return None;
    }
    // Only at the pattern's *start*: nothing but the partial pattern being typed
    // sits between the arm boundary and the cursor.
    if !arm
        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
        .trim()
        .is_empty()
    {
        return None;
    }
    match_head_scrutinee_offset(before, brace)
}

/// v0.145 (ADR 0169): the scrutinee offset and outer variant name at a
/// `match <scrutinee> { … OuterVariant(<partial>` position — the cursor inside a
/// variant's payload parens within an arm-pattern (before `=>`), the one place
/// `match_scrutinee_offset` bails. Conservative: the payload `(` must be still
/// open, the token before it an uppercase-led variant constructor, and only the
/// partial nested pattern may sit between the `(` and the cursor.
fn nested_pattern_offset(text: &str, cursor: usize) -> Option<(usize, String)> {
    let before = text.get(..cursor)?;
    let brace = innermost_open_brace(before)?;
    let arm_start = arm_start_offset(before, brace);
    let arm = before.get(arm_start..)?;
    if arm.contains("=>") {
        return None; // in the arm body, not its pattern
    }
    // The innermost `(` still open in the arm — the outer variant's payload.
    let paren = innermost_open_paren(arm)?;
    // The identifier immediately before that `(` is the outer variant; only an
    // uppercase-led constructor opens a nested pattern (a binding never does).
    let head = arm.get(..paren)?.trim_end();
    let variant: String = head
        .chars()
        .rev()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    if !variant.chars().next().is_some_and(char::is_uppercase) {
        return None;
    }
    // Between the payload `(` and the cursor, only the partial nested pattern
    // being typed (an identifier, optionally a `Type.` qualifier) may sit.
    let after = arm.get(paren + 1..)?;
    if !after
        .trim_start_matches(|c: char| c.is_alphanumeric() || c == '_' || c == '.')
        .trim()
        .is_empty()
    {
        return None;
    }
    let scrut_off = match_head_scrutinee_offset(before, brace)?;
    Some((scrut_off, variant))
}

/// The byte offset of the scrutinee's last character for the `match <scrutinee>`
/// whose body brace is at `brace`, or `None` if `brace` does not head a
/// `match`: a standalone `match` keyword, then a scrutinee expression with no
/// nested block or arrow between it and the brace. Shared by
/// `match_scrutinee_offset` and `nested_pattern_offset`.
fn match_head_scrutinee_offset(before: &str, brace: usize) -> Option<usize> {
    let head = before.get(..brace)?.trim_end();
    let m = head.rfind("match")?;
    if head[..m]
        .chars()
        .next_back()
        .is_some_and(|c| c.is_alphanumeric() || c == '_')
    {
        return None; // part of a longer identifier (`rematch`), not the keyword
    }
    let after = head.get(m + "match".len()..)?;
    if !after.starts_with(char::is_whitespace) {
        return None;
    }
    let scrut = after.trim();
    if scrut.is_empty() || scrut.contains(['{', '}']) || scrut.contains("=>") {
        return None;
    }
    // `head` was trimmed to end at the scrutinee's last char (the brace followed).
    Some(head.len() - 1)
}

/// The offset (relative to `arm`) of the innermost `(` left unclosed in `arm` — a
/// `(`-only balance scan, the payload paren the cursor sits in — or `None` if
/// every `(` is closed.
fn innermost_open_paren(arm: &str) -> Option<usize> {
    let mut stack: Vec<usize> = Vec::new();
    for (i, c) in arm.char_indices() {
        match c {
            '(' => stack.push(i),
            ')' => {
                stack.pop();
            }
            _ => {}
        }
    }
    stack.pop()
}

/// The byte offset of the innermost `{` left unclosed in `before` (a `{`-only
/// balance scan — the block the cursor sits in), or `None` if every `{` is closed.
fn innermost_open_brace(before: &str) -> Option<usize> {
    let mut stack: Vec<usize> = Vec::new();
    for (i, c) in before.char_indices() {
        match c {
            '{' => stack.push(i),
            '}' => {
                stack.pop();
            }
            _ => {}
        }
    }
    stack.pop()
}

/// The offset just past the last top-level `,` inside the block opened at `brace`
/// (depth 0 relative to that brace), or just past the brace itself if the block
/// holds no top-level comma yet — the start of the arm the cursor is editing.
fn arm_start_offset(before: &str, brace: usize) -> usize {
    let mut depth = 0i32;
    let mut start = brace + 1; // just after the `{`
    for (rel, c) in before[brace + 1..].char_indices() {
        match c {
            '{' | '(' | '[' => depth += 1,
            '}' | ')' | ']' => depth -= 1,
            ',' if depth == 0 => start = brace + 1 + rel + c.len_utf8(),
            _ => {}
        }
    }
    start
}

fn to_completion_item(c: completion::Completion) -> CompletionItem {
    CompletionItem {
        kind: Some(match c.kind {
            completion::CompletionKind::Unit => CompletionItemKind::MODULE,
            completion::CompletionKind::Capability => CompletionItemKind::INTERFACE,
            completion::CompletionKind::Type => CompletionItemKind::STRUCT,
            completion::CompletionKind::Keyword => CompletionItemKind::KEYWORD,
            completion::CompletionKind::Snippet => CompletionItemKind::SNIPPET,
            completion::CompletionKind::Variant => CompletionItemKind::ENUM_MEMBER,
            completion::CompletionKind::Member => CompletionItemKind::METHOD,
            completion::CompletionKind::Field => CompletionItemKind::FIELD,
            completion::CompletionKind::Constructor => CompletionItemKind::CONSTRUCTOR,
            completion::CompletionKind::Function => CompletionItemKind::FUNCTION,
        }),
        // Snippet items carry `${n:…}` tab stops; everything else inserts its
        // label verbatim (the default).
        insert_text_format: c.insert_text.as_ref().map(|_| InsertTextFormat::SNIPPET),
        insert_text: c.insert_text,
        label: c.label,
        detail: c.detail,
        ..Default::default()
    }
}

/// The byte offset of an LSP `(line, character)` position in `text`,
/// clamped to the end of the document when the position lies past it.
/// LSP positions count UTF-16 code units, so this goes through the shared
/// converter — a byte-faithful reading misplaces the cursor on any line
/// with non-ASCII text before it.
fn cursor_offset(text: &str, pos: Position) -> usize {
    crate::position::position_to_offset(text, pos).unwrap_or(text.len())
}

/// v0.34 (ADR 0067): a serializable mirror of [`bynk_check::index::SymbolKey`] for
/// round-tripping through `CallHierarchyItem.data` — the index kind isn't
/// `Serialize`, so the kind travels as its `display()` string.
#[derive(serde::Serialize, serde::Deserialize)]
struct SerKey {
    unit: String,
    kind: String,
    name: String,
}

impl From<&bynk_check::index::SymbolKey> for SerKey {
    fn from(k: &bynk_check::index::SymbolKey) -> Self {
        SerKey {
            unit: k.unit.clone(),
            kind: k.kind.display().to_string(),
            name: k.name.clone(),
        }
    }
}

impl SerKey {
    /// Recover a `SymbolKey` from a `CallHierarchyItem`'s `data`. `None` for a
    /// missing/garbled payload or an unknown kind — the follow-up then returns
    /// no calls rather than guessing.
    fn read(data: &Option<serde_json::Value>) -> Option<bynk_check::index::SymbolKey> {
        let sk: SerKey = serde_json::from_value(data.as_ref()?.clone()).ok()?;
        let kind = match sk.kind.as_str() {
            "type" => bynk_check::index::SymbolKind::Type,
            "fn" => bynk_check::index::SymbolKind::Fn,
            "capability" => bynk_check::index::SymbolKind::Capability,
            "service" => bynk_check::index::SymbolKind::Service,
            "agent" => bynk_check::index::SymbolKind::Agent,
            "provider" => bynk_check::index::SymbolKind::Provider,
            _ => return None,
        };
        Some(bynk_check::index::SymbolKey {
            unit: sk.unit,
            kind,
            name: sk.name,
        })
    }
}

fn lsp_symbol_kind(kind: bynk_check::index::SymbolKind) -> SymbolKind {
    match kind {
        bynk_check::index::SymbolKind::Type => SymbolKind::STRUCT,
        bynk_check::index::SymbolKind::Fn => SymbolKind::FUNCTION,
        bynk_check::index::SymbolKind::Capability => SymbolKind::INTERFACE,
        bynk_check::index::SymbolKind::Service | bynk_check::index::SymbolKind::Agent => {
            SymbolKind::CLASS
        }
        bynk_check::index::SymbolKind::Provider => SymbolKind::OBJECT,
        bynk_check::index::SymbolKind::Method => SymbolKind::METHOD,
        bynk_check::index::SymbolKind::CapabilityOp => SymbolKind::METHOD,
        bynk_check::index::SymbolKind::Field => SymbolKind::FIELD,
        bynk_check::index::SymbolKind::Actor => SymbolKind::INTERFACE,
        bynk_check::index::SymbolKind::Handler => SymbolKind::METHOD,
        bynk_check::index::SymbolKind::Messages => SymbolKind::STRUCT,
    }
}

/// Whether a watched-file URI names a `bynk.toml` manifest — the trigger for a
/// live config reload. Matches on the file-name component (not a path suffix),
/// so a file like `notbynk.toml` doesn't spuriously fire.
fn is_bynk_toml(uri: &Url) -> bool {
    let Ok(path) = uri.to_file_path() else {
        return false;
    };
    path.file_name().and_then(|n| n.to_str()) == Some("bynk.toml")
}

/// The `codeDescription` link for a diagnostic `code` (#853): a clickable link
/// to the code's Book explanation when the compiler curates one, else `None`
/// (the designed graceful-fallback state — an uncurated code renders no link,
/// which is not an error). Split out from [`make_diagnostic`] so the
/// mapped→`Some` / uncurated→`None` contract is directly testable.
fn code_description(code: &str) -> Option<CodeDescription> {
    let href = Url::parse(&bynk_syntax::diagnostics::explain(code)?.href()).ok()?;
    Some(CodeDescription { href })
}

#[cfg(test)]
mod code_description_tests {
    use super::code_description;

    #[test]
    fn mapped_code_gets_a_valid_book_link() {
        let cd = code_description("bynk.resolve.unknown_type")
            .expect("a curated code produces a codeDescription");
        assert_eq!(cd.href.scheme(), "https");
        assert_eq!(cd.href.host_str(), Some("bynk-lang.org"));
        assert!(cd.href.path().starts_with("/book/"));
    }

    #[test]
    fn uncurated_code_gets_no_link() {
        // A real code with no curated explanation, and a nonsense code, both
        // fall back to no link (graceful — not an error).
        assert!(code_description("bynk.resolve.duplicate_type").is_none());
        assert!(code_description("bynk.not.a_real_code").is_none());
    }

    #[test]
    fn every_curated_explanation_yields_a_parseable_url() {
        // Guards that no curated href ever silently drops its link because
        // `Url::parse` rejected it.
        for e in bynk_syntax::diagnostics::EXPLANATIONS {
            assert!(
                code_description(e.code).is_some(),
                "curated explanation `{}` produced no codeDescription — its href \
                 `{}` did not parse as a URL",
                e.code,
                e.href()
            );
        }
    }
}

fn make_diagnostic(
    d: &bynk_ide::Diagnostic,
    positions: &crate::position::PositionMap,
    uri: &Url,
) -> Diagnostic {
    let range = positions.range(d.error.span);
    let severity = match d.severity {
        bynk_syntax::Severity::Error => DiagnosticSeverity::ERROR,
        bynk_syntax::Severity::Warning => DiagnosticSeverity::WARNING,
    };
    let related_information: Vec<DiagnosticRelatedInformation> = d
        .error
        .labels
        .iter()
        .map(|(span, msg)| DiagnosticRelatedInformation {
            location: Location {
                // Secondary-label spans are offsets into this same document's
                // `text`, so they belong to the document's own URI — not a
                // placeholder. (Cross-file related info is not yet modelled.)
                uri: uri.clone(),
                range: positions.range(*span),
            },
            message: msg.clone(),
        })
        .collect();
    let mut message = d.error.message.clone();
    for note in &d.error.notes {
        message.push_str("\n\n");
        message.push_str("note: ");
        message.push_str(note);
    }
    Diagnostic {
        range,
        severity: Some(severity),
        code: Some(NumberOrString::String(d.error.category.to_string())),
        // #853: a curated code carries a `codeDescription` link to its Book
        // explanation (rendered as a link on the code in Problems/hover); an
        // uncurated code has no entry and stays `None` — the designed
        // graceful-fallback state, not an error.
        code_description: code_description(d.error.category),
        source: Some(SERVER_NAME.to_string()),
        message,
        related_information: if related_information.is_empty() {
            None
        } else {
            Some(related_information)
        },
        tags: None,
        data: None,
    }
}

/// Slice C: the server's entry point, moved out of `main.rs` so the crate
/// has a `[lib]` target. `main.rs` is now a thin shim over this.
pub async fn run() {
    // Answer `--version`/`-V` and exit before entering the stdio LSP loop, so
    // tooling (e.g. the VS Code status bar) can query the version without the
    // server blocking on stdin.
    if std::env::args()
        .skip(1)
        .any(|a| a == "--version" || a == "-V")
    {
        println!("{SERVER_NAME} {SERVER_VERSION}");
        return;
    }
    // Logging to ~/.bynk-lsp.log. Default level: warn; tunable via
    // RUST_LOG or the LSP client's trace setting.
    if let Some(home) = std::env::var_os("HOME") {
        let path: PathBuf = PathBuf::from(home).join(".bynk-lsp.log");
        if let Ok(file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        {
            use tracing_subscriber::prelude::*;
            let env_filter = tracing_subscriber::EnvFilter::try_from_env("BYNK_LSP_LOG")
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
            let file_layer = tracing_subscriber::fmt::layer()
                .with_writer(std::sync::Mutex::new(file))
                .with_ansi(false);
            tracing_subscriber::registry()
                .with(env_filter)
                .with(file_layer)
                .try_init()
                .ok();
        }
    }
    tracing::info!("bynkc-lsp v{} starting", SERVER_VERSION);
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();
    // #846: this server's first custom (non-standard) request — everything
    // else is a `LanguageServer` trait method, registered automatically by
    // `LspService::new`. `bynk/sequenceModel` has no trait slot, so it needs
    // the builder's `custom_method` instead.
    let (service, socket) = LspService::build(Backend::new)
        .custom_method("bynk/sequenceModel", Backend::sequence_model)
        .custom_method("bynk/documentationModel", Backend::documentation_model)
        .finish();
    Server::new(stdin, stdout, socket).serve(service).await;
}

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

    // -- Slice A: the project model, driven through `Backend` ---------------
    //
    // These are the crate's first *behaviour-over-time* tests: they drive the
    // real `Backend` — the layer the track doc (§4.1) notes has always been
    // testable in-crate via `LspService::new(Backend::new)`, and never was.
    // Everything else in this module asserts *static* shape.
    //
    // Hermetic on purpose. `bynk-lsp` is published and `Cargo.toml`'s `exclude`
    // list can only drop `tests/*.rs`, never this file — so an in-crate test
    // reading a sibling directory would fail `cargo test` on the released
    // tarball. (`find_source_root_walks_up_to_the_nearest_src` below already
    // does exactly that; not this slice's to fix.) The sibling-reading fixtures
    // live in `tests/project_model.rs`, which *is* excluded.

    /// A throwaway project, removed on drop — including on panic.
    struct Scratch(PathBuf);
    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn scratch_project(tag: &str, files: &[(&str, &str)]) -> Scratch {
        let dir = std::env::temp_dir().join(format!(
            "bynk_lsp_sliceA_{tag}_{}_{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        for (rel, body) in files {
            let p = dir.join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(&p, body).unwrap();
        }
        Scratch(dir)
    }

    /// Build a `Backend` over a real `LspService`, rooted at `root`.
    ///
    /// `LspService::new(Backend::new)` is what `main` itself calls — the
    /// `Client` it hands back is the only thing `Backend` needed, and it has
    /// been available for this since the server was written.
    async fn backend_at(root: &std::path::Path) -> Backend {
        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
        let backend = service.inner().clone();
        // Slice D: seed one project entry, keyed by the **canonical** root so a
        // request's `resolve_root`-based routing lands on the same key.
        let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
        {
            let mut state = backend.state.write().await;
            state.folders.push(canonical.clone());
            state.projects.insert(
                canonical.clone(),
                ProjectState {
                    config: project::load_config(&canonical).unwrap_or_default(),
                    ..Default::default()
                },
            );
        }
        backend
    }

    /// Test helpers for the single-project behaviour tests (each builds exactly
    /// one project via `backend_at` or an equivalent insert). They read whatever
    /// the one entry's key is, so a test need not thread the canonical root.
    impl Backend {
        async fn test_root(&self) -> PathBuf {
            self.state
                .read()
                .await
                .projects
                .keys()
                .next()
                .cloned()
                .expect("a test project entry")
        }
        async fn run_round(&self) {
            let root = self.test_root().await;
            self.run_project_diagnostics(root).await;
        }
        async fn test_analysis(&self) -> Option<Arc<Analysis>> {
            let root = self.test_root().await;
            self.project_analysis(&root).await
        }
        async fn test_round_started(&self) -> u64 {
            let root = self.test_root().await;
            self.state
                .read()
                .await
                .projects
                .get(&root)
                .map(|p| p.analysis_round_started)
                .unwrap_or(0)
        }
    }

    /// The slice, end to end through the server: a round covers **every**
    /// `include` tree, and each file keeps a distinct project-relative identity
    /// (ADR 0198). Before slice A the round was handed `<root>/src` and the
    /// `tests/` tree did not exist as far as the LSP was concerned.
    #[tokio::test]
    async fn a_round_covers_every_include_tree() {
        let s = scratch_project(
            "round",
            &[
                ("bynk.toml", "[project]\nname = \"round\"\n"),
                ("src/thing.bynk", "context thing\n"),
                // Same basename, second root — the ADR 0198 collision.
                ("tests/thing.bynk", "suite thing\n"),
            ],
        );
        let backend = backend_at(&s.0).await;
        backend.run_round().await;

        let analysis = backend.test_analysis().await.expect("a round committed");
        let mut keys: Vec<String> = analysis
            .snapshots
            .keys()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .collect();
        keys.sort();
        assert_eq!(
            keys,
            vec!["src/thing.bynk", "tests/thing.bynk"],
            "the round must cover both include trees, with distinct identities",
        );
    }

    /// The identity a request resolves through. `uri_to_rel` is one
    /// `strip_prefix` against the project root — total across `include` trees,
    /// where the old `src` base could only ever name files in one of them.
    #[tokio::test]
    async fn a_uri_in_any_include_tree_resolves_to_its_analysed_file() {
        let s = scratch_project(
            "uri",
            &[
                ("bynk.toml", "[project]\nname = \"uri\"\n"),
                ("src/thing.bynk", "context thing\n"),
                ("tests/thing.bynk", "suite thing\n"),
            ],
        );
        let backend = backend_at(&s.0).await;
        backend.run_round().await;
        let analysis = backend.test_analysis().await.expect("round");

        for (rel, label) in [
            ("src/thing.bynk", "primary"),
            ("tests/thing.bynk", "secondary"),
        ] {
            let abs = s.0.join(rel);
            let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
            let resolved = Backend::uri_to_rel(&analysis, &uri)
                .unwrap_or_else(|| panic!("{label} root URI must resolve"));
            assert_eq!(
                resolved.to_string_lossy().replace('\\', "/"),
                rel,
                "a {label}-tree URI must name its own analysed file",
            );
            assert!(
                analysis.snapshots.contains_key(&resolved),
                "…and that file must be in the round",
            );
        }
    }

    /// `exclude` reaches the server, not just the compiler. `project.rs` used to
    /// parse it and throw it away — its own comment said the analyse walk "does
    /// not yet prune by `exclude`".
    #[tokio::test]
    async fn an_excluded_tree_is_not_analysed() {
        let s = scratch_project(
            "excl",
            &[
                (
                    "bynk.toml",
                    "[project]\nname = \"excl\"\n\n[paths]\ninclude = [\".\"]\nexclude = [\"generated\"]\n",
                ),
                ("a.bynk", "context a\n"),
                ("generated/gen.bynk", "context gen\n"),
            ],
        );
        let backend = backend_at(&s.0).await;
        backend.run_round().await;
        let analysis = backend.test_analysis().await.expect("round");
        let keys: Vec<String> = analysis
            .snapshots
            .keys()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .collect();
        assert_eq!(keys, vec!["a.bynk"], "excluded trees stay out of the round");
    }

    /// CI repro (#653): the VS Code extension's fixture workspace — a legacy
    /// `[paths] src`/`tests` manifest (keys ADR 0147 retired, so
    /// `read_project_paths` ignores them → `conventional()` → `["src"]`) with a
    /// dotted commons in `src/`. Drives the real `references` handler.
    #[tokio::test]
    async fn references_resolve_in_the_vscode_fixture_layout() {
        let s = scratch_project(
            "vsc",
            &[
                (
                    "bynk.toml",
                    "[project]\nname = \"fixture\"\nversion = \"0.1.0\"\n\n[paths]\nsrc = \"src\"\ntests = \"tests\"\n",
                ),
                (
                    "src/text.bynk",
                    "commons fixture.text\n\nfn shout(s: String) -> String {\n  s\n}\n\nfn greet(name: String) -> String {\n  \"Hi, \\(shout(name))!\"\n}\n",
                ),
            ],
        );
        // Root exactly as `initialize` does: resolve from the workspace folder.
        let (root, config) = Backend::resolve_root(&s.0).expect("bynk.toml is present");
        assert_eq!(root, s.0, "the manifest's directory is the project root");

        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
        let backend = service.inner().clone();
        {
            let mut st = backend.state.write().await;
            // Key by the canonical root, so the entry matches `references`'
            // URI-based routing (`resolve_root` canonicalises).
            let canonical = root.canonicalize().unwrap_or_else(|_| root.clone());
            st.projects.insert(
                canonical,
                ProjectState {
                    config,
                    ..Default::default()
                },
            );
        }
        backend.run_round().await;

        let analysis = backend.test_analysis().await.expect("a round committed");
        let keys: Vec<String> = analysis
            .snapshots
            .keys()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .collect();
        assert_eq!(keys, vec!["src/text.bynk"], "the fixture file is analysed");

        // The URI the editor sends, mapped through the round's identity.
        let abs = s.0.join("src/text.bynk");
        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
        let rel = Backend::uri_to_rel(&analysis, &uri).expect("URI resolves into the round");
        assert_eq!(rel, PathBuf::from("src/text.bynk"));

        // `shout`'s declaration site: line 2 (0-based), at `fn shout`.
        let text = analysis.snapshots.get(&rel).expect("snapshot present");
        let decl = text.find("shout").expect("`shout` in source");
        let pos = crate::position::offset_to_position(text, decl);

        let refs = backend
            .references(ReferenceParams {
                text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: uri.clone() },
                    position: pos,
                },
                work_done_progress_params: Default::default(),
                partial_result_params: Default::default(),
                context: ReferenceContext {
                    include_declaration: true,
                },
            })
            .await
            .expect("references must not error");
        let found = refs.unwrap_or_default();
        assert!(
            !found.is_empty(),
            "`shout` is referenced by `greet` — references must resolve; got none",
        );
    }

    // -- Slice B: the freshness contract, driven through a real Backend -------
    //
    // These are behaviour-over-time tests (§4.1): they edit a buffer and then
    // make a request, asserting the request answers against the *new* text.
    // The static tests above can't see this — the defect lives between the
    // edit and the request, which only a driven sequence exercises.

    /// Open `src/a.bynk`, round it, then edit and drive `did_change`. `uri`,
    /// the round-1 relative path, and the edited version are returned.
    async fn open_round_edit(
        backend: &Backend,
        root: &std::path::Path,
        v1_text: &str,
        v2_text: &str,
    ) -> (Url, PathBuf) {
        let abs = root.join("src/a.bynk");
        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();

        backend
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri.clone(),
                    language_id: "bynk".into(),
                    version: 1,
                    text: v1_text.to_string(),
                },
            })
            .await;
        backend.run_round().await;

        // The round exists and is version 1.
        let a1 = backend.test_analysis().await.expect("round 1");
        let rel = Backend::uri_to_rel(&a1, &uri).expect("uri resolves");
        assert_eq!(a1.versions.get(&rel), Some(&1), "round 1 is version 1");

        // Edit: the buffer becomes `v2_text` at version 2. The debounce this
        // schedules is superseded by the request-driven refresh below.
        backend
            .did_change(DidChangeTextDocumentParams {
                text_document: VersionedTextDocumentIdentifier {
                    uri: uri.clone(),
                    version: 2,
                },
                content_changes: vec![TextDocumentContentChangeEvent {
                    range: None,
                    range_length: None,
                    text: v2_text.to_string(),
                }],
            })
            .await;
        (uri, rel)
    }

    /// The headline. After an edit that inserts a line above a symbol, a
    /// position request at the symbol's *new* location resolves to the symbol —
    /// because the gate refreshes to the edited buffer first. Under the old
    /// behaviour the new position was resolved against the round-1 snapshot,
    /// landing on the wrong text.
    #[tokio::test]
    async fn a_position_after_an_edit_resolves_against_the_new_text() {
        let v1 = "commons q.a\n\nfn target(x: Int) -> Int {\n  x\n}\n";
        // Prepend a blank line: `target` moves from line 2 to line 3.
        let v2 = format!("\n{v1}");
        let s = scratch_project(
            "fresh_hd",
            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
        );
        let backend = backend_at(&s.0).await;
        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;

        // The gate refreshes to the edited version and text.
        let a = backend.analysis_for(&uri).await.expect("current analysis");
        assert_eq!(a.versions.get(&rel), Some(&2), "gate refreshed to the edit");
        assert_eq!(a.snapshots.get(&rel).map(String::as_str), Some(v2.as_str()));

        // `target`'s new position resolves to `target` in the refreshed snapshot.
        let off_v2 = v2.find("target").unwrap();
        let new_pos = crate::position::offset_to_position(&v2, off_v2);
        let (a2, rel2, off) = backend
            .index_position(&uri, new_pos)
            .await
            .expect("position resolves");
        assert!(
            a2.snapshots.get(&rel2).unwrap()[off..].starts_with("target"),
            "the new position must land on `target` in the current snapshot — \
             the whole point of refreshing",
        );
    }

    /// The gate never returns a round whose snapshot for the file predates the
    /// buffer. A cached round at version 1 with the buffer at version 2 must be
    /// refreshed, not served.
    #[tokio::test]
    async fn a_stale_round_is_never_served() {
        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
        let v2 = format!("{v1}\nfn g(y: Int) -> Int {{\n  y\n}}\n");
        let s = scratch_project(
            "fresh_stale",
            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
        );
        let backend = backend_at(&s.0).await;
        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;

        // Precondition: the *cached* round is still version 1 (no refresh yet).
        let cached = backend.test_analysis().await.unwrap();
        assert_eq!(cached.versions.get(&rel), Some(&1), "cached round is stale");

        // The gate must not hand back that stale round.
        let a = backend.analysis_for(&uri).await.unwrap();
        assert_eq!(
            a.versions.get(&rel),
            Some(&2),
            "analysis_for must refresh past a stale cached round, never serve it",
        );
    }

    /// #733: `committed_analysis` is the non-refreshing counterpart of
    /// `analysis_for`. Where the strict gate refreshes past a stale round (the
    /// test above), this one **serves the committed round as-is** — even with the
    /// buffer a version ahead — and never triggers a refresh. That is what lets a
    /// decoration request answer from the committed round while the user types,
    /// instead of forcing a whole-project round on every keystroke.
    #[tokio::test]
    async fn committed_analysis_serves_the_stale_round_without_refreshing() {
        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
        let v2 = format!("{v1}\nfn g(y: Int) -> Int {{\n  y\n}}\n");
        let s = scratch_project(
            "fresh_committed",
            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
        );
        let backend = backend_at(&s.0).await;
        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;

        // Precondition: the cached round is still version 1 (buffer is at 2).
        assert_eq!(
            backend.test_analysis().await.unwrap().versions.get(&rel),
            Some(&1),
            "cached round is stale",
        );

        // The non-refreshing gate hands back that stale round unchanged...
        let a = backend
            .committed_analysis(&uri)
            .await
            .expect("committed round");
        assert_eq!(
            a.versions.get(&rel),
            Some(&1),
            "committed_analysis serves the committed round, stale and all",
        );
        // ...and left the cached round untouched (no refresh was triggered).
        assert_eq!(
            backend.test_analysis().await.unwrap().versions.get(&rel),
            Some(&1),
            "committed_analysis must not trigger a refresh",
        );
    }

    /// DECISION B: concurrent requests after one edit coalesce onto a single
    /// round, not one each. The refresh lock serialises them; the second finds
    /// the first's round already current.
    #[tokio::test]
    async fn concurrent_requests_after_one_edit_share_one_round() {
        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
        let v2 = format!("\n{v1}");
        let s = scratch_project(
            "fresh_coal",
            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
        );
        let backend = backend_at(&s.0).await;
        let (uri, _rel) = open_round_edit(&backend, &s.0, v1, &v2).await;

        let started_before = backend.test_round_started().await;

        // Fire several gate calls concurrently.
        let calls = (0..5).map(|_| {
            let b = backend.clone();
            let u = uri.clone();
            tokio::spawn(async move { b.analysis_for(&u).await.is_some() })
        });
        for c in calls {
            assert!(
                c.await.unwrap(),
                "each concurrent request must get an analysis"
            );
        }

        let started_after = backend.test_round_started().await;
        assert_eq!(
            started_after - started_before,
            1,
            "five concurrent requests after one edit must share ONE round, not run five",
        );
    }

    /// DECISION D: a file outside every `include` root cannot be answered at the
    /// client's version — the gate declines rather than serving something.
    #[tokio::test]
    async fn a_file_outside_the_project_is_declined() {
        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
        let s = scratch_project(
            "fresh_out",
            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
        );
        let backend = backend_at(&s.0).await;
        // Round the project so a cached analysis exists.
        backend.run_round().await;

        // A URI for a file the project does not contain, opened as a buffer.
        let outside = s.0.join("elsewhere.bynk");
        std::fs::write(&outside, v1).unwrap();
        let uri = Url::from_file_path(outside.canonicalize().unwrap()).unwrap();
        backend
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri.clone(),
                    language_id: "bynk".into(),
                    version: 1,
                    text: v1.to_string(),
                },
            })
            .await;

        assert!(
            backend.analysis_for(&uri).await.is_none(),
            "a file outside the include roots is never a snapshot key — decline, \
             don't serve a round that doesn't cover it",
        );
    }

    /// Review of #666: rename emits versioned edits across every file that
    /// references the symbol, so it must refresh **all** open buffers, not just
    /// the cursor's. Edit a non-cursor file that references the symbol, then
    /// rename from the (unedited) definition file: the edit for the dirty file
    /// must carry its *current* version, or the client rejects the whole rename.
    /// Under the per-URI gate the cursor's file was current, so no refresh ran
    /// and the dirty file kept its stale version.
    #[tokio::test]
    async fn a_multi_file_rename_stamps_a_dirty_non_cursor_file_at_its_current_version() {
        let util = "commons demo.util\n\ntype Money = Int where Positive\n";
        let thing = "commons demo.thing\n\nuses demo.util\n\nfn f(m: Money) -> Money {\n  m\n}\n";
        let s = scratch_project(
            "rename_multi",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                ("src/demo/util.bynk", util),
                ("src/demo/thing.bynk", thing),
            ],
        );
        let backend = backend_at(&s.0).await;
        let uri = |rel: &str| {
            let abs = s.0.join(rel);
            Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap()
        };
        let util_uri = uri("src/demo/util.bynk");
        let thing_uri = uri("src/demo/thing.bynk");

        for (u, text) in [(&util_uri, util), (&thing_uri, thing)] {
            backend
                .did_open(DidOpenTextDocumentParams {
                    text_document: TextDocumentItem {
                        uri: u.clone(),
                        language_id: "bynk".into(),
                        version: 1,
                        text: text.to_string(),
                    },
                })
                .await;
        }
        backend.run_round().await;

        // Edit the NON-cursor file (`thing`) to version 2 — a blank line above,
        // so `Money`'s references shift but still resolve.
        let thing_v2 = format!("\n{thing}");
        backend
            .did_change(DidChangeTextDocumentParams {
                text_document: VersionedTextDocumentIdentifier {
                    uri: thing_uri.clone(),
                    version: 2,
                },
                content_changes: vec![TextDocumentContentChangeEvent {
                    range: None,
                    range_length: None,
                    text: thing_v2.clone(),
                }],
            })
            .await;

        // Rename `Money` from its definition in `util` (untouched, still v1).
        let money_off = util.find("Money").unwrap();
        let pos = crate::position::offset_to_position(util, money_off);
        let edit = backend
            .rename(RenameParams {
                text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier {
                        uri: util_uri.clone(),
                    },
                    position: pos,
                },
                new_name: "Amount".into(),
                work_done_progress_params: Default::default(),
            })
            .await
            .expect("rename must not error")
            .expect("rename must produce edits");

        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
            panic!("expected document-change edits");
        };
        let thing_edit = edits
            .iter()
            .find(|e| e.text_document.uri == thing_uri)
            .expect("the rename must edit `thing`, which references the symbol");
        assert_eq!(
            thing_edit.text_document.version,
            Some(2),
            "the dirty non-cursor file's edit must carry its current version (2), \
             not the stale round's (1) — else the client rejects the whole rename",
        );
    }

    /// #302: renaming a unit's file rewrites its own declaration header
    /// **and** every other file's `uses`/`consumes` reference — over a split
    /// `src`/`tests` project, exercising the project-relative (`src/`-prefixed)
    /// path the `src`/`tests` split leaves on every identity path.
    #[tokio::test]
    async fn will_rename_files_updates_the_declaration_and_every_reference() {
        let charge = "commons billing.charge\n\ntype ChargeId = Int where Positive\n";
        let main = "context app.main\n\nuses billing.charge\n";
        let s = scratch_project(
            "will_rename_basic",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                ("src/billing/charge.bynk", charge),
                ("src/app/main.bynk", main),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
        let old_uri = uri("src/billing/charge.bynk");
        let new_uri = uri("src/billing/pay.bynk");
        let main_uri = uri("src/app/main.bynk");

        backend.run_round().await;

        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: old_uri.to_string(),
                    new_uri: new_uri.to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error")
            .expect("must produce edits");

        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
            panic!("expected document-change edits");
        };

        let own = edits
            .iter()
            .find(|e| e.text_document.uri == old_uri)
            .expect("the moved file's own declaration must be rewritten");
        assert_eq!(own.edits.len(), 1);
        let OneOf::Left(own_edit) = &own.edits[0] else {
            panic!("expected a plain TextEdit");
        };
        assert_eq!(own_edit.new_text, "billing.pay");

        let referencer = edits
            .iter()
            .find(|e| e.text_document.uri == main_uri)
            .expect("the referencing file must be rewritten");
        assert_eq!(referencer.edits.len(), 1);
        let OneOf::Left(ref_edit) = &referencer.edits[0] else {
            panic!("expected a plain TextEdit");
        };
        assert_eq!(ref_edit.new_text, "billing.pay");
    }

    /// #302: renaming one member file within a multi-file unit's directory
    /// doesn't change the unit's qualified name (it's the directory, not the
    /// filename) — no edits are needed.
    #[tokio::test]
    async fn will_rename_files_is_a_noop_for_a_multi_file_unit_member() {
        let s = scratch_project(
            "will_rename_multi_file_noop",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                (
                    "src/billing/charge/one.bynk",
                    "context billing.charge\n\ntype ChargeId = Int where Positive\n",
                ),
                (
                    "src/billing/charge/two.bynk",
                    "context billing.charge\n\ntype PaymentId = Int where Positive\n",
                ),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();

        backend.run_round().await;

        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: uri("src/billing/charge/one.bynk").to_string(),
                    new_uri: uri("src/billing/charge/renamed.bynk").to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error");
        assert!(
            edit.is_none(),
            "renaming a member file within the same directory must not edit anything"
        );
    }

    /// #302: a `suite` file has no addressable name of its own
    /// (`SourceUnit::name()` is its *target*'s name) — renaming it produces
    /// no edits.
    #[tokio::test]
    async fn will_rename_files_is_a_noop_for_a_suite() {
        let s = scratch_project(
            "will_rename_suite_noop",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                (
                    "src/billing/charge.bynk",
                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
                ),
                ("tests/billing_charge.bynk", "suite billing.charge\n"),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();

        backend.run_round().await;

        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: uri("tests/billing_charge.bynk").to_string(),
                    new_uri: uri("tests/billing_charge_renamed.bynk").to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error");
        assert!(edit.is_none(), "a suite rename must produce no edits");
    }

    /// #302 review: a `suite`'s own `target` is a *reference* too
    /// (`unit_reference_spans`' suite branch) — renaming the unit a suite
    /// tests must rewrite the suite's `suite <target>` header, not just
    /// `uses`/`consumes` clauses in ordinary units.
    #[tokio::test]
    async fn will_rename_files_updates_a_suite_s_target_reference() {
        let s = scratch_project(
            "will_rename_suite_target",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                (
                    "src/billing/charge.bynk",
                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
                ),
                ("tests/billing_charge.bynk", "suite billing.charge\n"),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
        let suite_uri = uri("tests/billing_charge.bynk");

        backend.run_round().await;

        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: uri("src/billing/charge.bynk").to_string(),
                    new_uri: uri("src/billing/pay.bynk").to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error")
            .expect("must produce edits");

        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
            panic!("expected document-change edits");
        };
        let suite_edit = edits
            .iter()
            .find(|e| e.text_document.uri == suite_uri)
            .expect("the suite's own `suite <target>` header must be rewritten");
        assert_eq!(suite_edit.edits.len(), 1);
        let OneOf::Left(e) = &suite_edit.edits[0] else {
            panic!("expected a plain TextEdit");
        };
        assert_eq!(e.new_text, "billing.pay");
    }

    /// #302 review: renaming into a path that implies a name some other file
    /// already declares must not hand back an edit that would create a
    /// duplicate-name project — a lightweight `unit_sources` check, not
    /// `rename`'s full re-analysis.
    #[tokio::test]
    async fn will_rename_files_refuses_a_rename_that_collides_with_an_existing_unit() {
        let s = scratch_project(
            "will_rename_collision",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                (
                    "src/billing/charge.bynk",
                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
                ),
                (
                    "src/billing/pay.bynk",
                    "commons billing.pay\n\ntype PaymentId = Int where Positive\n",
                ),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();

        backend.run_round().await;

        // Renaming `charge.bynk` to `pay.bynk` would imply `billing.pay` —
        // already declared by the sibling file.
        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: uri("src/billing/charge.bynk").to_string(),
                    new_uri: uri("src/billing/pay.bynk").to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error");
        assert!(
            edit.is_none(),
            "a rename that collides with an existing unit name must produce no edits"
        );
    }

    /// #302 review: `willRenameFiles`' `new_uri` names a file that doesn't
    /// exist yet, so `uri_to_rel`'s `canonicalize` fails and previously fell
    /// back to the client's raw, non-canonical path — which mismatches
    /// `project_root` (always canonical) whenever the workspace root sits
    /// behind a symlink, and the handler silently produced no edit.
    /// `uri_to_rel_for_new_path` canonicalizes the parent directory (which
    /// does exist) instead, so this must still produce edits.
    #[cfg(unix)]
    #[tokio::test]
    async fn will_rename_files_tolerates_a_symlinked_project_root() {
        let real = scratch_project(
            "will_rename_symlink_real",
            &[
                ("bynk.toml", "[project]\nname=\"demo\"\n"),
                (
                    "src/billing/charge.bynk",
                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
                ),
            ],
        );
        let alias = std::env::temp_dir().join(format!(
            "bynk_lsp_sliceA_will_rename_symlink_alias_{}_{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_file(&alias);
        std::os::unix::fs::symlink(&real.0, &alias).expect("symlink the scratch root");

        let backend = backend_at(&alias).await;
        // Built through the symlink, deliberately uncanonicalized — the path
        // shape a client actually sends (it opened the workspace at `alias`,
        // not at whatever `alias` resolves to).
        let uri = |rel: &str| Url::from_file_path(alias.join(rel)).unwrap();
        let old_uri = uri("src/billing/charge.bynk");
        let new_uri = uri("src/billing/pay.bynk"); // does not exist on disk

        backend.run_round().await;

        let edit = backend
            .will_rename_files(RenameFilesParams {
                files: vec![FileRename {
                    old_uri: old_uri.to_string(),
                    new_uri: new_uri.to_string(),
                }],
            })
            .await
            .expect("will_rename_files must not error")
            .expect("must produce edits despite the symlinked root");

        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
            panic!("expected document-change edits");
        };
        assert_eq!(
            edits.len(),
            1,
            "only the moved file's own header changes here"
        );
        let OneOf::Left(e) = &edits[0].edits[0] else {
            panic!("expected a plain TextEdit");
        };
        assert_eq!(e.new_text, "billing.pay");

        let _ = std::fs::remove_file(&alias);
    }

    /// #485: a rootless multi-file-commons file (a `src/` tree with no
    /// `bynk.toml`, the layout the compiler fixtures use) resolves its
    /// implicit source root — the nearest ancestor `src/` — so project-mode
    /// analysis kicks in instead of sibling-blind single-file `diagnose`.
    #[test]
    fn find_source_root_walks_up_to_the_nearest_src() {
        let ws = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .expect("workspace root");
        let make = ws.join(
            "bynkc/tests/fixtures/positive/\
             252_multi_file_commons_dotted_test/src/shipping/rates/make.bynk",
        );
        assert!(make.is_file(), "fixture present: {}", make.display());

        let src = Backend::find_source_root(&make).expect("an ancestor src/");
        assert!(
            src.ends_with("252_multi_file_commons_dotted_test/src"),
            "nearest ancestor src, got {}",
            src.display()
        );

        // No `bynk.toml` on the path, so resolution falls back to the implicit
        // src tree, and the project root is `src`'s parent.
        //
        // Slice A: the old invariant here was `root.join(config.src_dir) == src`
        // — the analysis root re-derived by reducing the manifest to one
        // directory. That reduction is gone: the round is rooted at the project
        // and `bynk_ide::AnalysisRoots::Project` resolves the trees from the
        // manifest (here, absent → `ProjectPaths::conventional`, which picks up
        // exactly this `src/`). So what must hold is that the root is `src`'s
        // parent, and that conventional discovery finds this file from it.
        let (root, _config) = Backend::resolve_root(&make).expect("implicit project");
        assert_eq!(root, src.parent().expect("src has a parent"));

        let found = bynk_ide::discover_files(&bynk_ide::AnalysisRoots::Project(root.clone()));
        let make_canon = make.canonicalize().unwrap_or(make.clone());
        assert!(
            found
                .iter()
                .any(|p| p.canonicalize().unwrap_or_else(|_| p.clone()) == make_canon),
            "the compiler's own discovery must reach {} from the project root {}; got {found:?}",
            make.display(),
            root.display(),
        );
    }

    /// A file with no `bynk.toml` and no ancestor `src/` stays in single-file
    /// mode — resolution returns `None`, so the caller keeps the per-buffer
    /// `diagnose` path.
    #[test]
    fn resolve_root_is_none_without_toml_or_src() {
        // The crate manifest sits under `bynk-lsp/`, not inside any `src/`.
        let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        assert!(p.is_file());
        assert!(Backend::find_source_root(&p).is_none());
        assert!(Backend::resolve_root(&p).is_none());
    }

    // v0.124 (slice 3): the `<expr> is <cursor>` scrutinee-offset detection that
    // feeds `is`-pattern completion.
    #[test]
    fn is_scrutinee_offset_locates_the_scrutinee() {
        let text = "  order.status is Pen";
        let off = is_scrutinee_offset(text, text.len()).expect("at an is-position");
        // Lands on the last char of `order.status` (the `s` of `status`).
        assert_eq!(&text[off..off + 1], "s");
        assert!(off < text.find(" is ").unwrap());
        // No trailing partial, cursor right after `is `.
        let text2 = "  x is ";
        let off2 = is_scrutinee_offset(text2, text2.len()).expect("at an is-position");
        assert_eq!(&text2[off2..off2 + 1], "x");
        // `basis` is not a standalone `is`.
        assert!(is_scrutinee_offset("  basis ", "  basis ".len()).is_none());
        // Not an is-position at all.
        assert!(is_scrutinee_offset("  let x = ", "  let x = ".len()).is_none());
    }

    // v0.128: the `match <expr> { <arm-start>` scrutinee-offset detection that
    // feeds match-arm variant completion.
    #[test]
    fn match_scrutinee_offset_locates_the_scrutinee() {
        // First arm, cursor right after the opening brace.
        let t = "match order.status {\n  ";
        let off = match_scrutinee_offset(t, t.len()).expect("at an arm-start");
        assert_eq!(&t[off..off + 1], "s"); // last char of `order.status`
        assert!(off < t.find(" {").unwrap());

        // First arm with a partial pattern typed.
        let t = "match color { Re";
        let off = match_scrutinee_offset(t, t.len()).expect("at an arm-start");
        assert_eq!(&t[off..off + 1], "r"); // last char of `color`

        // A later arm after a top-level comma, mid-partial.
        let t = "match c {\n  Red => 1,\n  Gr";
        let off = match_scrutinee_offset(t, t.len()).expect("at a later arm-start");
        assert_eq!(&t[off..off + 1], "c");

        // A top-level comma inside a preceding arm body does not confuse the
        // header (the nested call's comma is at depth > 0).
        let t = "match c {\n  Red => f(a, b),\n  ";
        assert!(match_scrutinee_offset(t, t.len()).is_some());

        // Inside an arm *body* (after `=>`) — not a pattern position.
        assert!(
            match_scrutinee_offset("match c {\n  Red => ", "match c {\n  Red => ".len()).is_none()
        );

        // A non-`match` block offers nothing.
        assert!(match_scrutinee_offset("fn f() {\n  ", "fn f() {\n  ".len()).is_none());

        // A nested constructor position (`Ok(<cursor>`) is not an arm-start.
        assert!(match_scrutinee_offset("match c {\n  Ok(", "match c {\n  Ok(".len()).is_none());

        // No open brace / no scrutinee → nothing.
        assert!(match_scrutinee_offset("match c ", "match c ".len()).is_none());
        assert!(match_scrutinee_offset("match {\n  ", "match {\n  ".len()).is_none());
    }

    // v0.145 (ADR 0169): the `match <expr> { … Variant(<partial>` nested-pattern
    // detection that feeds payload-variant completion — the position
    // `match_scrutinee_offset` deliberately bails on.
    #[test]
    fn nested_pattern_offset_locates_the_scrutinee_and_variant() {
        // Cursor right inside a variant's payload parens.
        let t = "match res {\n  Some(";
        let (off, variant) = nested_pattern_offset(t, t.len()).expect("inside a nested pattern");
        assert_eq!(&t[off..off + 1], "s"); // last char of `res`
        assert_eq!(variant, "Some");

        // With a partial nested pattern typed, and a qualifier.
        let t = "match res {\n  Ok(Po";
        let (off, variant) = nested_pattern_offset(t, t.len()).expect("mid partial");
        assert_eq!(&t[off..off + 1], "s");
        assert_eq!(variant, "Ok");

        // A later arm after a top-level comma.
        let t = "match r {\n  Ok(n) => n,\n  Err(";
        let (off, variant) = nested_pattern_offset(t, t.len()).expect("later arm");
        assert_eq!(&t[off..off + 1], "r");
        assert_eq!(variant, "Err");

        // A lowercase-led token before `(` is a binding/call, not a variant
        // constructor — no nested completion (there is no inner type to open).
        assert!(nested_pattern_offset("match r {\n  ok(", "match r {\n  ok(".len()).is_none());

        // An arm-start (no open paren) is the flat position, not a nested one.
        assert!(nested_pattern_offset("match c {\n  ", "match c {\n  ".len()).is_none());
        assert!(nested_pattern_offset("match c {\n  Ok", "match c {\n  Ok".len()).is_none());

        // Inside an arm body (after `=>`) is not a pattern position.
        let t = "match c {\n  Ok(n) => g(";
        assert!(nested_pattern_offset(t, t.len()).is_none());

        // A non-`match` block offers nothing.
        assert!(nested_pattern_offset("fn f() {\n  h(", "fn f() {\n  h(".len()).is_none());
    }

    /// A watched-file change on `bynk.toml` is recognised (so the config can be
    /// reloaded live), while a sibling `.bynk` file or a merely `…bynk.toml`-
    /// suffixed name is not — the name-component match, not a path suffix.
    #[test]
    fn is_bynk_toml_matches_only_the_manifest() {
        // Build URIs from a host-absolute base so `from_file_path` succeeds on
        // Windows too (a Unix-style `/proj` path is not absolute there — no
        // drive letter — and would fail to convert). Mirrors the sibling
        // `find_source_root` test's `CARGO_MANIFEST_DIR` base.
        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let toml = Url::from_file_path(base.join("bynk.toml")).expect("abs path");
        assert!(is_bynk_toml(&toml));
        let nested = Url::from_file_path(base.join("sub").join("bynk.toml")).expect("abs path");
        assert!(is_bynk_toml(&nested));

        // A source file is not the manifest.
        let src = Url::from_file_path(base.join("src").join("main.bynk")).expect("abs path");
        assert!(!is_bynk_toml(&src));
        // A file whose name merely *ends with* `bynk.toml` must not fire.
        let decoy = Url::from_file_path(base.join("notbynk.toml")).expect("abs path");
        assert!(!is_bynk_toml(&decoy));
        // A non-file URI never matches.
        let remote = Url::parse("https://example.com/bynk.toml").expect("url");
        assert!(!is_bynk_toml(&remote));
    }

    /// The v0.26 capability advertisements — the "trivial unit check" the
    /// proposal scopes in place of a transport round-trip.
    #[test]
    fn advertises_code_actions_and_the_index_riders() {
        let caps = server_capabilities();
        let Some(CodeActionProviderCapability::Options(opts)) = caps.code_action_provider else {
            panic!("codeActionProvider not advertised with options");
        };
        assert_eq!(
            opts.code_action_kinds,
            Some(vec![
                CodeActionKind::QUICKFIX,
                CodeActionKind::REFACTOR,
                CodeActionKind::REFACTOR_EXTRACT,
            ])
        );
        assert!(matches!(
            caps.workspace_symbol_provider,
            Some(OneOf::Left(true))
        ));
        assert!(matches!(
            caps.document_highlight_provider,
            Some(OneOf::Left(true))
        ));
    }

    /// The v0.27 capability advertisement — the "trivial unit check" the
    /// proposal scopes in place of a transport round-trip.
    #[test]
    fn advertises_save_notifications() {
        // `diagnostics_mode = "on_save"` is driven by `didSave`; the sync
        // options must opt in explicitly or clients may not send it (#513).
        let caps = server_capabilities();
        let Some(TextDocumentSyncCapability::Options(opts)) = caps.text_document_sync else {
            panic!("textDocumentSync not advertised with options");
        };
        assert_eq!(opts.change, Some(TextDocumentSyncKind::FULL));
        assert!(matches!(
            opts.save,
            Some(TextDocumentSyncSaveOptions::Supported(true))
        ));
    }

    #[test]
    fn advertises_inlay_hints() {
        let caps = server_capabilities();
        assert!(matches!(caps.inlay_hint_provider, Some(OneOf::Left(true))));
    }

    /// Slice 6: go-to-type-definition (value → its type's declaration).
    #[test]
    fn advertises_type_definition() {
        let caps = server_capabilities();
        assert!(matches!(
            caps.type_definition_provider,
            Some(TypeDefinitionProviderCapability::Simple(true))
        ));
    }

    /// Slice 6b: `uses`/`consumes` document links.
    #[test]
    fn advertises_document_links() {
        let caps = server_capabilities();
        assert!(caps.document_link_provider.is_some());
    }

    /// #302: `willRenameFiles` over `.bynk` files, not folders.
    #[test]
    fn advertises_will_rename_files() {
        let caps = server_capabilities();
        let file_ops = caps
            .workspace
            .as_ref()
            .and_then(|w| w.file_operations.as_ref())
            .expect("workspace.fileOperations advertised");
        let will_rename = file_ops
            .will_rename
            .as_ref()
            .expect("willRename registered");
        let filter = &will_rename.filters[0];
        assert_eq!(filter.pattern.glob, "**/*.bynk");
        assert_eq!(filter.pattern.matches, Some(FileOperationPatternKind::File));
    }

    /// Slice 5: completion advertises `.` triggers and lazy doc resolution.
    #[test]
    fn advertises_completion_with_dot_trigger_and_resolve() {
        let caps = server_capabilities();
        let opts = caps.completion_provider.expect("completion advertised");
        assert_eq!(opts.resolve_provider, Some(true), "resolve_provider");
        assert!(
            opts.trigger_characters
                .as_deref()
                .is_some_and(|t| t.iter().any(|c| c == ".")),
            "`.` trigger char"
        );
    }

    /// The v0.28 capability advertisement: full + range with the frozen
    /// legend (the legend's content is pinned in `index_queries`).
    #[test]
    fn advertises_semantic_tokens() {
        let caps = server_capabilities();
        let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(opts)) =
            caps.semantic_tokens_provider
        else {
            panic!("semanticTokensProvider not advertised with options");
        };
        assert_eq!(opts.full, Some(SemanticTokensFullOptions::Bool(true)));
        assert_eq!(opts.range, Some(true));
        assert_eq!(opts.legend, crate::index_queries::semantic_tokens_legend());
    }

    // ---- Slice D: per-workspace state (Q4) ----

    /// A backend with **no** seeded project — the real lazy-discovery flow,
    /// where `did_open` and requests create entries by routing (`resolve_root`).
    async fn bare_backend() -> Backend {
        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
        service.inner().clone()
    }

    fn file_uri(root: &std::path::Path, rel: &str) -> Url {
        let abs = root.join(rel);
        Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap()
    }

    async fn set_folders(backend: &Backend, roots: &[&std::path::Path]) {
        backend.state.write().await.folders = roots
            .iter()
            .map(|r| r.canonicalize().unwrap_or_else(|_| r.to_path_buf()))
            .collect();
    }

    async fn open(backend: &Backend, uri: &Url, text: &str) {
        backend
            .did_open(DidOpenTextDocumentParams {
                text_document: TextDocumentItem {
                    uri: uri.clone(),
                    language_id: "bynk".into(),
                    version: 1,
                    text: text.to_string(),
                },
            })
            .await;
    }

    fn snapshot_keys(a: &Analysis) -> Vec<String> {
        let mut keys: Vec<String> = a
            .snapshots
            .keys()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .collect();
        keys.sort();
        keys
    }

    /// Two `bynk.toml` projects under **one** workspace folder are two projects
    /// (Q4: route by discovered root, not folder). Opening a file in each creates
    /// its own entry, and each analyses **only its own** tree — the overlay
    /// isolation guard, too: project A's round never sees project B's file.
    #[tokio::test]
    async fn two_projects_under_one_folder_are_two_projects() {
        let ax_src = "commons a.x\n\nfn ax(n: Int) -> Int {\n  n\n}\n";
        let by_src = "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n";
        let s = scratch_project(
            "d_two",
            &[
                ("a/bynk.toml", "[project]\nname=\"a\"\n"),
                ("a/src/x.bynk", ax_src),
                ("b/bynk.toml", "[project]\nname=\"b\"\n"),
                ("b/src/y.bynk", by_src),
            ],
        );
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        let ax = file_uri(&s.0, "a/src/x.bynk");
        let by = file_uri(&s.0, "b/src/y.bynk");
        open(&backend, &ax, ax_src).await;
        open(&backend, &by, by_src).await;

        assert_ne!(
            Backend::root_for_uri_uncached(&ax).unwrap(),
            Backend::root_for_uri_uncached(&by).unwrap(),
            "the two files resolve to different project roots",
        );
        assert_eq!(
            backend.state.read().await.projects.len(),
            2,
            "one entry per project, not one for the shared folder",
        );

        let a = backend.analysis_for(&ax).await.expect("A analysed");
        let b = backend.analysis_for(&by).await.expect("B analysed");
        assert_eq!(
            snapshot_keys(&a),
            vec!["src/x.bynk"],
            "A sees only A's file"
        );
        assert_eq!(
            snapshot_keys(&b),
            vec!["src/y.bynk"],
            "B sees only B's file"
        );
    }

    /// Q4 lifecycle: `did_change_workspace_folders` removing a folder with **no
    /// open buffer** prunes the idle project entry and clears nothing it must
    /// keep. Routing no longer resolves it because the seed is gone.
    #[tokio::test]
    async fn removing_a_folder_prunes_an_idle_project() {
        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
        let s = scratch_project(
            "d_prune",
            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
        );
        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, a).await;
        backend.analysis_for(&uri).await.expect("analysed");
        // Close the buffer, so nothing but the folder pins the project.
        backend
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
            })
            .await;
        assert_eq!(backend.state.read().await.projects.len(), 1);

        backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
                event: WorkspaceFoldersChangeEvent {
                    added: vec![],
                    removed: vec![WorkspaceFolder {
                        uri: Url::from_file_path(&folder).unwrap(),
                        name: "p".into(),
                    }],
                },
            })
            .await;
        assert!(
            backend.state.read().await.projects.is_empty(),
            "an idle project is pruned when its last covering folder is removed",
        );
    }

    /// Q4 lifecycle: a project that still holds an **open buffer** survives folder
    /// removal — routing needs it until the buffer closes.
    #[tokio::test]
    async fn removing_a_folder_retains_a_project_with_an_open_buffer() {
        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
        let s = scratch_project(
            "d_retain",
            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
        );
        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, a).await; // buffer stays open

        backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
                event: WorkspaceFoldersChangeEvent {
                    added: vec![],
                    removed: vec![WorkspaceFolder {
                        uri: Url::from_file_path(&folder).unwrap(),
                        name: "p".into(),
                    }],
                },
            })
            .await;
        assert_eq!(
            backend.state.read().await.projects.len(),
            1,
            "a project with an open buffer must survive folder removal",
        );
        assert!(
            backend.analysis_for(&uri).await.is_some(),
            "and it must still answer requests",
        );
    }

    /// Q4 §C: closing the **last** buffer of a project whose folder was already
    /// removed prunes it — the mirror of the folder path. Without it the project
    /// lingers forever with published diagnostics no folder or buffer justifies.
    #[tokio::test]
    async fn closing_the_last_buffer_of_a_folder_removed_project_prunes_it() {
        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
        let s = scratch_project(
            "d_close_prune",
            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
        );
        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, a).await;
        backend.analysis_for(&uri).await.expect("analysed");

        // Remove the folder while the buffer is open — retained (its buffer pins it).
        backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
                event: WorkspaceFoldersChangeEvent {
                    added: vec![],
                    removed: vec![WorkspaceFolder {
                        uri: Url::from_file_path(&folder).unwrap(),
                        name: "p".into(),
                    }],
                },
            })
            .await;
        assert_eq!(
            backend.state.read().await.projects.len(),
            1,
            "retained while its buffer is open",
        );

        // Close the last buffer — now fully orphaned (no folder, no buffer).
        backend
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
            })
            .await;
        assert!(
            backend.state.read().await.projects.is_empty(),
            "closing the last buffer of a folder-removed project must prune it",
        );
    }

    /// Q4: a rename spans **one** project — a stale buffer in another project must
    /// not block it (`analysis_covering_open_buffers` is per-project). Under a
    /// whole-server gate, B's dirty buffer would refuse A's rename.
    #[tokio::test]
    async fn a_rename_in_one_project_ignores_a_dirty_buffer_in_another() {
        let a_src = "commons a.x\n\ntype Money = Int where Positive\n\nfn charge(m: Money) -> Money {\n  m\n}\n";
        let b_src = "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n";
        let s = scratch_project(
            "d_rename_iso",
            &[
                ("a/bynk.toml", "[project]\nname=\"a\"\n"),
                ("a/src/x.bynk", a_src),
                ("b/bynk.toml", "[project]\nname=\"b\"\n"),
                ("b/src/y.bynk", b_src),
            ],
        );
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        let ax = file_uri(&s.0, "a/src/x.bynk");
        let by = file_uri(&s.0, "b/src/y.bynk");
        open(&backend, &ax, a_src).await;
        open(&backend, &by, b_src).await;
        backend.analysis_for(&ax).await.expect("A analysed");
        backend.analysis_for(&by).await.expect("B analysed");

        // Make B's buffer dirty (version 2, not yet re-analysed).
        backend
            .did_change(DidChangeTextDocumentParams {
                text_document: VersionedTextDocumentIdentifier {
                    uri: by.clone(),
                    version: 2,
                },
                content_changes: vec![TextDocumentContentChangeEvent {
                    range: None,
                    range_length: None,
                    text: format!("\n{b_src}"),
                }],
            })
            .await;

        // Rename `Money` in A — must succeed despite B being dirty.
        let off = a_src.find("Money").unwrap();
        let pos = crate::position::offset_to_position(a_src, off);
        let edit = backend
            .rename(RenameParams {
                text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: ax.clone() },
                    position: pos,
                },
                new_name: "Amount".into(),
                work_done_progress_params: Default::default(),
            })
            .await
            .expect("rename must not error");
        assert!(
            edit.is_some(),
            "a rename in project A must not be blocked by a dirty buffer in project B",
        );
    }

    // ---- Slice E: startup analysis & dynamic watchers ----

    /// `initialize` captures the client's `didChangeWatchedFiles` dynamic-
    /// registration support, which gates the server-side watcher registration.
    #[tokio::test]
    async fn initialize_captures_the_dynamic_watcher_capability() {
        let backend = bare_backend().await;
        let params = InitializeParams {
            capabilities: ClientCapabilities {
                workspace: Some(WorkspaceClientCapabilities {
                    did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
                        dynamic_registration: Some(true),
                        relative_pattern_support: None,
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            },
            ..Default::default()
        };
        backend.initialize(params).await.expect("initialize");
        assert!(
            backend.state.read().await.supports_dynamic_watchers,
            "the client's dynamic-registration support must be captured for `initialized`",
        );
    }

    /// #733: `initialize` captures each pull-based decoration's `refresh_support`
    /// independently — the flag gates whether a committed round nudges the client
    /// to re-pull that decoration. The three `and_then` chains are easy to
    /// mis-wire (a swapped field reads the wrong capability), so pin each: two
    /// advertised, one withheld, one whole family absent.
    #[tokio::test]
    async fn initialize_captures_each_decoration_refresh_capability() {
        let backend = bare_backend().await;
        let params = InitializeParams {
            capabilities: ClientCapabilities {
                workspace: Some(WorkspaceClientCapabilities {
                    // Semantic tokens: advertised.
                    semantic_tokens: Some(SemanticTokensWorkspaceClientCapabilities {
                        refresh_support: Some(true),
                    }),
                    // Inlay hints: explicitly withheld.
                    inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
                        refresh_support: Some(false),
                    }),
                    // Code lens: the whole family absent (no capability at all).
                    ..Default::default()
                }),
                ..Default::default()
            },
            ..Default::default()
        };
        backend.initialize(params).await.expect("initialize");
        let refresh = backend.state.read().await.supports_refresh;
        assert!(
            refresh.semantic_tokens,
            "semantic tokens: advertised → true"
        );
        assert!(!refresh.inlay_hints, "inlay hints: withheld → false");
        assert!(!refresh.code_lens, "code lens: absent → false");
    }

    /// The discovery walk finds every nested `bynk.toml` project under a folder
    /// (a monorepo), and skips the caches it must never descend.
    #[tokio::test]
    async fn discover_projects_under_finds_nested_projects_and_skips_caches() {
        let s = scratch_project(
            "e_discover",
            &[
                ("packages/a/bynk.toml", "[project]\nname=\"a\"\n"),
                ("packages/a/src/x.bynk", "commons a.x\n"),
                ("packages/b/bynk.toml", "[project]\nname=\"b\"\n"),
                ("packages/b/src/y.bynk", "commons b.y\n"),
                // A manifest under a skipped dir must NOT be discovered.
                ("node_modules/dep/bynk.toml", "[project]\nname=\"dep\"\n"),
            ],
        );
        let mut roots = Backend::discover_projects_under(&s.0);
        roots.sort();
        let names: Vec<String> = roots
            .iter()
            .map(|r| r.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            names,
            vec!["a", "b"],
            "both monorepo projects found, node_modules skipped; got {roots:?}",
        );
    }

    /// Startup analysis: `initialized` warms every project under the workspace
    /// folders — creating each entry so diagnostics/features are ready — **with
    /// no `did_open`**. This is spec §2.3's documented startup analysis.
    #[tokio::test]
    async fn initialized_warms_every_project_under_the_folders() {
        let s = scratch_project(
            "e_warm",
            &[
                ("packages/a/bynk.toml", "[project]\nname=\"a\"\n"),
                (
                    "packages/a/src/x.bynk",
                    "commons a.x\n\nfn ax(n: Int) -> Int {\n  n\n}\n",
                ),
                ("packages/b/bynk.toml", "[project]\nname=\"b\"\n"),
                (
                    "packages/b/src/y.bynk",
                    "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n",
                ),
            ],
        );
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;

        // No file opened — just the handshake completion.
        backend.initialized(InitializedParams {}).await;

        assert_eq!(
            backend.state.read().await.projects.len(),
            2,
            "both monorepo projects are warmed at `initialized`, before any open",
        );
        // And each is genuinely analysable without an open buffer.
        let ax = file_uri(&s.0, "packages/a/src/x.bynk");
        assert!(
            backend.analysis_for(&ax).await.is_some(),
            "a warmed project answers index requests with no `did_open`",
        );
    }

    /// The implicit-`src/` project (#485 — a `src/` tree with no `bynk.toml`) is
    /// warmed at startup too, not only lazily on first open. `resolve_root` finds
    /// only a `src/` *ancestor*, so the folder-is-the-root case needs the explicit
    /// check in `discover_projects_under`.
    #[tokio::test]
    async fn initialized_warms_an_implicit_src_project() {
        let s = scratch_project(
            "e_implicit",
            &[(
                "src/a.bynk",
                "commons demo.a\n\nfn f(n: Int) -> Int {\n  n\n}\n",
            )],
        );
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        backend.initialized(InitializedParams {}).await;
        assert_eq!(
            backend.state.read().await.projects.len(),
            1,
            "a rootless `src/` project is warmed at startup, not only on open",
        );
    }

    /// Review of #677: the discovery walk must not follow a symlink cycle into a
    /// stack overflow — a `loop -> .` in an ordinary directory. The visited-set
    /// (canonicalised dirs) bounds it.
    #[cfg(unix)]
    #[tokio::test]
    async fn discover_projects_under_survives_a_symlink_cycle() {
        let s = scratch_project(
            "e_cycle",
            &[
                ("bynk.toml", "[project]\nname=\"p\"\n"),
                ("src/a.bynk", "commons p.a\n"),
            ],
        );
        // A directory symlink pointing back at the folder — a cycle.
        std::os::unix::fs::symlink(&s.0, s.0.join("loop")).ok();
        let roots = Backend::discover_projects_under(&s.0); // must terminate
        let canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        assert!(
            roots.contains(&canon),
            "the project is found and the walk terminates despite the cycle",
        );
    }

    /// Review of #677: with the per-query `workspace/symbol` walk dropped, a
    /// `bynk.toml` **created** after startup is picked up via its watcher event
    /// — the watcher warms the new project.
    #[tokio::test]
    async fn a_created_manifest_warms_a_new_project() {
        let s = scratch_project("e_created", &[("src/a.bynk", "commons p.a\n")]);
        std::fs::write(s.0.join("bynk.toml"), "[project]\nname=\"p\"\n").unwrap();
        let root = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let backend = bare_backend().await;
        set_folders(&backend, &[&s.0]).await;
        assert!(
            backend.state.read().await.projects.is_empty(),
            "no entry before the watcher fires",
        );

        let toml_uri = Url::from_file_path(root.join("bynk.toml")).unwrap();
        backend
            .did_change_watched_files(DidChangeWatchedFilesParams {
                changes: vec![FileEvent {
                    uri: toml_uri,
                    typ: FileChangeType::CREATED,
                }],
            })
            .await;
        assert_eq!(
            backend.state.read().await.projects.len(),
            1,
            "a created bynk.toml warms its project via the watcher event",
        );
    }

    /// #682: a repeated route for the same URI is served from `root_cache`
    /// rather than re-walking the filesystem each time — a `None` route
    /// (single-file mode) is cached too, since it's just as stable an answer.
    #[tokio::test]
    async fn root_for_uri_populates_the_cache() {
        let s = scratch_project("g_cache_hit", &[("a.bynk", "commons demo.a\n")]);
        let uri = file_uri(&s.0, "a.bynk");
        let backend = bare_backend().await;

        assert!(
            backend.root_for_uri(&uri).await.is_none(),
            "no bynk.toml and no src/ ancestor — routes to no project",
        );
        assert_eq!(
            backend.state.read().await.root_cache.get(&uri),
            Some(&None),
            "the miss is cached too",
        );
    }

    /// #682 (DECISION C): a `bynk.toml` created after a URI was already routed
    /// (and cached) re-routes that URI once the watcher event invalidates the
    /// cache — a stale cached `None` must not survive the manifest's arrival.
    #[tokio::test]
    async fn a_created_manifest_invalidates_the_cached_route() {
        let s = scratch_project("g_cache_invalidate", &[("a.bynk", "commons p.a\n")]);
        let uri = file_uri(&s.0, "a.bynk");
        let backend = bare_backend().await;

        assert!(
            backend.root_for_uri(&uri).await.is_none(),
            "precondition: cached as routing to no project",
        );

        std::fs::write(s.0.join("bynk.toml"), "[project]\nname=\"p\"\n").unwrap();
        let root = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let toml_uri = Url::from_file_path(root.join("bynk.toml")).unwrap();
        backend
            .did_change_watched_files(DidChangeWatchedFilesParams {
                changes: vec![FileEvent {
                    uri: toml_uri,
                    typ: FileChangeType::CREATED,
                }],
            })
            .await;

        assert_eq!(
            backend.root_for_uri(&uri).await,
            Some(root),
            "re-routes to the new project now the stale cache entry is gone",
        );
    }

    /// #822: the guard `root_for_uri` checks before writing back a cache miss
    /// — an accidental `!=`-for-`==` inversion here would silently reopen the
    /// TOCTOU the generation counter exists to close, and the real race is too
    /// timing-dependent to exercise deterministically, so this pins the
    /// predicate directly.
    #[test]
    fn root_cache_write_is_current_rejects_a_generation_that_moved() {
        assert!(
            Backend::root_cache_write_is_current(3, 3),
            "no clear happened since the read — the write-back applies",
        );
        assert!(
            !Backend::root_cache_write_is_current(3, 4),
            "a clear bumped the generation since the read — the write-back must be dropped",
        );
    }

    /// #822: both `root_cache.clear()` sites must bump `root_cache_generation`
    /// alongside the clear — the guard only closes the TOCTOU if every
    /// invalidation does both. `did_change_watched_files`'s bump is covered
    /// indirectly by `a_created_manifest_invalidates_the_cached_route`; this
    /// covers `did_change_workspace_folders`'s directly, since a regression
    /// dropping just that one bump would reopen the race there specifically.
    #[tokio::test]
    async fn a_workspace_folder_change_bumps_the_root_cache_generation() {
        let s = scratch_project("g_race_folder", &[("bynk.toml", "[project]\nname=\"p\"\n")]);
        let backend = bare_backend().await;
        let before = backend.state.read().await.root_cache_generation;

        backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
                event: WorkspaceFoldersChangeEvent {
                    added: vec![WorkspaceFolder {
                        uri: Url::from_file_path(&s.0).unwrap(),
                        name: "p".into(),
                    }],
                    removed: vec![],
                },
            })
            .await;

        assert!(
            backend.state.read().await.root_cache_generation > before,
            "a workspace-folder change must bump the generation, not just clear the cache",
        );
    }

    /// A folder added at runtime is warmed the same way (the proactive scan
    /// slice D deferred to E), so its projects appear without an open.
    #[tokio::test]
    async fn an_added_folder_is_warmed() {
        let s = scratch_project(
            "e_added",
            &[
                ("bynk.toml", "[project]\nname=\"p\"\n"),
                (
                    "src/a.bynk",
                    "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n",
                ),
            ],
        );
        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
        let backend = bare_backend().await; // no folders yet
        assert!(backend.state.read().await.projects.is_empty());

        backend
            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
                event: WorkspaceFoldersChangeEvent {
                    added: vec![WorkspaceFolder {
                        uri: Url::from_file_path(&folder).unwrap(),
                        name: "p".into(),
                    }],
                    removed: vec![],
                },
            })
            .await;

        assert_eq!(
            backend.state.read().await.projects.len(),
            1,
            "an added workspace folder's project is warmed proactively",
        );
    }

    // ---- Slice F: one diagnostics scheduler ----

    fn change_params(uri: &Url, version: i32, text: &str) -> DidChangeTextDocumentParams {
        DidChangeTextDocumentParams {
            text_document: VersionedTextDocumentIdentifier {
                uri: uri.clone(),
                version,
            },
            content_changes: vec![TextDocumentContentChangeEvent {
                range: None,
                range_length: None,
                text: text.to_string(),
            }],
        }
    }

    /// Slice F: a **single-file** buffer (no project) now debounces by
    /// generation — a burst bumps the URI's generation once per change, so only
    /// the last-scheduled task survives its freshness check and runs `diagnose`.
    /// Before F single-file had no generation and ran once per keystroke.
    #[tokio::test]
    async fn a_single_file_burst_coalesces_by_generation() {
        // A `.bynk` file with no `bynk.toml` and no `src/` — single-file mode.
        let s = scratch_project("f_single", &[("a.bynk", "commons demo.a\n")]);
        let uri = file_uri(&s.0, "a.bynk");
        assert!(
            Backend::root_for_uri_uncached(&uri).is_none(),
            "precondition: the file routes to no project",
        );
        let backend = bare_backend().await;
        for _ in 0..3 {
            backend.schedule_single_file(uri.clone()).await;
        }
        assert_eq!(
            backend
                .state
                .read()
                .await
                .single_file_generations
                .get(&uri)
                .copied(),
            Some(3),
            "each change bumps the generation; only the third task passes its check",
        );
    }

    /// Slice F: `did_close` clears a single-file buffer's debounce generation, so
    /// the map does not grow unboundedly across a session.
    #[tokio::test]
    async fn did_close_clears_the_single_file_generation() {
        let s = scratch_project("f_close", &[("a.bynk", "commons demo.a\n")]);
        let uri = file_uri(&s.0, "a.bynk");
        let backend = bare_backend().await;
        backend.schedule_single_file(uri.clone()).await;
        assert!(
            backend
                .state
                .read()
                .await
                .single_file_generations
                .contains_key(&uri),
            "the generation exists after scheduling",
        );
        backend
            .did_close(DidCloseTextDocumentParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
            })
            .await;
        assert!(
            !backend
                .state
                .read()
                .await
                .single_file_generations
                .contains_key(&uri),
            "did_close clears the single-file generation",
        );
    }

    /// Slice F: `did_change` in **project** mode now feeds the one generation-
    /// based scheduler directly (no separate pre-sleep, no second hardcoded
    /// debounce). A burst bumps the project's generation once per change, so a
    /// single round survives — coalescing, through the real handler.
    #[tokio::test]
    async fn a_project_change_burst_coalesces_through_did_change() {
        let src = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
        let s = scratch_project(
            "f_burst",
            &[
                ("bynk.toml", "[project]\nname=\"q\"\n"),
                ("src/a.bynk", src),
            ],
        );
        let backend = backend_at(&s.0).await;
        let root = backend.test_root().await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, src).await;

        let gen_before = {
            let state = backend.state.read().await;
            state.projects.get(&root).unwrap().analysis_generation
        };
        for v in 2..=5 {
            backend
                .did_change(change_params(
                    &uri,
                    v,
                    &format!("{}{src}", "\n".repeat(v as usize)),
                ))
                .await;
        }
        let gen_after = {
            let state = backend.state.read().await;
            state.projects.get(&root).unwrap().analysis_generation
        };
        assert_eq!(
            gen_after - gen_before,
            4,
            "each of the four changes bumps the generation once — only the last \
             scheduled round runs (no per-change round, no stacked debounce)",
        );
    }

    // -- #596: store-map query vocabulary, end to end through `completion` ----
    //
    // The unit tests in `completion.rs`/`kernel_methods.rs`/`store_ops.rs`
    // cover each half in isolation; a #812 review flagged the gap that no test
    // drove a real `textDocument/completion` request through `Backend` to
    // check the two halves actually merge (and, separately, that the
    // provenance-based half survives a project-wide resolve failure that
    // blanks `type_receiver`). These close both.

    fn completion_labels(response: Option<CompletionResponse>) -> Vec<String> {
        match response {
            Some(CompletionResponse::Array(items)) => items.into_iter().map(|i| i.label).collect(),
            Some(CompletionResponse::List(list)) => {
                list.items.into_iter().map(|i| i.label).collect()
            }
            None => Vec::new(),
        }
    }

    async fn complete_at(backend: &Backend, uri: &Url, text: &str, needle: &str) -> Vec<String> {
        let offset = text.find(needle).expect("needle present") + needle.len();
        let pos = crate::position::offset_to_position(text, offset);
        let response = backend
            .completion(CompletionParams {
                text_document_position: TextDocumentPositionParams {
                    text_document: TextDocumentIdentifier { uri: uri.clone() },
                    position: pos,
                },
                work_done_progress_params: Default::default(),
                partial_result_params: Default::default(),
                context: None,
            })
            .await
            .expect("completion must not error");
        completion_labels(response)
    }

    /// A `store Map` field's `.` completion merges both halves in one
    /// response: the `Query` kernel methods (`filter`, `collect`, …) from
    /// `kernel_methods::methods_for`, and the store-field vocabulary (entry
    /// ops + accessors) from the provenance-based path — driven through the
    /// real `Backend::completion`, not the pure helpers directly.
    #[tokio::test]
    async fn store_map_receiver_completion_merges_both_vocabularies() {
        let src = "context shop\n\nagent Inventory {\n  key id: String\n  store items: Map[String, Int]\n\n  on call f() -> Effect[()] {\n    items.\n  }\n}\n";
        let s = scratch_project(
            "store_map_merge",
            &[
                ("bynk.toml", "[project]\nname=\"shop\"\n"),
                ("src/a.bynk", src),
            ],
        );
        let backend = backend_at(&s.0).await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, src).await;
        backend.run_round().await;

        let labels = complete_at(&backend, &uri, src, "    items.").await;
        assert!(
            labels.contains(&"filter".to_string()),
            "the Query kernel vocabulary: {labels:?}"
        );
        assert!(
            labels.contains(&"collect".to_string()),
            "the Query kernel vocabulary: {labels:?}"
        );
        assert!(
            labels.contains(&"put".to_string()),
            "the store entry ops: {labels:?}"
        );
        assert!(
            labels.contains(&"entries".to_string()),
            "the Map query accessors: {labels:?}"
        );
    }

    /// The provenance-based half does not need `type_receiver` to succeed: an
    /// unresolved type name elsewhere in the same file — in an unrelated
    /// `type` declaration, not even the agent using `items` — trips the
    /// *resolve* gate (`resolve_file`), which runs before `check_record` and
    /// so blanks `expr_types` for the **whole file** if it fails: the one
    /// clean-file-ceiling gap ADR 0094 didn't close (that error-tolerance is
    /// inside the checker; a resolve failure never reaches it). Before the
    /// #812 review fix, `value_member_completions` returned early on that
    /// `None` and never reached the store-field path at all; the entry
    /// ops/accessors must still surface here.
    #[tokio::test]
    async fn store_field_vocabulary_survives_an_unrelated_resolve_failure() {
        let src = "context shop\n\ntype Bad = { x: NoSuchType }\n\nagent Inventory {\n  key id: String\n  store items: Map[String, Int]\n\n  on call f() -> Effect[()] {\n    items.\n  }\n}\n";
        let s = scratch_project(
            "store_map_resolve_gap",
            &[
                ("bynk.toml", "[project]\nname=\"shop\"\n"),
                ("src/a.bynk", src),
            ],
        );
        let backend = backend_at(&s.0).await;
        let uri = file_uri(&s.0, "src/a.bynk");
        open(&backend, &uri, src).await;
        backend.run_round().await;

        // Precondition: the round really did fail to type this file (the
        // fixture actually reaches the ceiling this test is about, rather
        // than passing vacuously because the file happened to check fine).
        let analysis = backend.test_analysis().await.expect("a round committed");
        let rel = Backend::uri_to_rel(&analysis, &uri).expect("uri resolves");
        assert!(
            analysis
                .diagnostics
                .get(&rel)
                .is_some_and(|ds| !ds.is_empty()),
            "the fixture must actually fail to check — an undeclared return \
             type is the trigger this test exercises",
        );

        let labels = complete_at(&backend, &uri, src, "    items.").await;
        // A sharper precondition than "some diagnostic exists": the typed half
        // (`Query` kernel methods) really did go silent, confirming this
        // exercises `type_receiver` returning `None` — not a fixture that
        // merely warns while still typing `items` fine, which would let the
        // pre-fix code pass here too.
        assert!(
            !labels.contains(&"filter".to_string()),
            "the fixture must blank the typed half too, or this doesn't test \
             the gap: {labels:?}"
        );
        assert!(
            labels.contains(&"put".to_string()),
            "store entry ops must survive an unrelated resolve failure: {labels:?}"
        );
        assert!(
            labels.contains(&"entries".to_string()),
            "Map query accessors must survive an unrelated resolve failure: {labels:?}"
        );
    }
}