bynk-syntax 0.142.0

Bynk's syntax foundation: lexer, parser, AST, spans, the CompileError type, and the diagnostic-code registry — the lowest leaf of the compiler crate set.
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
//! Declaration parsing — unit/commons/context/test/mock/adapter/binding
//! declarations and their fragment forms. Split out of `parser.rs`
//! (ADR 0060) as a second `impl Parser` block; the scanning core (`expect`,
//! `peek`, `bump`, the trivia/doc helpers) and the other parse concerns stay
//! in the parent module, reached as ancestor privates via `self`.

use super::*;

impl<'a> Parser<'a> {
    pub(crate) fn parse_unit(&mut self) -> Result<SourceUnit, CompileError> {
        // Optional doc block describing the declaration itself, plus any
        // line comments that lead the file.
        let (header_leading, leading_doc) = self.collect_item_lead();
        let header_trivia = Trivia {
            leading: header_leading,
            trailing: None,
        };
        match self.peek_kind() {
            Some(TokenKind::Commons) => {
                let start = self.expect(TokenKind::Commons, "to start the commons declaration")?;
                let doc = self.finalize_doc(leading_doc, start.span);
                let name = self.parse_qualified_name()?;
                let mut c = match self.peek_kind() {
                    Some(TokenKind::LBrace) => self.parse_commons_brace(start.span, name, doc)?,
                    _ => self.parse_commons_fragment(start.span, name, doc)?,
                };
                c.trivia = header_trivia;
                Ok(SourceUnit::Commons(c))
            }
            Some(TokenKind::Context) => {
                let start = self.expect(TokenKind::Context, "to start the context declaration")?;
                let doc = self.finalize_doc(leading_doc, start.span);
                let name = self.parse_qualified_name()?;
                let mut c = match self.peek_kind() {
                    Some(TokenKind::LBrace) => self.parse_context_brace(start.span, name, doc)?,
                    _ => self.parse_context_fragment(start.span, name, doc)?,
                };
                c.trivia = header_trivia;
                Ok(SourceUnit::Context(c))
            }
            Some(TokenKind::Adapter) => {
                let start = self.expect(TokenKind::Adapter, "to start the adapter declaration")?;
                let doc = self.finalize_doc(leading_doc, start.span);
                let name = self.parse_qualified_name()?;
                let mut a = match self.peek_kind() {
                    Some(TokenKind::LBrace) => {
                        self.parse_adapter_body(start.span, name, doc, true)?
                    }
                    _ => self.parse_adapter_body(start.span, name, doc, false)?,
                };
                a.trivia = header_trivia;
                Ok(SourceUnit::Adapter(a))
            }
            Some(TokenKind::Suite) => {
                let start = self.expect(TokenKind::Suite, "to start the suite declaration")?;
                let doc = self.finalize_doc(leading_doc, start.span);
                let name = self.parse_qualified_name()?;
                // v0.118: an optional `as <tier>` sets the suite's default tier,
                // which its `case` members inherit and override (a `property`
                // ignores it). `as` is unambiguous here — no `consumes` is in
                // scope in a suite header (DECISION N).
                let tier = if self.peek_kind() == Some(TokenKind::As) {
                    self.bump();
                    Some(self.parse_tier()?)
                } else {
                    None
                };
                let mut t = match self.peek_kind() {
                    Some(TokenKind::LBrace) => {
                        self.parse_test_brace(start.span, name, doc, tier)?
                    }
                    _ => self.parse_test_fragment(start.span, name, doc, tier)?,
                };
                t.trivia = header_trivia;
                Ok(SourceUnit::Suite(t))
            }
            Some(_) => {
                let t = self.peek().unwrap();
                if let Some((_, doc_span)) = leading_doc {
                    self.warnings.push(CompileError::new(
                        "bynk.parse.orphan_doc_block",
                        doc_span,
                        "documentation block has no following declaration to attach to",
                    ));
                }
                Err(CompileError::new(
                    "bynk.parse.expected_unit_header",
                    t.span,
                    format!(
                        "expected `commons`, `context`, or `suite` to start the file, found {}",
                        t.kind.describe()
                    ),
                )
                .with_note(
                    "every `.bynk` file begins with either a `commons`, `context`, or `suite` declaration",
                ))
            }
            None => {
                if let Some((_, doc_span)) = leading_doc {
                    self.warnings.push(CompileError::new(
                        "bynk.parse.orphan_doc_block",
                        doc_span,
                        "documentation block has no following declaration to attach to",
                    ));
                }
                Err(CompileError::new(
                    "bynk.parse.unexpected_eof",
                    self.eof_span(),
                    "expected `commons`, `context`, or `suite` to start the file, found end of file",
                ))
            }
        }
    }

    fn parse_commons_brace(
        &mut self,
        start: Span,
        name: QualifiedName,
        documentation: Option<String>,
    ) -> Result<Commons, CompileError> {
        self.expect(TokenKind::LBrace, "after the commons name")?;
        let mut items = Vec::new();
        let mut uses = Vec::new();
        let trailing_comments: Vec<String>;
        loop {
            // Optional doc block and leading line comments before the next item.
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    // Doc not attachable; treat as orphan if present. Any
                    // leading comments at this position end up as the
                    // body's trailing comments.
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    trailing_comments = std::mem::take(&mut leading);
                    break;
                }
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(
                            CompileError::new(
                                "bynk.parse.orphan_doc_block",
                                doc_span,
                                "documentation block before `uses` is not allowed; only `type` and `fn` declarations carry docs",
                            ),
                        );
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Type) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_type_decl() {
                        Ok(mut t) => {
                            t.documentation = doc;
                            t.trivia.leading = leading;
                            t.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Type(t));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_fn_decl() {
                        Ok(mut f) => {
                            f.documentation = doc;
                            f.trivia.leading = leading;
                            f.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Fn(f));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Capability) => {
                    let err = CompileError::new(
                        "bynk.capability.outside_context",
                        self.peek().unwrap().span,
                        "`capability` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Provides) => {
                    let err = CompileError::new(
                        "bynk.provider.outside_context",
                        self.peek().unwrap().span,
                        "`provides` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Service) => {
                    let err = CompileError::new(
                        "bynk.service.outside_context",
                        self.peek().unwrap().span,
                        "`service` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Agent) => {
                    let err = CompileError::new(
                        "bynk.agent.outside_context",
                        self.peek().unwrap().span,
                        "`agent` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Actor) => {
                    let err = CompileError::new(
                        "bynk.actor.outside_context",
                        self.peek().unwrap().span,
                        "`actor` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected `type`, `fn`, or `uses` declaration, found {}",
                            t.kind.describe()
                        ),
                    )
                    .with_note(
                        "the body of a commons contains zero or more `type`, `fn`, or `uses` declarations",
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the commons body, found end of file",
                    ));
                }
            }
        }
        let end = self.expect(TokenKind::RBrace, "to close the commons body")?;
        Ok(Commons {
            name,
            items,
            uses,
            documentation,
            form: CommonsForm::Brace,
            span: start.merge(end.span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    fn parse_commons_fragment(
        &mut self,
        start: Span,
        name: QualifiedName,
        documentation: Option<String>,
    ) -> Result<Commons, CompileError> {
        let mut items = Vec::new();
        let mut uses = Vec::new();
        // Cover the header (`commons <name>`) so the unit span stays valid even
        // when every item is dropped by error recovery — the document-symbol
        // selection range (the name span) must remain contained in this span.
        let mut last_span = start.merge(name.span);
        let mut seen_item = false;
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(
                            CompileError::new(
                                "bynk.parse.orphan_doc_block",
                                doc_span,
                                "documentation block before `uses` is not allowed; only `type` and `fn` declarations carry docs",
                            ),
                        );
                    }
                    if seen_item {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.uses_after_decls",
                            t.span,
                            "`uses` clauses must appear before any `type` or `fn` declaration in a fragment-form commons",
                        )
                        .with_note(
                            "move all `uses` lines to immediately after the `commons` header",
                        ));
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            last_span = u.span;
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Type) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_type_decl() {
                        Ok(mut t) => {
                            t.documentation = doc;
                            t.trivia.leading = leading;
                            t.trivia.trailing = self.take_trailing_trivia();
                            last_span = t.span;
                            items.push(CommonsItem::Type(t));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_fn_decl() {
                        Ok(mut f) => {
                            f.documentation = doc;
                            f.trivia.leading = leading;
                            f.trivia.trailing = self.take_trailing_trivia();
                            last_span = f.span;
                            items.push(CommonsItem::Fn(f));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                None => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    // Comments we held as leading for the next item, plus
                    // any held in the trivia table's epilogue, become the
                    // commons body's trailing comments.
                    leading.extend(self.trivia.take_epilogue());
                    trailing_comments = leading;
                    break;
                }
                Some(TokenKind::Capability) => {
                    let err = CompileError::new(
                        "bynk.capability.outside_context",
                        self.peek().unwrap().span,
                        "`capability` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Provides) => {
                    let err = CompileError::new(
                        "bynk.provider.outside_context",
                        self.peek().unwrap().span,
                        "`provides` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Service) => {
                    let err = CompileError::new(
                        "bynk.service.outside_context",
                        self.peek().unwrap().span,
                        "`service` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Agent) => {
                    let err = CompileError::new(
                        "bynk.agent.outside_context",
                        self.peek().unwrap().span,
                        "`agent` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(TokenKind::Actor) => {
                    let err = CompileError::new(
                        "bynk.actor.outside_context",
                        self.peek().unwrap().span,
                        "`actor` declarations are only allowed inside a context, not a commons",
                    );
                    self.handle_item_err(err)?;
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected `type`, `fn`, or `uses` declaration, found {}",
                            t.kind.describe()
                        ),
                    )
                    .with_note(
                        "in fragment-form commons (no braces), the body is a sequence of `type`, `fn`, or `uses` declarations to end of file",
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        // Force progress in recovery: bump at least one token, then sync.
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
            }
        }
        Ok(Commons {
            name,
            items,
            uses,
            documentation,
            form: CommonsForm::Fragment,
            span: start.merge(last_span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    fn parse_uses_decl(&mut self) -> Result<UsesDecl, CompileError> {
        let kw = self.expect(TokenKind::Uses, "to start a `uses` declaration")?;
        let target = self.parse_qualified_name()?;
        let span = kw.span.merge(target.span);
        Ok(UsesDecl {
            target,
            span,
            trivia: Trivia::default(),
        })
    }

    fn parse_consumes_decl(&mut self) -> Result<ConsumesDecl, CompileError> {
        let kw = self.expect(TokenKind::Consumes, "to start a `consumes` declaration")?;
        let target = self.parse_qualified_name()?;
        let mut span = kw.span.merge(target.span);
        let mut alias = None;
        let mut selected = None;
        match self.peek_kind() {
            // v0.6: `consumes U as Alias`.
            Some(TokenKind::As) => {
                self.bump();
                let id = self.expect_ident("as an alias for the consumed context")?;
                span = span.merge(id.span);
                alias = Some(id);
            }
            // v0.17: `consumes U { Cap, … }` — selected capabilities (§3.3).
            Some(TokenKind::LBrace) => {
                self.bump();
                let mut names = Vec::new();
                while self.peek_kind() != Some(TokenKind::RBrace) {
                    let id = self.expect_ident("a capability name in `consumes U { … }`")?;
                    names.push(id);
                    if self.eat(TokenKind::Comma).is_none() {
                        break;
                    }
                }
                let close =
                    self.expect(TokenKind::RBrace, "to close the consumed-capability list")?;
                span = span.merge(close.span);
                selected = Some(names);
            }
            _ => {}
        }
        Ok(ConsumesDecl {
            target,
            alias,
            selected,
            span,
            trivia: Trivia::default(),
        })
    }

    fn parse_exports_decl(&mut self) -> Result<ExportsDecl, CompileError> {
        let kw = self.expect(TokenKind::Exports, "to start an `exports` declaration")?;
        let kind = match self.peek_kind() {
            Some(TokenKind::Opaque) => {
                self.bump();
                ExportKind::Type(Visibility::Opaque)
            }
            Some(TokenKind::Transparent) => {
                self.bump();
                ExportKind::Type(Visibility::Transparent)
            }
            // v0.15: `exports capability { ... }` offers capabilities to consumers.
            Some(TokenKind::Capability) => {
                self.bump();
                ExportKind::Capability
            }
            Some(_) => {
                let t = self.peek().unwrap();
                return Err(CompileError::new(
                    "bynk.parse.expected_visibility",
                    t.span,
                    format!(
                        "expected `opaque`, `transparent`, or `capability` after `exports`, found {}",
                        t.kind.describe()
                    ),
                )
                .with_note(
                    "exports clauses are `exports opaque { ... }`, `exports transparent { ... }`, or `exports capability { ... }`",
                ));
            }
            None => {
                return Err(CompileError::new(
                    "bynk.parse.unexpected_eof",
                    self.eof_span(),
                    "expected `opaque`, `transparent`, or `capability` after `exports`, found end of file",
                ));
            }
        };
        self.expect(TokenKind::LBrace, "to open the exports list")?;
        let mut names = Vec::new();
        let name_role = match kind {
            ExportKind::Capability => "as an exported capability name",
            ExportKind::Type(_) => "as an exported type name",
        };
        while self.peek_kind() != Some(TokenKind::RBrace) {
            names.push(self.expect_ident(name_role)?);
            if self.eat(TokenKind::Comma).is_none() {
                break;
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the exports list")?;
        let span = kw.span.merge(close.span);
        Ok(ExportsDecl {
            kind,
            names,
            span,
            trivia: Trivia::default(),
        })
    }

    fn parse_test_brace(
        &mut self,
        start: Span,
        target: QualifiedName,
        documentation: Option<String>,
        tier: Option<TestTier>,
    ) -> Result<SuiteDecl, CompileError> {
        self.expect(TokenKind::LBrace, "after the test target name")?;
        let mut uses = Vec::new();
        let mut provides = Vec::new();
        let mut cases = Vec::new();
        let mut properties = Vec::new();
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    trailing_comments = std::mem::take(&mut leading);
                    break;
                }
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `uses` is not allowed",
                        ));
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Provides) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_provides_clause() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            provides.push(p);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Case) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_test_case() {
                        Ok(mut c) => {
                            c.documentation = doc;
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            cases.push(c);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Property) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_property() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            properties.push(p);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected `uses`, `provides`, `case \"name\"`, or `property \"name\"` declaration, found {}",
                            t.kind.describe()
                        ),
                    )
                    .with_note(
                        "the body of a suite contains zero or more `uses`, `provides`, `case`, or `property` declarations",
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the test body, found end of file",
                    ));
                }
            }
        }
        let end = self.expect(TokenKind::RBrace, "to close the test body")?;
        Ok(SuiteDecl {
            target,
            uses,
            provides,
            cases,
            properties,
            tier,
            form: CommonsForm::Brace,
            documentation,
            span: start.merge(end.span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    fn parse_test_fragment(
        &mut self,
        start: Span,
        target: QualifiedName,
        documentation: Option<String>,
        tier: Option<TestTier>,
    ) -> Result<SuiteDecl, CompileError> {
        let mut uses = Vec::new();
        let mut provides = Vec::new();
        let mut cases = Vec::new();
        let mut properties = Vec::new();
        // Cover the header (`test <target>`) so the unit span stays valid even
        // when every item is dropped by error recovery (see commons fragment).
        let mut last_span = start.merge(target.span);
        let mut seen_non_uses = false;
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `uses` is not allowed",
                        ));
                    }
                    if seen_non_uses {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.uses_after_decls",
                            t.span,
                            "`uses` clauses must appear before any `provides`, `case`, or `property` declarations in a fragment-form test",
                        ));
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            last_span = u.span;
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Provides) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_provides_clause() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            last_span = p.span;
                            provides.push(p);
                            seen_non_uses = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Case) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_test_case() {
                        Ok(mut c) => {
                            c.documentation = doc;
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            last_span = c.span;
                            cases.push(c);
                            seen_non_uses = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Property) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_property() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            last_span = p.span;
                            properties.push(p);
                            seen_non_uses = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                None => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    leading.extend(self.trivia.take_epilogue());
                    trailing_comments = leading;
                    break;
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected `uses`, `provides`, `case \"name\"`, or `property \"name\"` declaration, found {}",
                            t.kind.describe()
                        ),
                    )
                    .with_note(
                        "in fragment-form suites, the body is a sequence of `uses`, `provides`, `case`, or `property` declarations to end of file",
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
            }
        }
        Ok(SuiteDecl {
            target,
            uses,
            provides,
            cases,
            properties,
            tier,
            form: CommonsForm::Fragment,
            documentation,
            span: start.merge(last_span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    /// v0.118: parse a tier name (`unit` / `integration` / `system`) after `as`.
    /// The names are contextual identifiers, not keywords, so they stay usable
    /// as ordinary identifiers everywhere else.
    fn parse_tier(&mut self) -> Result<TestTier, CompileError> {
        let tok = self.expect(TokenKind::Ident, "a tier name after `as`")?;
        match self.slice(tok.span) {
            "unit" => Ok(TestTier::Unit),
            "integration" => Ok(TestTier::Integration),
            "system" => Ok(TestTier::System),
            other => Err(CompileError::new(
                "bynk.parse.unknown_tier",
                tok.span,
                format!(
                    "`{other}` is not a test tier; expected `unit`, `integration`, or `system`"
                ),
            )
            .with_note(
                "a `case`/`suite` tier clause is `as unit`, `as integration`, or `as system`",
            )),
        }
    }

    /// v0.118: parse a `provides Cap.method(<args>) returns <v> | fails` clause
    /// (the leading `provides` has not yet been consumed).
    fn parse_provides_clause(&mut self) -> Result<ProvidesClause, CompileError> {
        let kw = self.expect(TokenKind::Provides, "to start a `provides` clause")?;
        let capability = self.expect_ident("the capability after `provides`")?;
        self.expect(
            TokenKind::Dot,
            "after the capability in a `provides` clause",
        )?;
        let method = self.expect_ident("the method name after `.`")?;
        self.expect(
            TokenKind::LParen,
            "after the method name in a `provides` clause",
        )?;
        let mut args = Vec::new();
        if self.peek_kind() != Some(TokenKind::RParen) {
            args.push(self.parse_arg_pattern()?);
            while self.eat(TokenKind::Comma).is_some() {
                if self.peek_kind() == Some(TokenKind::RParen) {
                    break;
                }
                args.push(self.parse_arg_pattern()?);
            }
        }
        self.expect(TokenKind::RParen, "to close the `provides` argument list")?;
        let rhs = self.parse_provides_rhs()?;
        let span = kw.span.merge(rhs.span());
        Ok(ProvidesClause {
            capability,
            method,
            args,
            rhs,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }

    /// One argument pattern in a `provides` call pattern: `_` or a value.
    fn parse_arg_pattern(&mut self) -> Result<ArgPattern, CompileError> {
        if self.peek_kind() == Some(TokenKind::Underscore) {
            let span = self.peek().unwrap().span;
            self.bump();
            Ok(ArgPattern::Any(span))
        } else {
            Ok(ArgPattern::Value(self.parse_expr()?))
        }
    }

    /// The right-hand side of a `provides` clause: `fails`, `returns <value>`,
    /// or `returns each [<outcome>, …]`. `returns`, `fails`, and `each` are
    /// contextual identifiers here.
    fn parse_provides_rhs(&mut self) -> Result<ProvidesRhs, CompileError> {
        let tok = self.expect(
            TokenKind::Ident,
            "`returns` or `fails` after the `provides` call pattern",
        )?;
        match self.slice(tok.span) {
            "fails" => Ok(ProvidesRhs::Fails(tok.span)),
            "returns" => {
                let is_each = self.peek_kind() == Some(TokenKind::Ident)
                    && self.slice(self.peek().unwrap().span) == "each";
                if is_each {
                    self.bump();
                    let open = self.expect(TokenKind::LBracket, "after `returns each`")?;
                    let mut outcomes = Vec::new();
                    if self.peek_kind() != Some(TokenKind::RBracket) {
                        outcomes.push(self.parse_seq_outcome()?);
                        while self.eat(TokenKind::Comma).is_some() {
                            if self.peek_kind() == Some(TokenKind::RBracket) {
                                break;
                            }
                            outcomes.push(self.parse_seq_outcome()?);
                        }
                    }
                    let close =
                        self.expect(TokenKind::RBracket, "to close the `returns each` sequence")?;
                    Ok(ProvidesRhs::ReturnsEach(outcomes, open.span.merge(close.span)))
                } else {
                    Ok(ProvidesRhs::Returns(self.parse_expr()?))
                }
            }
            other => Err(CompileError::new(
                "bynk.parse.expected_token",
                tok.span,
                format!("expected `returns` or `fails` in a `provides` clause, found `{other}`"),
            )
            .with_note(
                "a `provides` clause ends `returns <value>`, `returns each [<outcome>, …]`, or `fails`",
            )),
        }
    }

    /// One outcome in a `returns each` sequence: `fails` or a value.
    fn parse_seq_outcome(&mut self) -> Result<SeqOutcome, CompileError> {
        if self.peek_kind() == Some(TokenKind::Ident)
            && self.slice(self.peek().unwrap().span) == "fails"
        {
            let span = self.peek().unwrap().span;
            self.bump();
            Ok(SeqOutcome::Fails(span))
        } else {
            Ok(SeqOutcome::Value(self.parse_expr()?))
        }
    }

    fn parse_test_case(&mut self) -> Result<Case, CompileError> {
        let kw = self.expect(TokenKind::Case, "to start a test case")?;
        let name_tok = self.expect(TokenKind::StrLit, "as the test case name")?;
        let name = parse_string_literal(self.slice(name_tok.span), name_tok.span)?;
        // v0.118: an optional `as <tier>` after the case name.
        let tier = if self.peek_kind() == Some(TokenKind::As) {
            self.bump();
            Some(self.parse_tier()?)
        } else {
            None
        };
        // v0.118: case-scoped `provides` clauses lead the case body, before any
        // statements. The case opens its own brace so it can peel them off.
        let open = self.expect(TokenKind::LBrace, "to open the test case body")?;
        let mut provides = Vec::new();
        while self.peek_kind() == Some(TokenKind::Provides) {
            let (leading, item_doc) = self.collect_item_lead();
            let next_span = self.peek().unwrap().span;
            let doc = self.finalize_doc(item_doc, next_span);
            let mut p = self.parse_provides_clause()?;
            p.documentation = doc;
            p.trivia.leading = leading;
            p.trivia.trailing = self.take_trailing_trivia();
            provides.push(p);
        }
        let body = self.parse_block_rest(open.span)?;
        let span = kw.span.merge(body.span);
        Ok(Case {
            name,
            name_span: name_tok.span,
            tier,
            provides,
            body,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }

    /// v0.114 (testing track slice 2): a generative `property "name" { for all
    /// … }` block inside a suite.
    fn parse_property(&mut self) -> Result<PropertyDecl, CompileError> {
        let kw = self.expect(TokenKind::Property, "to start a property")?;
        let name_tok = self.expect(TokenKind::StrLit, "as the property name")?;
        let name = parse_string_literal(self.slice(name_tok.span), name_tok.span)?;
        self.expect(TokenKind::LBrace, "to open the property body")?;
        let forall = self.parse_for_all()?;
        let end = self.expect(TokenKind::RBrace, "to close the property body")?;
        Ok(PropertyDecl {
            name,
            name_span: name_tok.span,
            forall,
            documentation: None,
            span: kw.span.merge(end.span),
            trivia: Trivia::default(),
        })
    }

    /// `for all x: T, y: U [where <pred>] { … }` — the generative binder. Each
    /// binding's type supplies the runner's inhabitant space; `where` filters
    /// generated tuples before the body runs.
    fn parse_for_all(&mut self) -> Result<ForAll, CompileError> {
        // `for` and `all` are contextual identifiers, not keywords, so `all`
        // stays usable as a list combinator (`all(xs, p)`). Here they lead the
        // binder — validated by text.
        let start = self.expect(TokenKind::Ident, "to start a `for all` binder")?;
        if self.slice(start.span) != "for" {
            return Err(CompileError::new(
                "bynk.parse.expected_token",
                start.span,
                format!(
                    "expected `for` to start a `for all` binder, found `{}`",
                    self.slice(start.span)
                ),
            ));
        }
        let all_tok = self.expect(TokenKind::Ident, "after `for` in a `for all` binder")?;
        if self.slice(all_tok.span) != "all" {
            return Err(CompileError::new(
                "bynk.parse.expected_token",
                all_tok.span,
                format!(
                    "expected `all` after `for` in a `for all` binder, found `{}`",
                    self.slice(all_tok.span)
                ),
            ));
        }
        let mut bindings = Vec::new();
        loop {
            let name = self.expect_ident("as a `for all` binding name")?;
            self.expect(TokenKind::Colon, "after a `for all` binding name")?;
            let type_ref = self.parse_type_ref("as the type of a `for all` binding")?;
            bindings.push(ForAllBinding { name, type_ref });
            if self.eat(TokenKind::Comma).is_none() {
                break;
            }
        }
        let where_pred = if self.eat(TokenKind::Where).is_some() {
            Some(self.parse_expr()?)
        } else {
            None
        };
        let body = self.parse_block("to open the `for all` body")?;
        let span = start.span.merge(body.span);
        Ok(ForAll {
            bindings,
            where_pred,
            body,
            span,
        })
    }

    fn parse_context_brace(
        &mut self,
        start: Span,
        name: QualifiedName,
        documentation: Option<String>,
    ) -> Result<Context, CompileError> {
        self.expect(TokenKind::LBrace, "after the context name")?;
        let mut items = Vec::new();
        let mut uses = Vec::new();
        let mut consumes = Vec::new();
        let mut exports = Vec::new();
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    trailing_comments = std::mem::take(&mut leading);
                    break;
                }
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `uses` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Consumes) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `consumes` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    match self.parse_consumes_decl() {
                        Ok(mut c) => {
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            consumes.push(c);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Exports) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `exports` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    match self.parse_exports_decl() {
                        Ok(mut e) => {
                            e.trivia.leading = leading;
                            e.trivia.trailing = self.take_trailing_trivia();
                            exports.push(e);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Type) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_type_decl() {
                        Ok(mut t) => {
                            t.documentation = doc;
                            t.trivia.leading = leading;
                            t.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Type(t));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_fn_decl() {
                        Ok(mut f) => {
                            f.documentation = doc;
                            f.trivia.leading = leading;
                            f.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Fn(f));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Capability) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_capability_decl() {
                        Ok(mut c) => {
                            c.documentation = doc;
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Capability(c));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Provides) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_provider_decl() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Provider(p));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Service) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_service_decl() {
                        Ok(mut s) => {
                            s.documentation = doc;
                            s.trivia.leading = leading;
                            s.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Service(s));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Agent) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_agent_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Agent(a));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Actor) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_actor_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            items.push(CommonsItem::Actor(a));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected a `type`, `fn`, `uses`, `consumes`, `exports`, `capability`, `provides`, `service`, `agent`, or `actor` declaration, found {}",
                            t.kind.describe()
                        ),
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the context body, found end of file",
                    ));
                }
            }
        }
        let end = self.expect(TokenKind::RBrace, "to close the context body")?;
        Ok(Context {
            name,
            items,
            uses,
            consumes,
            exports,
            documentation,
            form: CommonsForm::Brace,
            span: start.merge(end.span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    fn parse_context_fragment(
        &mut self,
        start: Span,
        name: QualifiedName,
        documentation: Option<String>,
    ) -> Result<Context, CompileError> {
        let mut items = Vec::new();
        let mut uses = Vec::new();
        let mut consumes = Vec::new();
        let mut exports = Vec::new();
        // Cover the header (`context <name>`) so the unit span stays valid even
        // when every item is dropped by error recovery (see commons fragment).
        let mut last_span = start.merge(name.span);
        let mut seen_item = false;
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::Uses) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `uses` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    if seen_item {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.uses_after_decls",
                            t.span,
                            "`uses` clauses must appear before any `type` or `fn` declaration in a fragment-form context",
                        )
                        .with_note(
                            "move all `uses` lines to immediately after the `context` header",
                        ));
                    }
                    match self.parse_uses_decl() {
                        Ok(mut u) => {
                            u.trivia.leading = leading;
                            u.trivia.trailing = self.take_trailing_trivia();
                            last_span = u.span;
                            uses.push(u);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Consumes) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `consumes` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    if seen_item {
                        let t = self.peek().unwrap();
                        let err = CompileError::new(
                            "bynk.parse.consumes_after_decls",
                            t.span,
                            "`consumes` clauses must appear before any `type` or `fn` declaration in a fragment-form context",
                        )
                        .with_note(
                            "move all `consumes` lines to immediately after the `uses` clauses",
                        );
                        if self.recover_mode {
                            self.recovered_errors.push(err);
                            self.bump();
                            self.recover_to_top_item();
                            continue;
                        } else {
                            return Err(err);
                        }
                    }
                    match self.parse_consumes_decl() {
                        Ok(mut c) => {
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            last_span = c.span;
                            consumes.push(c);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Exports) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block before `exports` is not allowed; only `type` and `fn` declarations carry docs",
                        ));
                    }
                    if seen_item {
                        let t = self.peek().unwrap();
                        let err = CompileError::new(
                            "bynk.parse.exports_after_decls",
                            t.span,
                            "`exports` clauses must appear before any `type` or `fn` declaration in a fragment-form context",
                        )
                        .with_note(
                            "move all `exports` lines to immediately after the `consumes` clauses",
                        );
                        if self.recover_mode {
                            self.recovered_errors.push(err);
                            self.bump();
                            self.recover_to_top_item();
                            continue;
                        } else {
                            return Err(err);
                        }
                    }
                    match self.parse_exports_decl() {
                        Ok(mut e) => {
                            e.trivia.leading = leading;
                            e.trivia.trailing = self.take_trailing_trivia();
                            last_span = e.span;
                            exports.push(e);
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Type) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_type_decl() {
                        Ok(mut t) => {
                            t.documentation = doc;
                            t.trivia.leading = leading;
                            t.trivia.trailing = self.take_trailing_trivia();
                            last_span = t.span;
                            items.push(CommonsItem::Type(t));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_fn_decl() {
                        Ok(mut f) => {
                            f.documentation = doc;
                            f.trivia.leading = leading;
                            f.trivia.trailing = self.take_trailing_trivia();
                            last_span = f.span;
                            items.push(CommonsItem::Fn(f));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Capability) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_capability_decl() {
                        Ok(mut c) => {
                            c.documentation = doc;
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            last_span = c.span;
                            items.push(CommonsItem::Capability(c));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Provides) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_provider_decl() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            last_span = p.span;
                            items.push(CommonsItem::Provider(p));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Service) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_service_decl() {
                        Ok(mut s) => {
                            s.documentation = doc;
                            s.trivia.leading = leading;
                            s.trivia.trailing = self.take_trailing_trivia();
                            last_span = s.span;
                            items.push(CommonsItem::Service(s));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Agent) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_agent_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            last_span = a.span;
                            items.push(CommonsItem::Agent(a));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Actor) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_actor_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            last_span = a.span;
                            items.push(CommonsItem::Actor(a));
                            seen_item = true;
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                None => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    leading.extend(self.trivia.take_epilogue());
                    trailing_comments = leading;
                    break;
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected a `type`, `fn`, `uses`, `consumes`, `exports`, `capability`, `provides`, `service`, `agent`, or `actor` declaration, found {}",
                            t.kind.describe()
                        ),
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
            }
        }
        Ok(Context {
            name,
            items,
            uses,
            consumes,
            exports,
            documentation,
            form: CommonsForm::Fragment,
            span: start.merge(last_span),
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    /// Parse an `adapter` body in either brace (`brace = true`) or fragment
    /// (`brace = false`) form (v0.17 §3.1). An adapter accepts a `binding`
    /// clause plus the same item set as a context; service, agent and
    /// bodied-provider placement is validated by the checker, not rejected
    /// here, so the diagnostics can be precise. v0.18 admits `consumes`
    /// (braced form, adapter targets — also checked semantically).
    fn parse_adapter_body(
        &mut self,
        start: Span,
        name: QualifiedName,
        documentation: Option<String>,
        brace: bool,
    ) -> Result<AdapterDecl, CompileError> {
        if brace {
            self.expect(TokenKind::LBrace, "after the adapter name")?;
        }
        let mut items = Vec::new();
        let mut uses = Vec::new();
        let mut exports = Vec::new();
        let mut consumes = Vec::new();
        let mut binding: Option<BindingDecl> = None;
        // Cover the header (`adapter <name>`) so the unit span stays valid even
        // when every item is dropped by error recovery (see commons fragment).
        let mut last_span = start.merge(name.span);
        let trailing_comments: Vec<String>;
        loop {
            let (mut leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) if brace => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    trailing_comments = std::mem::take(&mut leading);
                    break;
                }
                None if !brace => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    leading.extend(self.trivia.take_epilogue());
                    trailing_comments = leading;
                    break;
                }
                Some(TokenKind::Binding) => {
                    let mut b = self.parse_binding_decl()?;
                    b.trivia.leading = leading;
                    b.trivia.trailing = self.take_trailing_trivia();
                    last_span = b.span;
                    if binding.is_some() {
                        let err = CompileError::new(
                            "bynk.adapter.duplicate_binding",
                            b.span,
                            "an adapter may declare at most one `binding` clause",
                        );
                        self.handle_item_err(err)?;
                    } else {
                        binding = Some(b);
                    }
                }
                Some(TokenKind::Uses) => match self.parse_uses_decl() {
                    Ok(mut u) => {
                        u.trivia.leading = leading;
                        u.trivia.trailing = self.take_trailing_trivia();
                        last_span = u.span;
                        uses.push(u);
                    }
                    Err(e) => self.handle_item_err(e)?,
                },
                // v0.18: adapter-to-adapter capability dependencies. The braced-form
                // and adapter-target restrictions are checked semantically so the
                // diagnostics can be precise.
                Some(TokenKind::Consumes) => match self.parse_consumes_decl() {
                    Ok(mut c) => {
                        c.trivia.leading = leading;
                        c.trivia.trailing = self.take_trailing_trivia();
                        last_span = c.span;
                        consumes.push(c);
                    }
                    Err(e) => self.handle_item_err(e)?,
                },
                Some(TokenKind::Exports) => match self.parse_exports_decl() {
                    Ok(mut e) => {
                        e.trivia.leading = leading;
                        e.trivia.trailing = self.take_trailing_trivia();
                        last_span = e.span;
                        exports.push(e);
                    }
                    Err(e) => self.handle_item_err(e)?,
                },
                Some(TokenKind::Type) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_type_decl() {
                        Ok(mut t) => {
                            t.documentation = doc;
                            t.trivia.leading = leading;
                            t.trivia.trailing = self.take_trailing_trivia();
                            last_span = t.span;
                            items.push(CommonsItem::Type(t));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_fn_decl() {
                        Ok(mut f) => {
                            f.documentation = doc;
                            f.trivia.leading = leading;
                            f.trivia.trailing = self.take_trailing_trivia();
                            last_span = f.span;
                            items.push(CommonsItem::Fn(f));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Capability) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_capability_decl() {
                        Ok(mut c) => {
                            c.documentation = doc;
                            c.trivia.leading = leading;
                            c.trivia.trailing = self.take_trailing_trivia();
                            last_span = c.span;
                            items.push(CommonsItem::Capability(c));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Provides) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_provider_decl() {
                        Ok(mut p) => {
                            p.documentation = doc;
                            p.trivia.leading = leading;
                            p.trivia.trailing = self.take_trailing_trivia();
                            last_span = p.span;
                            items.push(CommonsItem::Provider(p));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                // `service` and `agent` parse into items so the checker can
                // reject them precisely (`bynk.adapter.disallowed_item`).
                Some(TokenKind::Service) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_service_decl() {
                        Ok(mut s) => {
                            s.documentation = doc;
                            s.trivia.leading = leading;
                            s.trivia.trailing = self.take_trailing_trivia();
                            last_span = s.span;
                            items.push(CommonsItem::Service(s));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Agent) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_agent_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            last_span = a.span;
                            items.push(CommonsItem::Agent(a));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                Some(TokenKind::Actor) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    match self.parse_actor_decl() {
                        Ok(mut a) => {
                            a.documentation = doc;
                            a.trivia.leading = leading;
                            a.trivia.trailing = self.take_trailing_trivia();
                            last_span = a.span;
                            items.push(CommonsItem::Actor(a));
                        }
                        Err(e) => self.handle_item_err(e)?,
                    }
                }
                _ => {
                    let t = match self.peek() {
                        Some(t) => t,
                        None => {
                            return Err(CompileError::new(
                                "bynk.parse.unexpected_eof",
                                self.eof_span(),
                                "expected `}` to close the adapter body, found end of file",
                            ));
                        }
                    };
                    let err = CompileError::new(
                        "bynk.parse.expected_item",
                        t.span,
                        format!(
                            "expected a `binding`, `type`, `fn`, `uses`, `consumes`, `exports`, `capability`, or `provides` declaration, found {}",
                            t.kind.describe()
                        ),
                    );
                    if self.recover_mode {
                        self.recovered_errors.push(err);
                        self.bump();
                        self.recover_to_top_item();
                    } else {
                        return Err(err);
                    }
                }
            }
        }
        let span = if brace {
            let end = self.expect(TokenKind::RBrace, "to close the adapter body")?;
            start.merge(end.span)
        } else {
            start.merge(last_span)
        };
        Ok(AdapterDecl {
            name,
            items,
            uses,
            exports,
            consumes,
            binding,
            documentation,
            form: if brace {
                CommonsForm::Brace
            } else {
                CommonsForm::Fragment
            },
            span,
            trivia: Trivia::default(),
            trailing_comments,
        })
    }

    /// Parse a `binding "<module>" requires { "pkg": "range", … }` clause
    /// (v0.17 §3.5). The `requires { … }` map is optional.
    fn parse_binding_decl(&mut self) -> Result<BindingDecl, CompileError> {
        let kw = self.expect(TokenKind::Binding, "to start a `binding` declaration")?;
        let mod_tok = self.expect(
            TokenKind::StrLit,
            "the binding module path as a string literal",
        )?;
        let module = parse_string_literal(self.slice(mod_tok.span), mod_tok.span)?;
        let mut span = kw.span.merge(mod_tok.span);
        let mut requires = Vec::new();
        // v0.115: `requires` is a keyword (contract clauses). In a `binding`
        // it heads the optional dependency map (`requires { "pkg": "range" }`);
        // the two uses never overlap syntactically.
        if self.peek_kind() == Some(TokenKind::Requires) {
            self.bump(); // `requires`
            self.expect(TokenKind::LBrace, "to open the `requires` map")?;
            loop {
                match self.peek_kind() {
                    Some(TokenKind::RBrace) => break,
                    Some(TokenKind::StrLit) => {
                        let pkg_tok = self.bump().unwrap();
                        let package = parse_string_literal(self.slice(pkg_tok.span), pkg_tok.span)?;
                        self.expect(TokenKind::Colon, "after the package name")?;
                        let range_tok = self
                            .expect(TokenKind::StrLit, "the version range as a string literal")?;
                        let range =
                            parse_string_literal(self.slice(range_tok.span), range_tok.span)?;
                        requires.push(RequiresDep {
                            package,
                            range,
                            span: pkg_tok.span.merge(range_tok.span),
                        });
                        // optional trailing comma between entries
                        self.eat(TokenKind::Comma);
                    }
                    _ => {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.expected_item",
                            t.span,
                            format!(
                                "expected a `\"package\": \"range\"` entry or `}}` in the `requires` map, found {}",
                                t.kind.describe()
                            ),
                        ));
                    }
                }
            }
            let close = self.expect(TokenKind::RBrace, "to close the `requires` map")?;
            span = span.merge(close.span);
        }
        Ok(BindingDecl {
            module,
            module_span: mod_tok.span,
            requires,
            span,
            trivia: Trivia::default(),
        })
    }

    fn parse_qualified_name(&mut self) -> Result<QualifiedName, CompileError> {
        let first = self.expect_ident("for the commons name")?;
        let mut parts = vec![first];
        let mut span = parts[0].span;
        while self.eat(TokenKind::Dot).is_some() {
            let part = self.expect_ident("after `.` in the commons name")?;
            span = span.merge(part.span);
            parts.push(part);
        }
        Ok(QualifiedName { parts, span })
    }
}

impl<'a> Parser<'a> {
    // -- v0.5 declarations --

    fn parse_capability_decl(&mut self) -> Result<CapabilityDecl, CompileError> {
        let kw = self.expect(TokenKind::Capability, "to start a capability declaration")?;
        let name = self.expect_ident("after `capability`")?;
        self.expect(TokenKind::LBrace, "to open the capability body")?;
        let mut ops = Vec::new();
        loop {
            let (leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following operation to attach to",
                        ));
                    }
                    break;
                }
                Some(TokenKind::Fn) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut op = self.parse_capability_op()?;
                    op.documentation = doc;
                    op.trivia.leading = leading;
                    op.trivia.trailing = self.take_trailing_trivia();
                    ops.push(op);
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    return Err(CompileError::new(
                        "bynk.parse.expected_capability_op",
                        t.span,
                        format!(
                            "expected `fn` to declare a capability operation, found {}",
                            t.kind.describe()
                        ),
                    ));
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the capability body, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the capability body")?;
        if ops.is_empty() {
            return Err(CompileError::new(
                "bynk.parse.empty_capability",
                kw.span.merge(close.span),
                "a capability must declare at least one operation",
            ));
        }
        Ok(CapabilityDecl {
            name,
            ops,
            documentation: None,
            span: kw.span.merge(close.span),
            trivia: Trivia::default(),
        })
    }

    fn parse_capability_op(&mut self) -> Result<CapabilityOp, CompileError> {
        let kw = self.expect(TokenKind::Fn, "to start a capability operation")?;
        let name = self.expect_ident("as the capability operation name")?;
        self.expect(TokenKind::LParen, "after the operation name")?;
        let mut params = Vec::new();
        if self.peek_kind() != Some(TokenKind::RParen) {
            params.push(self.parse_param()?);
            while self.eat(TokenKind::Comma).is_some() {
                params.push(self.parse_param()?);
            }
        }
        self.expect(TokenKind::RParen, "to close the operation parameter list")?;
        self.expect(TokenKind::Arrow, "before the operation return type")?;
        let return_type = self.parse_type_ref("as the operation return type")?;
        let end_span = return_type.span();
        Ok(CapabilityOp {
            name,
            params,
            return_type,
            documentation: None,
            span: kw.span.merge(end_span),
            trivia: Trivia::default(),
        })
    }

    /// Parse one capability reference in a `given` clause (v0.15 §3.2). A bare
    /// name (`Cap`) is a local capability; a dotted name (`B.Cap` /
    /// `platform.time.Clock`) refers to a capability provided by a consumed
    /// context — every segment but the last forms the context prefix.
    fn parse_cap_ref(&mut self) -> Result<CapRef, CompileError> {
        let role = "as a capability name in the `given` clause";
        let mut parts = vec![self.expect_ident(role)?];
        while self.peek_kind() == Some(TokenKind::Dot) {
            self.bump();
            parts.push(self.expect_ident(role)?);
        }
        let name = parts.pop().unwrap();
        let context = if parts.is_empty() {
            None
        } else {
            let qspan = parts
                .first()
                .unwrap()
                .span
                .merge(parts.last().unwrap().span);
            Some(QualifiedName { parts, span: qspan })
        };
        let span = context
            .as_ref()
            .map(|q| q.span.merge(name.span))
            .unwrap_or(name.span);
        Ok(CapRef {
            context,
            name,
            span,
        })
    }

    fn parse_provider_decl(&mut self) -> Result<ProviderDecl, CompileError> {
        let kw = self.expect(TokenKind::Provides, "to start a provider declaration")?;
        let capability = self.expect_ident("after `provides`")?;
        self.expect(TokenKind::Eq, "after the capability name")?;
        let provider_name = self.expect_ident("as the provider name")?;
        // v0.12: optional `given C1, C2` — capabilities the provider depends on.
        // v0.15: a dependency may be a cross-context capability (`given B.Cap`).
        let mut given = Vec::new();
        if self.peek_kind() == Some(TokenKind::Given) {
            self.bump();
            given.push(self.parse_cap_ref()?);
            while self.eat(TokenKind::Comma).is_some() {
                given.push(self.parse_cap_ref()?);
            }
        }
        // v0.17: a provider with **no** brace block is an *external* provider —
        // its implementation is supplied by an adapter's binding. The absence of
        // the brace block (not an empty one) is the signal. Whether this form is
        // legal here (adapter) or not (context) is decided by the checker, so the
        // parser accepts both shapes structurally.
        if self.peek_kind() != Some(TokenKind::LBrace) {
            let end = given.last().map(|g| g.span).unwrap_or(provider_name.span);
            return Ok(ProviderDecl {
                capability,
                provider_name,
                given,
                ops: Vec::new(),
                external: true,
                documentation: None,
                span: kw.span.merge(end),
                trivia: Trivia::default(),
            });
        }
        self.expect(TokenKind::LBrace, "to open the provider body")?;
        let mut ops = Vec::new();
        loop {
            let leading = self.take_leading_trivia();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => break,
                Some(TokenKind::Fn) => {
                    let mut op = self.parse_provider_op()?;
                    op.trivia.leading = leading;
                    op.trivia.trailing = self.take_trailing_trivia();
                    ops.push(op);
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    return Err(CompileError::new(
                        "bynk.parse.expected_provider_op",
                        t.span,
                        format!(
                            "expected `fn` to declare a provider operation, found {}",
                            t.kind.describe()
                        ),
                    ));
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the provider body, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the provider body")?;
        Ok(ProviderDecl {
            capability,
            provider_name,
            given,
            ops,
            external: false,
            documentation: None,
            span: kw.span.merge(close.span),
            trivia: Trivia::default(),
        })
    }

    fn parse_provider_op(&mut self) -> Result<ProviderOp, CompileError> {
        let kw = self.expect(TokenKind::Fn, "to start a provider operation")?;
        let name = self.expect_ident("as the provider operation name")?;
        self.expect(TokenKind::LParen, "after the operation name")?;
        let mut params = Vec::new();
        if self.peek_kind() != Some(TokenKind::RParen) {
            params.push(self.parse_param()?);
            while self.eat(TokenKind::Comma).is_some() {
                params.push(self.parse_param()?);
            }
        }
        self.expect(TokenKind::RParen, "to close the operation parameter list")?;
        self.expect(TokenKind::Arrow, "before the operation return type")?;
        let return_type = self.parse_type_ref("as the operation return type")?;
        let body = self.parse_block("to open the provider operation body")?;
        let span = kw.span.merge(body.span);
        Ok(ProviderOp {
            name,
            params,
            return_type,
            body,
            span,
            trivia: Trivia::default(),
        })
    }

    /// v0.45: an actor declaration — a nominal boundary contract.
    ///
    /// Normal form: `actor Name { auth = Scheme }` or
    /// `actor Name { auth = Scheme, identity = Type }`.
    ///
    /// Reserved refinement form (parsed, rejected in the checker):
    /// `actor Admin = User where <predicate>`.
    fn parse_actor_decl(&mut self) -> Result<ActorDecl, CompileError> {
        let kw = self.expect(TokenKind::Actor, "to start an actor declaration")?;
        let name = self.expect_ident("after `actor`")?;

        // Refinement form: `actor Name = Base where <predicate>` (Q3). Parsed so
        // the grammar is fixed now; the checker emits
        // `bynk.actor.refinement_unsupported`.
        if self.peek_kind() == Some(TokenKind::Eq) {
            self.bump();
            let base = self.expect_ident("as the base actor after `=`")?;
            self.expect(TokenKind::Where, "before the actor refinement predicate")?;
            let predicate = self.parse_expr()?;
            let span = kw.span.merge(predicate.span);
            return Ok(ActorDecl {
                name,
                auth: None,
                auth_config: Vec::new(),
                identity: None,
                refinement: Some(ActorRefinement {
                    base,
                    predicate,
                    span,
                }),
                documentation: None,
                span,
                trivia: Trivia::default(),
            });
        }

        // Normal form: `actor Name { auth = Scheme (, identity = Type)? }`.
        self.expect(TokenKind::LBrace, "to open the actor body")?;
        let auth_kw = self.expect_ident("expected `auth` to start the actor body")?;
        if auth_kw.name != "auth" {
            return Err(CompileError::new(
                "bynk.parse.expected_token",
                auth_kw.span,
                format!(
                    "expected `auth` in the actor body, found `{}`",
                    auth_kw.name
                ),
            )
            .with_note("an actor body begins with `auth = <Scheme>`"));
        }
        self.expect(TokenKind::Eq, "after `auth`")?;
        // The scheme name is an identifier, except `None` (which is also the
        // `Option` keyword) — accept that token here as the scheme name.
        let auth = if self.peek_kind() == Some(TokenKind::None) {
            let t = self.expect(TokenKind::None, "as the authentication scheme")?;
            Ident {
                name: "None".to_string(),
                span: t.span,
            }
        } else {
            self.expect_ident("as the authentication scheme after `auth =`")?
        };

        // v0.47/v0.51: a scheme may carry a keyed config —
        // `Scheme(key = value, …)` (e.g. `Bearer(secret = "…")`,
        // `Signature(secret = "…", header = "…", timestamp = "…", tolerance =
        // 300)`). Values are string or integer literals; the checker validates
        // which keys each scheme requires/allows.
        let mut auth_config = Vec::new();
        if self.peek_kind() == Some(TokenKind::LParen) {
            self.bump();
            loop {
                let key = self.expect_ident("as a scheme config key")?;
                self.expect(TokenKind::Eq, "after the scheme config key")?;
                let (value, vspan) = match self.peek_kind() {
                    Some(TokenKind::StrLit) => {
                        let t = self.expect(TokenKind::StrLit, "as a scheme config value")?;
                        (
                            SchemeArgValue::Str(parse_string_literal(self.slice(t.span), t.span)?),
                            t.span,
                        )
                    }
                    Some(TokenKind::IntLit) => {
                        let t = self.expect(TokenKind::IntLit, "as a scheme config value")?;
                        let n: i64 = self.slice(t.span).parse().map_err(|_| {
                            CompileError::new(
                                "bynk.parse.expected_token",
                                t.span,
                                "invalid integer in scheme config".to_string(),
                            )
                        })?;
                        (SchemeArgValue::Int(n), t.span)
                    }
                    _ => {
                        let t = self.peek();
                        return Err(CompileError::new(
                            "bynk.parse.expected_token",
                            t.map(|t| t.span).unwrap_or_else(|| self.eof_span()),
                            "expected a string or integer scheme config value".to_string(),
                        ));
                    }
                };
                auth_config.push(SchemeArg {
                    key,
                    value,
                    span: vspan,
                });
                if self.eat(TokenKind::Comma).is_none() {
                    break;
                }
                if self.peek_kind() == Some(TokenKind::RParen) {
                    break; // trailing comma
                }
            }
            self.expect(TokenKind::RParen, "to close the scheme config")?;
        }

        let mut identity = None;
        if self.eat(TokenKind::Comma).is_some() {
            let id_kw = self.expect_ident("expected `identity` after `,`")?;
            if id_kw.name != "identity" {
                return Err(CompileError::new(
                    "bynk.parse.expected_token",
                    id_kw.span,
                    format!("expected `identity`, found `{}`", id_kw.name),
                )
                .with_note("the only actor field after `auth` is `identity = <Type>`"));
            }
            self.expect(TokenKind::Eq, "after `identity`")?;
            identity = Some(self.parse_type_ref("as the actor identity type")?);
        }

        let close = self.expect(TokenKind::RBrace, "to close the actor body")?;
        let span = kw.span.merge(close.span);
        Ok(ActorDecl {
            name,
            auth: Some(auth),
            auth_config,
            identity,
            refinement: None,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }

    fn parse_service_decl(&mut self) -> Result<ServiceDecl, CompileError> {
        let kw = self.expect(TokenKind::Service, "to start a service declaration")?;
        let name = self.expect_ident("after `service`")?;
        let protocol = self.parse_service_protocol()?;
        self.expect(TokenKind::LBrace, "to open the service body")?;
        let mut handlers = Vec::new();
        let mut cors: Option<CorsPolicy> = None;
        let mut security: Option<SecurityPolicy> = None;
        let mut limits: Option<LimitsPolicy> = None;
        loop {
            let (leading, item_doc) = self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following handler to attach to",
                        ));
                    }
                    break;
                }
                // `cors { … }` is a contextual keyword (like `store`/`key`): the
                // identifier `cors` in service-body item position introduces the
                // CORS policy, so it stays usable as an ordinary identifier
                // elsewhere. At most one per service.
                Some(TokenKind::Ident) if self.peek_is_cors_kw() => {
                    let policy = self.parse_cors_policy(leading)?;
                    if cors.is_some() {
                        return Err(CompileError::new(
                            "bynk.parse.duplicate_cors",
                            policy.span,
                            "a service declares at most one `cors { }` policy",
                        ));
                    }
                    cors = Some(policy);
                }
                // `security { … }` is a contextual keyword like `cors` (v0.141,
                // ADR 0164): the identifier `security` in service-body item
                // position introduces the security-headers policy, so it stays
                // usable as an ordinary identifier elsewhere. At most one per
                // service.
                Some(TokenKind::Ident) if self.peek_is_security_kw() => {
                    let policy = self.parse_security_policy(leading)?;
                    if security.is_some() {
                        return Err(CompileError::new(
                            "bynk.parse.duplicate_security",
                            policy.span,
                            "a service declares at most one `security { }` policy",
                        ));
                    }
                    security = Some(policy);
                }
                // `limits { … }` is a contextual keyword like `cors`/`security`
                // (v0.142, ADR 0165): the identifier `limits` in service-body item
                // position introduces the request-body-size policy, so it stays
                // usable as an ordinary identifier elsewhere. At most one per
                // service.
                Some(TokenKind::Ident) if self.peek_is_limits_kw() => {
                    let policy = self.parse_limits_policy(leading)?;
                    if limits.is_some() {
                        return Err(CompileError::new(
                            "bynk.parse.duplicate_limits",
                            policy.span,
                            "a service declares at most one `limits { }` policy",
                        ));
                    }
                    limits = Some(policy);
                }
                // A leading `@name(args)` introduces a handler-position annotation
                // (v0.140): consume the annotation run, then the `on` handler it
                // decorates. Validation gates `@cache` to `on GET` and `@limit` to
                // a body-taking route downstream.
                Some(TokenKind::At) => {
                    let annotations = self.parse_handler_annotations()?;
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut h = self.parse_handler(false, annotations)?;
                    h.documentation = doc;
                    h.trivia.leading = leading;
                    h.trivia.trailing = self.take_trailing_trivia();
                    handlers.push(h);
                }
                Some(TokenKind::On) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut h = self.parse_handler(false, Vec::new())?;
                    h.documentation = doc;
                    h.trivia.leading = leading;
                    h.trivia.trailing = self.take_trailing_trivia();
                    handlers.push(h);
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    return Err(CompileError::new(
                        "bynk.parse.expected_handler",
                        t.span,
                        format!(
                            "expected `on` to start a handler, found {}",
                            t.kind.describe()
                        ),
                    ));
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the service body, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the service body")?;
        if handlers.is_empty() {
            return Err(CompileError::new(
                "bynk.parse.empty_service",
                kw.span.merge(close.span),
                "a service must declare at least one handler",
            ));
        }
        Ok(ServiceDecl {
            name,
            protocol,
            cors,
            security,
            limits,
            handlers,
            documentation: None,
            span: kw.span.merge(close.span),
            trivia: Trivia::default(),
        })
    }

    /// True when the next token is the contextual keyword `cors` (an identifier
    /// literally spelled `cors`), introducing the CORS policy section.
    fn peek_is_cors_kw(&self) -> bool {
        matches!(self.peek(), Some(t) if t.kind == TokenKind::Ident && self.slice(t.span) == "cors")
    }

    /// True when the next token is the contextual keyword `security` (an
    /// identifier literally spelled `security`), introducing the security-headers
    /// policy section.
    fn peek_is_security_kw(&self) -> bool {
        matches!(self.peek(), Some(t) if t.kind == TokenKind::Ident && self.slice(t.span) == "security")
    }

    /// True when the next token is the contextual keyword `limits` (an identifier
    /// literally spelled `limits`), introducing the request-body-size policy
    /// section.
    fn peek_is_limits_kw(&self) -> bool {
        matches!(self.peek(), Some(t) if t.kind == TokenKind::Ident && self.slice(t.span) == "limits")
    }

    /// Parse a `cors { name: value, … }` policy (v0.131, ADR 0159). Fields are
    /// parsed leniently as `name: expr` pairs; the checker validates the field
    /// names (closed set) and the value shapes. A trailing comma is allowed and
    /// newlines separate fields, mirroring a record construction.
    fn parse_cors_policy(&mut self, leading: Vec<String>) -> Result<CorsPolicy, CompileError> {
        let kw = self.expect_ident("to start a `cors` policy")?;
        self.expect(TokenKind::LBrace, "to open the `cors` policy body")?;
        let mut fields: Vec<CorsField> = Vec::new();
        loop {
            self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => break,
                Some(_) => {
                    let name = self.expect_ident("as a `cors` policy field name")?;
                    self.expect(TokenKind::Colon, "after the `cors` field name")?;
                    let value = self.parse_expr()?;
                    let span = name.span.merge(value.span);
                    fields.push(CorsField { name, value, span });
                    let _ = self.eat(TokenKind::Comma);
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the `cors` policy, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the `cors` policy body")?;
        Ok(CorsPolicy {
            fields,
            span: kw.span.merge(close.span),
            trivia: Trivia {
                leading,
                trailing: self.take_trailing_trivia(),
            },
        })
    }

    /// Parse a `security { name: value, … }` policy (v0.141, ADR 0164). Fields are
    /// parsed leniently as `name: expr` pairs; the checker validates the field
    /// names (closed set `hsts`/`nosniff`) and the value shapes. A trailing comma
    /// is allowed and newlines separate fields, mirroring `parse_cors_policy`.
    fn parse_security_policy(
        &mut self,
        leading: Vec<String>,
    ) -> Result<SecurityPolicy, CompileError> {
        let kw = self.expect_ident("to start a `security` policy")?;
        self.expect(TokenKind::LBrace, "to open the `security` policy body")?;
        let mut fields: Vec<SecurityField> = Vec::new();
        loop {
            self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => break,
                Some(_) => {
                    let name = self.expect_ident("as a `security` policy field name")?;
                    self.expect(TokenKind::Colon, "after the `security` field name")?;
                    let value = self.parse_expr()?;
                    let span = name.span.merge(value.span);
                    fields.push(SecurityField { name, value, span });
                    let _ = self.eat(TokenKind::Comma);
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the `security` policy, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the `security` policy body")?;
        Ok(SecurityPolicy {
            fields,
            span: kw.span.merge(close.span),
            trivia: Trivia {
                leading,
                trailing: self.take_trailing_trivia(),
            },
        })
    }

    /// Parse a `limits { name: value, … }` policy (v0.142, ADR 0165). Fields are
    /// parsed leniently as `name: expr` pairs; the checker validates the field
    /// names (closed set `maxBody`) and the value shapes (a positive `Int`). A
    /// trailing comma is allowed and newlines separate fields, mirroring
    /// `parse_cors_policy`/`parse_security_policy`.
    fn parse_limits_policy(&mut self, leading: Vec<String>) -> Result<LimitsPolicy, CompileError> {
        let kw = self.expect_ident("to start a `limits` policy")?;
        self.expect(TokenKind::LBrace, "to open the `limits` policy body")?;
        let mut fields: Vec<LimitsField> = Vec::new();
        loop {
            self.collect_item_lead();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => break,
                Some(_) => {
                    let name = self.expect_ident("as a `limits` policy field name")?;
                    self.expect(TokenKind::Colon, "after the `limits` field name")?;
                    let value = self.parse_expr()?;
                    let span = name.span.merge(value.span);
                    fields.push(LimitsField { name, value, span });
                    let _ = self.eat(TokenKind::Comma);
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the `limits` policy, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the `limits` policy body")?;
        Ok(LimitsPolicy {
            fields,
            span: kw.span.merge(close.span),
            trivia: Trivia {
                leading,
                trailing: self.take_trailing_trivia(),
            },
        })
    }

    /// Parse the optional `from <protocol>` header clause (v0.44). Absent ⇒
    /// `Call` (the contract-mediated internal-RPC default). `from queue("name")`
    /// carries its bound queue; `from http`/`from cron` carry no binding.
    fn parse_service_protocol(&mut self) -> Result<ServiceProtocol, CompileError> {
        if self.eat(TokenKind::From).is_none() {
            return Ok(ServiceProtocol::Call);
        }
        match self.peek_kind() {
            Some(TokenKind::Http) => {
                self.bump();
                Ok(ServiceProtocol::Http)
            }
            Some(TokenKind::Cron) => {
                self.bump();
                Ok(ServiceProtocol::Cron)
            }
            Some(TokenKind::Queue) => {
                self.bump();
                self.expect(
                    TokenKind::LParen,
                    "expected a queue binding `(\"name\")` after `from queue`",
                )?;
                let name_tok = self.expect(
                    TokenKind::StrLit,
                    "expected the bound queue name as a string literal",
                )?;
                let name = parse_string_literal(self.slice(name_tok.span), name_tok.span)?;
                self.expect(TokenKind::RParen, "to close the queue binding")?;
                Ok(ServiceProtocol::Queue { name })
            }
            // v0.103 (real-time track slice 3): `from WebSocket(in: T, out: T)`.
            // `WebSocket` is a contextual identifier (not a keyword), like the
            // built-in type names.
            Some(TokenKind::Ident)
                if self
                    .peek()
                    .is_some_and(|t| self.slice(t.span) == "WebSocket") =>
            {
                self.bump();
                self.expect(
                    TokenKind::LParen,
                    "expected `(in: ClientFrame, out: ServerFrame)` after `from WebSocket`",
                )?;
                let in_label = self.expect_ident("expected `in:` in the WebSocket header")?;
                if in_label.name != "in" {
                    return Err(CompileError::new(
                        "bynk.service.websocket_header",
                        in_label.span,
                        "the WebSocket header binds frame types as `in: <type>, out: <type>`",
                    ));
                }
                self.expect(TokenKind::Colon, "after `in`")?;
                let in_type = self.parse_type_ref("as the WebSocket `in:` frame type")?;
                self.expect(TokenKind::Comma, "between the `in:` and `out:` frame types")?;
                let out_label = self.expect_ident("expected `out:` in the WebSocket header")?;
                if out_label.name != "out" {
                    return Err(CompileError::new(
                        "bynk.service.websocket_header",
                        out_label.span,
                        "the WebSocket header binds frame types as `in: <type>, out: <type>`",
                    ));
                }
                self.expect(TokenKind::Colon, "after `out`")?;
                let out_type = self.parse_type_ref("as the WebSocket `out:` frame type")?;
                self.expect(TokenKind::RParen, "to close the WebSocket header")?;
                Ok(ServiceProtocol::WebSocket { in_type, out_type })
            }
            _ => {
                let (span, found) = match self.peek() {
                    Some(t) => (t.span, t.kind.describe()),
                    None => (self.eof_span(), "end of file"),
                };
                Err(CompileError::new(
                    "bynk.service.unknown_protocol",
                    span,
                    format!(
                        "unknown protocol after `from` — found {found}, expected `http`, `cron`, `queue`, or `WebSocket`"
                    ),
                )
                .with_note(
                    "protocols are a closed set; Kafka and MQTT are transports, not protocols — \
                     use `from queue` and bind the broker at the platform layer",
                ))
            }
        }
    }

    fn parse_agent_decl(&mut self) -> Result<AgentDecl, CompileError> {
        let kw = self.expect(TokenKind::Agent, "to start an agent declaration")?;
        let name = self.expect_ident("after `agent`")?;
        self.expect(TokenKind::LBrace, "to open the agent body")?;
        // key id: Type
        // The `key` keyword is recognised as an identifier with the literal
        // name "key" — we don't have a dedicated keyword so it can be a
        // method name elsewhere. v0.5 reserves it only inside an agent body.
        let key_ident =
            self.expect_ident("expected `key id: Type` at the start of the agent body")?;
        if key_ident.name != "key" {
            return Err(CompileError::new(
                "bynk.parse.expected_agent_key",
                key_ident.span,
                format!(
                    "expected `key id: Type` at the start of the agent body, found `{}`",
                    key_ident.name
                ),
            ));
        }
        let key_name = self.expect_ident("as the agent key field name")?;
        self.expect(TokenKind::Colon, "after the agent key field name")?;
        let key_type = self.parse_type_ref("as the agent key type")?;
        // Agent body — a pinned four-phase parse (identity → storage → contracts
        // → behaviour). v0.81 (storage track): the storage phase is the legacy
        // `state { }` block and/or the successor `store` fields, which coexist
        // during the track (ADR 0108 D3). All body items are doc-prefixed, so a
        // single loop collects the lead once and dispatches; ordering guards keep
        // the phases pinned (storage before contracts/behaviour; invariants before
        // handlers).
        let mut store_fields: Vec<StoreField> = Vec::new();
        let mut invariants = Vec::new();
        let mut transitions = Vec::new();
        let mut handlers = Vec::new();
        loop {
            let (leading, item_doc) = self.collect_item_lead();
            let storage_closed =
                !invariants.is_empty() || !transitions.is_empty() || !handlers.is_empty();
            match self.peek_kind() {
                Some(TokenKind::RBrace) => {
                    if let Some((_, doc_span)) = item_doc {
                        self.warnings.push(CompileError::new(
                            "bynk.parse.orphan_doc_block",
                            doc_span,
                            "documentation block has no following declaration to attach to",
                        ));
                    }
                    break;
                }
                // `store` is a contextual keyword (like `key`): the literal
                // identifier `store` in agent-body item position introduces a
                // store field, so it stays usable as an ordinary identifier
                // elsewhere (e.g. a `cache.store` context).
                Some(TokenKind::Ident) if self.peek_is_store_kw() => {
                    if storage_closed {
                        return Err(self.storage_after_phase_err());
                    }
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut sf = self.parse_store_field()?;
                    sf.documentation = doc;
                    sf.trivia.leading = leading;
                    sf.trivia.trailing = self.take_trailing_trivia();
                    store_fields.push(sf);
                }
                Some(TokenKind::Invariant) => {
                    if !handlers.is_empty() {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.invariant_after_handler",
                            t.span,
                            "an `invariant` must be declared before the agent's handlers",
                        )
                        .with_note(
                            "invariants form a phase between the storage fields and the \
                             `on` handlers; move this invariant above the first handler",
                        ));
                    }
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut inv = self.parse_invariant()?;
                    inv.documentation = doc;
                    inv.trivia.leading = leading;
                    inv.trivia.trailing = self.take_trailing_trivia();
                    invariants.push(inv);
                }
                Some(TokenKind::Transition) => {
                    if !handlers.is_empty() {
                        let t = self.peek().unwrap();
                        return Err(CompileError::new(
                            "bynk.parse.transition_after_handler",
                            t.span,
                            "a `transition` must be declared before the agent's handlers",
                        )
                        .with_note(
                            "step invariants form a phase between the storage fields and the \
                             `on` handlers (beside `invariant`); move this transition above the \
                             first handler",
                        ));
                    }
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut tr = self.parse_transition()?;
                    tr.documentation = doc;
                    tr.trivia.leading = leading;
                    tr.trivia.trailing = self.take_trailing_trivia();
                    transitions.push(tr);
                }
                // Handler-position annotations before an agent handler parse
                // uniformly (v0.140); validation rejects `@cache` on a non-HTTP
                // handler, keeping the grammar permissive and the diagnostic precise.
                Some(TokenKind::At) => {
                    let annotations = self.parse_handler_annotations()?;
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut h = self.parse_handler(true, annotations)?;
                    h.documentation = doc;
                    h.trivia.leading = leading;
                    h.trivia.trailing = self.take_trailing_trivia();
                    handlers.push(h);
                }
                Some(TokenKind::On) => {
                    let next_span = self.peek().unwrap().span;
                    let doc = self.finalize_doc(item_doc, next_span);
                    let mut h = self.parse_handler(true, Vec::new())?;
                    h.documentation = doc;
                    h.trivia.leading = leading;
                    h.trivia.trailing = self.take_trailing_trivia();
                    handlers.push(h);
                }
                Some(_) => {
                    let t = self.peek().unwrap();
                    return Err(CompileError::new(
                        "bynk.parse.expected_handler",
                        t.span,
                        format!(
                            "expected `on` to start a handler, found {}",
                            t.kind.describe()
                        ),
                    ));
                }
                None => {
                    return Err(CompileError::new(
                        "bynk.parse.unexpected_eof",
                        self.eof_span(),
                        "expected `}` to close the agent body, found end of file",
                    ));
                }
            }
        }
        let close = self.expect(TokenKind::RBrace, "to close the agent body")?;
        if store_fields.is_empty() {
            return Err(CompileError::new(
                "bynk.parse.expected_agent_storage",
                kw.span.merge(close.span),
                "an agent must declare its storage — it has no `store` fields",
            ));
        }
        if handlers.is_empty() {
            return Err(CompileError::new(
                "bynk.parse.empty_agent",
                kw.span.merge(close.span),
                "an agent must declare at least one handler",
            ));
        }
        Ok(AgentDecl {
            name,
            key_name,
            key_type,
            store_fields,
            invariants,
            transitions,
            handlers,
            documentation: None,
            span: kw.span.merge(close.span),
            trivia: Trivia::default(),
        })
    }

    /// The error for a `state`/`store` declaration appearing after the agent's
    /// invariants or handlers (the storage phase must come first).
    fn storage_after_phase_err(&self) -> CompileError {
        let t = self.peek().unwrap();
        CompileError::new(
            "bynk.parse.storage_after_phase",
            t.span,
            "agent storage (`state` / `store`) must be declared before the invariants and handlers",
        )
        .with_note("the agent body is ordered: key → storage → invariants → handlers")
    }

    /// Parse a single `store` field (v0.81): `store <name>: <Kind>[…] [= init]`.
    /// The kind is an ordinary type reference (`Cell[Int]`, `Map[K, V]`); the
    /// checker restricts which heads are storage kinds. Doc/trivia are attached
    /// by the caller. Access-pattern annotations are deferred (storage track Q3).
    /// True when the next token is the contextual keyword `store` (an identifier
    /// literally spelled `store`), introducing a storage-kind field.
    fn peek_is_store_kw(&self) -> bool {
        matches!(self.peek(), Some(t) if t.kind == TokenKind::Ident && self.slice(t.span) == "store")
    }

    fn parse_store_field(&mut self) -> Result<StoreField, CompileError> {
        let kw = self.expect_ident("to start a `store` field")?;
        let name = self.expect_ident("expected the store field name after `store`")?;
        self.expect(TokenKind::Colon, "after the store field name")?;
        let kind = self.parse_store_kind()?;
        let mut end = kind.span;
        // v0.85 (ADR 0111): zero or more `@name(args)` annotations sit between the
        // storage kind and the `=` initialiser. The name is any identifier (the
        // checker matches it against the closed registry), so an unknown
        // annotation is a checker diagnostic rather than a parse error.
        let mut annotations = Vec::new();
        while self.peek_kind() == Some(TokenKind::At) {
            let ann = self.parse_annotation()?;
            end = ann.span;
            annotations.push(ann);
        }
        let init = if self.eat(TokenKind::Eq).is_some() {
            let e = self.parse_expr()?;
            end = e.span;
            Some(e)
        } else {
            None
        };
        Ok(StoreField {
            name,
            kind,
            annotations,
            init,
            documentation: None,
            span: kw.span.merge(end),
            trivia: Trivia::default(),
        })
    }

    /// Consume a run of one or more handler-position annotations (v0.140, ADR
    /// 0163) — `@cache(maxAge: 5.minutes) @…` — sitting between a handler's doc
    /// block and its `on`. Reuses [`parse_annotation`] (shared with `store`
    /// fields, ADR 0111); the caller has already confirmed the leading `@`. The
    /// next token must open a handler — a dangling annotation with no `on` is a
    /// parse error, so the annotation surface can never silently attach to nothing.
    fn parse_handler_annotations(&mut self) -> Result<Vec<Annotation>, CompileError> {
        let mut annotations = Vec::new();
        while self.peek_kind() == Some(TokenKind::At) {
            annotations.push(self.parse_annotation()?);
        }
        if self.peek_kind() != Some(TokenKind::On) {
            let span = self
                .peek()
                .map(|t| t.span)
                .unwrap_or_else(|| self.eof_span());
            let found = self
                .peek()
                .map(|t| t.kind.describe())
                .unwrap_or("end of file");
            return Err(CompileError::new(
                "bynk.parse.dangling_handler_annotation",
                span,
                format!("expected `on` to start the annotated handler, found {found}"),
            )
            .with_note(
                "a handler annotation (e.g. `@cache(maxAge: 5.minutes)`) must sit immediately before an `on` handler",
            ));
        }
        Ok(annotations)
    }

    /// Parse one storage annotation (v0.85; ADR 0111): `@<name>` or
    /// `@<name>(<arg>, …)`. Each argument is an optional `label:` then a value
    /// expression (`by: orderId`, `5.minutes`). The empty `@name()` form is
    /// accepted and yields no arguments.
    fn parse_annotation(&mut self) -> Result<Annotation, CompileError> {
        let at = self.expect(TokenKind::At, "to start a storage annotation")?;
        let name = self.expect_ident("expected an annotation name after `@`")?;
        let mut end = name.span;
        let mut args = Vec::new();
        if self.eat(TokenKind::LParen).is_some() {
            if self.peek_kind() != Some(TokenKind::RParen) {
                loop {
                    args.push(self.parse_annotation_arg()?);
                    if self.eat(TokenKind::Comma).is_none() {
                        break;
                    }
                }
            }
            let close =
                self.expect(TokenKind::RParen, "to close the annotation's argument list")?;
            end = close.span;
        }
        Ok(Annotation {
            name,
            args,
            span: at.span.merge(end),
        })
    }

    /// Parse one annotation argument: an optional `label:` prefix then a value
    /// expression. A word directly followed by `:` is a label (`by: orderId`);
    /// anything else is a positional value (`5.minutes`). The label word may be a
    /// reserved keyword (`by` is one), so it is taken by lexeme rather than via
    /// [`expect_ident`] — annotation labels are a closed metadata vocabulary, not
    /// expression identifiers.
    fn parse_annotation_arg(&mut self) -> Result<AnnotationArg, CompileError> {
        let label = if self.peek_annotation_label() {
            let tok = self.bump().unwrap();
            let label = Ident {
                name: self.slice(tok.span).to_string(),
                span: tok.span,
            };
            self.expect(TokenKind::Colon, "after an annotation argument label")?;
            Some(label)
        } else {
            None
        };
        let value = self.parse_expr()?;
        let span = label
            .as_ref()
            .map(|l| l.span.merge(value.span))
            .unwrap_or(value.span);
        Ok(AnnotationArg { label, value, span })
    }

    /// True when the cursor is on an alphabetic word immediately followed by `:`
    /// — the `label:` form of an annotation argument. Accepts keyword tokens
    /// (e.g. `by`) since labels are not expression identifiers.
    fn peek_annotation_label(&self) -> bool {
        let Some(tok) = self.peek() else { return false };
        if self.tokens.get(self.pos + 1).map(|t| t.kind) != Some(TokenKind::Colon) {
            return false;
        }
        self.slice(tok.span)
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic())
    }

    /// Parse a storage kind applied to its element type(s): `Cell[Int]`,
    /// `Map[K, V]`, or a bare head. The head is any identifier; the checker
    /// restricts it to the closed kind catalogue.
    fn parse_store_kind(&mut self) -> Result<StoreKind, CompileError> {
        let head = self.expect_ident("as the storage kind (e.g. `Cell`, `Map`, `Log`)")?;
        let head_span = head.span;
        let mut end = head_span;
        let mut args = Vec::new();
        if self.eat(TokenKind::LBracket).is_some() {
            loop {
                args.push(self.parse_type_ref("as a storage-kind type argument")?);
                if self.eat(TokenKind::Comma).is_none() {
                    break;
                }
            }
            let close = self.expect(
                TokenKind::RBracket,
                "to close the storage-kind type arguments",
            )?;
            end = close.span;
        }
        Ok(StoreKind {
            head,
            args,
            span: head_span.merge(end),
        })
    }

    /// Parse a single invariant declaration (v0.80): `invariant <name>: <expr>`.
    /// The predicate is an ordinary expression (with `implies`/`is`) over the
    /// agent's state fields; well-formedness is the checker's job. Doc and
    /// trivia are attached by the caller (the inline-declaration doc convention).
    fn parse_invariant(&mut self) -> Result<Invariant, CompileError> {
        let kw = self.expect(TokenKind::Invariant, "to start an invariant declaration")?;
        let name = self.expect_ident("expected the invariant name after `invariant`")?;
        self.expect(TokenKind::Colon, "after the invariant name")?;
        let predicate = self.parse_expr()?;
        let span = kw.span.merge(predicate.span);
        Ok(Invariant {
            name,
            predicate,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }

    /// Parse a step invariant: `transition <name>: <predicate>` (v0.116, testing
    /// track slice 4). Mirrors [`parse_invariant`], but the predicate ranges over
    /// the contextual `old`/`new` state pair rather than the bare state fields.
    fn parse_transition(&mut self) -> Result<Transition, CompileError> {
        let kw = self.expect(TokenKind::Transition, "to start a transition declaration")?;
        let name = self.expect_ident("expected the transition name after `transition`")?;
        self.expect(TokenKind::Colon, "after the transition name")?;
        let predicate = self.parse_expr()?;
        let span = kw.span.merge(predicate.span);
        Ok(Transition {
            name,
            predicate,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }

    /// Parse a handler block.
    ///
    /// Service handlers are `on call(args) -> T given C1, C2 { body }`.
    /// Agent handlers are `on call methodName(args) -> T given C1, C2 { body }`,
    /// where the method name is the agent operation invoked on an instance.
    /// Parse one handler, `on <form>(…) [by …] (params) -> T [given …] { body }`.
    /// Any handler-position annotations (`@cache(…)`, v0.140) were consumed by the
    /// caller from the token stream *before* the `on` and are threaded in here — the
    /// grammar accepts them uniformly, and project validation gates each to its
    /// legal position (e.g. `@cache` only on `on GET`).
    fn parse_handler(
        &mut self,
        is_agent: bool,
        annotations: Vec<Annotation>,
    ) -> Result<Handler, CompileError> {
        let kw = self.expect(TokenKind::On, "to start a handler")?;
        // v0.44: the handler form is a single ident after `on` — `call`, an
        // HTTP method-builder (`GET("/route")`), `schedule("expr")`, or
        // `message(...)`. The protocol lives on the service header; the checker
        // verifies the form matches it.
        let kind_ident = self.expect_ident(
            "expected a handler form (e.g. `call`, `GET`, `schedule`, `message`) after `on`",
        )?;
        let kind = match kind_ident.name.as_str() {
            "call" => HandlerKind::Call,
            "message" => HandlerKind::Message,
            // v0.103: the WebSocket upgrade handler — `on open by … (params) …`.
            "open" => HandlerKind::Open,
            // v0.106 (slice 3b-iii): the WebSocket close handler. (`on message` on a
            // `from WebSocket` service reuses `HandlerKind::Message`; the checker
            // disambiguates the queue and WebSocket forms by the service protocol.)
            "close" => HandlerKind::Close,
            "schedule" => {
                self.expect(TokenKind::LParen, "before the cron schedule expression")?;
                let expr_tok = self.expect(
                    TokenKind::StrLit,
                    "expected a cron expression string literal in `schedule(\"\")`",
                )?;
                let expr = parse_string_literal(self.slice(expr_tok.span), expr_tok.span)?;
                self.expect(TokenKind::RParen, "to close the schedule expression")?;
                HandlerKind::Cron { expr }
            }
            method if HttpMethod::from_ident(method).is_some() => {
                let method = HttpMethod::from_ident(method).unwrap();
                self.expect(TokenKind::LParen, "before the route pattern")?;
                let path_tok = self.expect(
                    TokenKind::StrLit,
                    "expected a route pattern string literal in `GET(\"\")`",
                )?;
                let path = parse_string_literal(self.slice(path_tok.span), path_tok.span)?;
                self.expect(TokenKind::RParen, "to close the route pattern")?;
                HandlerKind::Http { method, path }
            }
            other => {
                return Err(CompileError::new(
                    "bynk.parse.unknown_handler_kind",
                    kind_ident.span,
                    format!(
                        "unknown handler form `{other}` — expected `call`, an HTTP method (`GET`/`POST`/`PUT`/`PATCH`/`DELETE`), `schedule`, or `message`"
                    ),
                )
                .with_note(
                    "use `on call(...)`, `on GET(\"/path\") (...)`, `on schedule(\"expr\") (...)`, or `on message(m: T)`",
                ));
            }
        };
        // Only `on call` handlers are valid inside an agent.
        if is_agent && !matches!(kind, HandlerKind::Call) {
            return Err(CompileError::new(
                "bynk.parse.handler_in_agent",
                kind_ident.span,
                "only `on call` handlers are valid inside an `agent`; protocol handlers belong on a `service`",
            )
            .with_note(
                "agents persist state and respond to `on call`; HTTP routes, schedules, and queue messages belong on services",
            ));
        }
        // Agent handlers have a method name before the parameter list:
        //   on call addItem(item: CartItem) -> ...
        // Service handlers have just the parameter list:
        //   on call(amount: Money) -> ...
        let method_name = if is_agent && self.peek_kind() == Some(TokenKind::Ident) {
            Some(self.expect_ident("as the agent handler operation name")?)
        } else {
            None
        };
        // v0.45/v0.50: the optional `by (<binder>:)? <Actor>` clause sits after
        // the protocol config and before the parameters. `by <name>: <Actor>`
        // captures the verified identity (read as `name.identity`);
        // `by <Actor>` declares-and-verifies the contract without capturing it
        // (anonymous / verify-and-discard). One-token lookahead on `:`
        // disambiguates.
        let by_clause = if self.peek_kind() == Some(TokenKind::By) {
            let by_kw = self.expect(TokenKind::By, "to start the handler actor clause")?;
            // `_` is not a valid binder — guide to the binder-less form.
            if self.peek_kind() == Some(TokenKind::Underscore) {
                let t = self.peek().unwrap();
                return Err(CompileError::new(
                    "bynk.parse.expected_token",
                    t.span,
                    "`_` is not a valid actor binder".to_string(),
                )
                .with_note("omit the binder for an anonymous handler — `by <Actor>`"));
            }
            let first = self.expect_ident("as the actor (or its binder) after `by`")?;
            // A `:` after the first name means it was the binder; otherwise the
            // first name *is* the actor (binder-less form).
            let (binder, mut actors) = if self.peek_kind() == Some(TokenKind::Colon) {
                self.bump();
                (
                    Some(first),
                    vec![self.expect_ident("as the actor contract name after `:`")?],
                )
            } else {
                (None, vec![first])
            };
            // v0.52: a `|`-separated list names an ordered sum of peer actors
            // (`by who: A | B`), resolved first-wins. One name is the ordinary
            // single-actor handler. The binder requirement for a sum is a
            // semantic rule (`bynk.actor.sum_requires_binder`), not a parse one.
            while self.eat(TokenKind::Pipe).is_some() {
                actors.push(self.expect_ident("as a peer actor after `|`")?);
            }
            let last = actors.last().unwrap();
            let span = by_kw.span.merge(last.span);
            Some(ByClause {
                binder,
                actors,
                span,
            })
        } else {
            None
        };
        self.expect(TokenKind::LParen, "before the handler parameter list")?;
        let mut params = Vec::new();
        if self.peek_kind() != Some(TokenKind::RParen) {
            params.push(self.parse_param()?);
            while self.eat(TokenKind::Comma).is_some() {
                params.push(self.parse_param()?);
            }
        }
        self.expect(TokenKind::RParen, "to close the handler parameter list")?;
        self.expect(TokenKind::Arrow, "before the handler return type")?;
        let return_type = self.parse_type_ref("as the handler return type")?;
        let mut given = Vec::new();
        if self.peek_kind() == Some(TokenKind::Given) {
            self.bump();
            given.push(self.parse_cap_ref()?);
            while self.eat(TokenKind::Comma).is_some() {
                given.push(self.parse_cap_ref()?);
            }
        }
        let body = self.parse_block("to open the handler body")?;
        let span = kw.span.merge(body.span);
        // The annotation span (when any) extends the handler's start so hover /
        // go-to-definition over the `@name` resolves to this handler.
        let span = match annotations.first() {
            Some(first) => first.span.merge(body.span),
            None => span,
        };
        Ok(Handler {
            kind,
            annotations,
            method_name,
            by_clause,
            params,
            return_type,
            given,
            body,
            documentation: None,
            span,
            trivia: Trivia::default(),
        })
    }
}