whipplescript-parser 0.5.5

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

use crate::{parse_expression, Diagnostic, Expr, SourceSpan};

/// Parses short durations: `<integer><unit>` with unit `s`, `m`, `h`, or `d`.
pub fn parse_short_duration_seconds(value: &str) -> Option<u64> {
    let unit = value.chars().last()?;
    let number = value.get(..value.len() - 1)?.parse::<u64>().ok()?;
    let multiplier = match unit {
        's' => 1,
        'm' => 60,
        'h' => 3600,
        'd' => 86400,
        _ => return None,
    };
    number.checked_mul(multiplier)
}

/// Structural ISO-8601 instant check (`YYYY-MM-DDTHH:MM:SS[.fff](Z|±HH:MM)`)
/// for `time` literals, with calendar-field range validation. Kept
/// dependency-free: the runtime compares instants via SQLite `strftime`.
pub fn is_iso8601_instant(value: &str) -> bool {
    let bytes = value.as_bytes();
    let digits = |range: std::ops::Range<usize>| {
        bytes
            .get(range)
            .is_some_and(|slice| !slice.is_empty() && slice.iter().all(u8::is_ascii_digit))
    };
    let field = |range: std::ops::Range<usize>| -> u32 {
        value
            .get(range)
            .and_then(|text| text.parse().ok())
            .unwrap_or(u32::MAX)
    };
    if !(digits(0..4) && bytes.get(4) == Some(&b'-') && digits(5..7))
        || bytes.get(7) != Some(&b'-')
        || !digits(8..10)
        || bytes.get(10) != Some(&b'T')
        || !digits(11..13)
        || bytes.get(13) != Some(&b':')
        || !digits(14..16)
        || bytes.get(16) != Some(&b':')
        || !digits(17..19)
    {
        return false;
    }
    if !(1..=12).contains(&field(5..7))
        || !(1..=31).contains(&field(8..10))
        || field(11..13) > 23
        || field(14..16) > 59
        || field(17..19) > 60
    {
        return false;
    }
    let mut index = 19;
    if bytes.get(index) == Some(&b'.') {
        index += 1;
        let start = index;
        while bytes.get(index).is_some_and(u8::is_ascii_digit) {
            index += 1;
        }
        if index == start {
            return false;
        }
    }
    match bytes.get(index) {
        Some(b'Z') => index + 1 == bytes.len(),
        Some(b'+') | Some(b'-') => {
            digits(index + 1..index + 3)
                && bytes.get(index + 3) == Some(&b':')
                && digits(index + 4..index + 6)
                && index + 6 == bytes.len()
                && field(index + 1..index + 3) <= 23
                && field(index + 4..index + 6) <= 59
        }
        _ => false,
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BodyAst {
    pub statements: Vec<BodyStmt>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BodyStmt {
    Record(RecordStmt),
    /// `done x` / `done x -> record ...` — marks a fact terminal, optionally
    /// replacing it with a record.
    Done {
        binding: String,
        replacement: Option<RecordStmt>,
        span: SourceSpan,
    },
    Effect(EffectStmt),
    After(AfterBlock),
    Region(RegionBlock),
    Case(CaseBlock),
    Terminal(TerminalStmt),
    Cancel {
        binding: String,
        span: SourceSpan,
    },
    /// `emit milestone "<name>" of <PayloadClass> { fields }` (Family C,
    /// child-milestone lifecycle): a synchronous durable fact the child workflow
    /// projects mid-flight for an observing parent. It is NOT an async effect —
    /// it derives a `workflow.milestone:<name>` fact in the child's own base at
    /// rule-commit time, mirroring `record`. `payload_class` types the parent's
    /// `after p reaches "<name>" as m` binding. See
    /// spec/decision-records/discriminated-families-design.md section 7.3.
    Milestone {
        name: String,
        payload_class: Option<String>,
        fields: Vec<FieldAssign>,
        span: SourceSpan,
    },
    /// `redact <source> keep [<field>, …] as <out>` (DR-0027 redact): an explicit,
    /// audited PROJECTION of the record bound to `source` onto the kept field set,
    /// producing a new binding `out`. It is the information-flow crossing the
    /// rule-level opaque join box is refined at — the projection carries only the
    /// labels of the KEPT fields (the dropped fields are non-interfering, proven in
    /// models/lean/Whipple/Redaction.lean: `canRead_redact`). It is NOT an async
    /// effect: it is a synchronous, pure restructure (like a record projection), so
    /// it never becomes an `IrEffectKind` — it is rule metadata the IFC checker and
    /// the runtime projection both read. `out`'s type is the source schema projected
    /// to the kept fields (`redact.<rule>.<out>`); accessing a dropped field on `out`
    /// is a type error.
    Redact {
        source: String,
        keep: Vec<String>,
        binding: String,
        span: SourceSpan,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecordStmt {
    pub schema: String,
    pub from: Option<String>,
    pub fields: Vec<FieldAssign>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldAssign {
    pub name: String,
    pub value: FieldValue,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FieldValue {
    /// Bare field in a `from` block: copy the same-named field.
    Shorthand,
    /// An expression, kept with its exact source text for template
    /// rendering and lowering compatibility.
    Expr { source: String, expr: Expr },
    /// Nested typed payload, e.g. invoke input: `phase PhaseReview { ... }`.
    Nested {
        schema: String,
        fields: Vec<FieldAssign>,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EffectStmt {
    pub kind: BodyEffectKind,
    pub binding: Option<String>,
    pub requires: Vec<String>,
    /// `timeout <duration>` in seconds, creation-anchored.
    pub timeout_seconds: Option<u64>,
    pub prompt: Option<Prompt>,
    pub span: SourceSpan,
}

/// Access grant metadata (`with access to <resource> { <grant clauses> }`) on an
/// effect. On `tell`, it narrows the turn's effective authority per Proposal A
/// (spec/agent-harness.md). On `invoke`, it is the explicit start-grant surface for
/// narrowing the child workflow's authority.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessGrant {
    pub resource: String,
    pub operations: Vec<AccessGrantOp>,
    pub span: SourceSpan,
}

/// One operation clause inside a turn-access grant block — an operation name with its
/// optional `for <target>` reference and/or `["glob", …]` path patterns (e.g.
/// `recall for issue`, `read ["docs/**"]`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessGrantOp {
    pub operation: String,
    pub target: Option<String>,
    pub globs: Vec<String>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BodyEffectKind {
    Tell {
        target: String,
        access_grants: Vec<AccessGrant>,
        /// Turn-scoped `with skills [...]` (context-assembly Phase 7): skills pinned
        /// into this turn's provenance. Does NOT filter the discover-all catalogue.
        skills: Vec<String>,
        /// `on stream <name>` (std.vcs, DR-0052 Decision 5): the per-turn
        /// homing exception — this turn's bound line homes to the named
        /// stream instead of the agent's declared membership.
        on_stream: Option<String>,
    },
    Coerce {
        name: String,
        args: Vec<String>,
        /// the `endorsed` source marker (DR-0027 I-IFC3): the author declares this
        /// coerce is an integrity-raising crossing, making the trusted surface
        /// visible at the crossing point. Authorization still lives in governance.
        endorsed: bool,
        /// the `declassified` source marker (DR-0027 I-IFC3): the author declares
        /// this coerce a confidentiality-lowering crossing. The coerce's OUTPUT
        /// SCHEMA is the bounded type that bounds the leak — you cannot declassify
        /// without passing through a bounded type. Authorization lives in governance.
        declassified: bool,
    },
    /// Bare free-text model prompt: `prompt "<text>" [using <provider>] as x`.
    /// It lowers through the same model/backend path as `coerce`, but its
    /// completed value is a plain string.
    Prompt {
        provider: Option<String>,
    },
    /// Inline anonymous coercion: `decide "<prompt>" -> { field type, ... } as x`.
    Decide {
        result_fields: Vec<(String, String)>,
    },
    Call {
        capability: String,
        argument: Option<String>,
    },
    ConstructCapabilityCall {
        keyword: String,
        target_capability: String,
        fields: Vec<ConstructUseField>,
    },
    Invoke {
        workflow: String,
        payload: Vec<FieldAssign>,
        access_grants: Vec<AccessGrant>,
    },
    Timer {
        duration_seconds: u64,
        duration_source: String,
        /// Absolute deadline expression (a time literal or a time-typed
        /// path); `None` for a relative `timer <duration>`.
        until: Option<String>,
    },
    Exec {
        target: ExecTarget,
        /// `-> Schema` / `-> each Schema`: deterministic JSON ingestion of
        /// stdout at the effect-result boundary (spec/json-ingestion.md).
        parse_target: Option<ExecParse>,
    },
    /// Work-queue verbs (`file issue into q { ... }`, `claim x`, `release x`,
    /// `finish x [{ ... }]`).
    TrackerFile {
        queue: String,
        fields: Vec<FieldAssign>,
    },
    TrackerClaim {
        item: String,
        /// `ttl <duration>`: the claim-TTL, in seconds. `Some(n)` records a
        /// timed lease (`expires_at = now + n`) that `ready`/`claim` reclaim
        /// once past-due; `None` is the untimed backstop lease (T3).
        ttl_seconds: Option<u64>,
        /// The `endorsed` source marker (DR-0051 §2), the same crossing
        /// `coerce … endorsed` carries: the author declares that adopting this
        /// party's decision is the integrity raise. Honoured only when the
        /// claimed tracker is itself vouched (§3) — otherwise an agent could
        /// file its own issue and claim it, laundering its own output through a
        /// two-step it fully controls.
        endorsed: bool,
    },
    TrackerRelease {
        item: String,
    },
    TrackerFinish {
        item: String,
        fields: Vec<FieldAssign>,
    },
    /// Coordination verbs (spec/coordination.md): one atomic attempt each,
    /// with branchable sum-typed outcomes.
    LeaseAcquire {
        resource: String,
        key_expr: String,
        /// `until ttl`: fire-and-forget; TTL is the sole release.
        until_ttl: bool,
        /// `wait <duration>`: bounded retry on contention. `Some(seconds)` retries
        /// the acquire until it is `held` or the wait elapses (then `contended`);
        /// `None` reports `contended` on the first attempt.
        wait_seconds: Option<u64>,
    },
    /// `renew <acquire-binding> [until <ttl>] as <b>`: extend a held lease's
    /// TTL before it expires (spec/coordination.md). Names the acquire's `as`
    /// binding and works on the same lease; `Renewed`/`NotHeld` outcomes.
    LeaseRenew {
        /// The `as` binding of the `acquire` this renew extends.
        acquire_binding: String,
        /// `until <duration>`: the new TTL in seconds. `None` reuses the
        /// acquire's declared TTL.
        ttl_seconds: Option<u64>,
    },
    LedgerAppend {
        ledger: String,
        schema: String,
        fields: Vec<FieldAssign>,
    },
    CounterConsume {
        counter: String,
        key_expr: String,
        amount_expr: String,
    },
    /// `emit signal <name> to <instance-expr> { payload }`: inject a typed,
    /// durable event into a known peer instance — directed fire-and-forget
    /// (spec/event-ingress.md, spec/coordination.md messaging).
    Notify {
        target_expr: String,
        event: String,
        /// S6: `emit signal <name> to <target> from <binding> { overrides }` —
        /// copy the source binding's same-named fields (bounded to the signal's
        /// declared fields), with the block overriding; mirrors `record … from`.
        from: Option<String>,
        fields: Vec<FieldAssign>,
    },
    /// `read <format> from <store> at <path> as <binding>` (std.files): a typed
    /// file read lowering through `typed_effect_call`. v0 paths are literal
    /// strings.
    FileRead {
        format: String,
        store: String,
        path: String,
    },
    /// `write <format> to <store> at <path> { body <expr> mode <mode> } as
    /// <binding>` (std.files): a typed file write lowering through
    /// `typed_effect_call`. v0 formats are `text`/`markdown` body codecs; the
    /// `mode` (create/replace/upsert/append) is required (no silent overwrite),
    /// and `body` is an expression resolved at effect-input time.
    FileWrite {
        format: String,
        store: String,
        path: String,
        body: String,
        mode: String,
    },
    /// `import <format> <Schema> from <store> at <path> as <binding>`
    /// (std.files): decode a structured file into typed `<Schema>` facts (one per
    /// row) via the platform fact-batch admission primitive. v0 formats are
    /// `jsonl`/`json`/`csv`.
    FileImport {
        format: String,
        schema: String,
        store: String,
        path: String,
    },
    /// `export <format> <Schema> to <store> at <path> { [where <pred>] mode
    /// <mode> } as <binding>` (std.files): serialize the collection of `<Schema>`
    /// facts (optionally filtered by `where`, per DR-0022 collection-valued
    /// projections) to a structured file. v0 formats are `jsonl`/`json`/`csv`;
    /// `mode` is required (no silent overwrite).
    FileExport {
        format: String,
        schema: String,
        store: String,
        path: String,
        predicate: Option<String>,
        mode: String,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConstructUseField {
    pub name: String,
    pub source: String,
}

// --- DR-0011 `effect_operation` meta-grammar (compiled-in table) -------------
//
// The shipped std package constructs (`recall`, `learn`, `curate`, `send`)
// share one rule-body shape: `<keyword> [<connective> <slot>]* [{
// <payload-field>* }]? as <binding>`. Rather than one hand-written parser per
// keyword, each is described by an `EffectOperationSpec` row and parsed
// generically by `parse_effect_operation`. The spec types below stay
// hand-written; the table const is generated by build.rs from the embedded std
// manifests' `grammar` objects (std/manifests/*.json — the single source of
// grammar). See spec/construct-grammar.md, "DR-0011 Two-Shape Meta-Grammar
// (S6 build)".

/// A slot's value kind: a bare identifier or a value expression.
#[derive(Clone, Copy, Debug)]
enum SlotKind {
    Identifier,
    Expression,
}

/// The trailing `as <binding>` policy for an effect operation. Both shipped
/// constructs require a binding; `Optional`/`None` complete the DR-0011 mode
/// vocabulary and are enforced by `parse_effect_operation` when a construct
/// registers them.
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
enum BindingMode {
    Required,
    Optional,
    None,
}

/// One ordered slot: a named value, optionally introduced by a fixed connective
/// word consumed before it (`recall <pool>` has none; `send via <channel>` uses
/// `via`). Connectives are drawn from {`from`, `for`, `into`, `to`, `via`}.
#[derive(Clone, Copy, Debug)]
struct EffectSlotSpec {
    name: &'static str,
    kind: SlotKind,
    connective: Option<&'static str>,
}

/// One field inside the optional `{ ... }` payload block: a named expression,
/// required or not.
#[derive(Clone, Copy, Debug)]
struct PayloadFieldSpec {
    name: &'static str,
    required: bool,
}

/// The full grammar of one `effect_operation` construct.
#[derive(Clone, Copy, Debug)]
struct EffectOperationSpec {
    keyword: &'static str,
    slots: &'static [EffectSlotSpec],
    payload: Option<&'static [PayloadFieldSpec]>,
    binding: BindingMode,
    target_capability: &'static str,
}

// The table itself is generated at build time from the canonical embedded std
// manifests (std/manifests/*.json) by build.rs: each construct's DR-0011
// `grammar` object transcribes into one `EffectOperationSpec` row, so the
// manifests are the single source of parse grammar and the table can never
// drift from them.
include!(concat!(env!("OUT_DIR"), "/effect_operation_grammar.rs"));

/// Look up the `effect_operation` grammar for a leading rule-body keyword.
fn effect_operation_spec(keyword: &str) -> Option<&'static EffectOperationSpec> {
    EFFECT_OPERATION_GRAMMAR
        .iter()
        .find(|spec| spec.keyword == keyword)
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExecTarget {
    RawCommand(String),
    Capability { name: String, stdin_binding: String },
}

/// The `->` ingestion contract on an `exec`: stdout must parse as `schema`
/// (one object) or, with `each`, as a JSONL/array stream of `schema`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExecParse {
    pub schema: String,
    pub each: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Prompt {
    pub text: String,
    pub content_type: Option<String>,
}

/// DR-0043 Decision 5: a `during <cond> { … } on lapse [as x] { … }` region
/// (`until <cond>` is the negated polarity). The region's steps commit only
/// while the condition holds — checked atomically inside each advancing
/// commit — and the first advancing commit under a broken condition commits
/// the lapse arm instead, exactly once. Statements after the region are the
/// point of no return.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RegionBlock {
    /// `until` negates: the region runs while the condition is FALSE and
    /// lapses when it becomes true.
    pub until: bool,
    /// The condition's raw expression text (guard grammar; pure queries).
    pub condition: String,
    pub body: Vec<BodyStmt>,
    /// `on lapse as <binding>`: the synthesized optional progress view.
    pub lapse_binding: Option<String>,
    pub lapse_body: Vec<BodyStmt>,
    /// Source extent of the region BODY content (inside its braces), for the
    /// compile-path variant splices.
    pub body_span: SourceSpan,
    /// Source extent of the lapse-arm content (inside its braces).
    pub lapse_span: SourceSpan,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AfterBlock {
    pub binding: String,
    pub predicate: AfterPredicate,
    pub alias: Option<String>,
    /// For `after p reaches "<name>" as m`: the child milestone name being
    /// observed (Family C). `None` for every other predicate. The name lives
    /// here rather than on `AfterPredicate` so the predicate stays a fieldless
    /// `Copy` enum (see `AfterPredicate::Reaches`).
    pub milestone: Option<String>,
    pub body: Vec<BodyStmt>,
    pub span: SourceSpan,
}

impl AfterPredicate {
    /// The kernel text-scanner's spelling of this predicate (what
    /// `after <binding> <predicate>` looks like in body text).
    pub fn kernel_str(&self) -> &'static str {
        match self {
            AfterPredicate::Succeeds => "succeeds",
            AfterPredicate::Fails => "fails",
            AfterPredicate::Completes => "completes",
            AfterPredicate::Cancelled => "cancelled",
            AfterPredicate::TimedOut => "times out",
            AfterPredicate::Reaches => "reaches",
            AfterPredicate::Held => "held",
            AfterPredicate::Contended => "contended",
            AfterPredicate::Ok => "ok",
            AfterPredicate::Over => "over",
            AfterPredicate::Promoted => "promoted",
            AfterPredicate::Conflicted => "conflicted",
            AfterPredicate::Applied => "applied",
            AfterPredicate::Stranded => "stranded",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AfterPredicate {
    Succeeds,
    Fails,
    Completes,
    /// Terminal statuses from the canonical terminal union
    /// (spec/expression-kernel.md): the effect reached a non-success terminal
    /// state. `TimedOut` is spelled `times out`; `Cancelled` is `cancelled`.
    TimedOut,
    Cancelled,
    /// Coordination outcomes (spec/coordination.md): the effect completed
    /// and its sum-typed value carries the matching `variant`.
    Held,
    Contended,
    Ok,
    Over,
    /// std.vcs promotion outcomes (DR-0052 grammar pass, the acquire
    /// pattern one tier up): the boundary hop COMPLETES with variant
    /// Promoted|Conflicted — refusal is data, and `succeeds` is refused
    /// on a promote binding so no workflow proceeds "as if promoted" on
    /// a conflicted boundary.
    Promoted,
    Conflicted,
    /// std.vcs selective-verb outcomes (DR-0052 R4): `undo` and
    /// `transport` COMPLETE with Applied|Stranded / Applied|Conflicted —
    /// the proposal landed, or the dependency-closure / certified
    /// precondition refused, as data. Same enforcement as
    /// promote/acquire.
    Applied,
    Stranded,
    /// `after p reaches "<name>" as m` (Family C, child-milestone lifecycle): the
    /// invoked child workflow `p` projected the named milestone mid-flight. The
    /// milestone name is carried on `AfterBlock.milestone`, keeping this variant
    /// fieldless/`Copy`. See spec/decision-records/discriminated-families-design.md
    /// section 7.3.
    Reaches,
}

impl AfterPredicate {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Succeeds => "succeeds",
            Self::Fails => "fails",
            Self::Completes => "completes",
            Self::TimedOut => "times out",
            Self::Cancelled => "cancelled",
            Self::Held => "held",
            Self::Contended => "contended",
            Self::Ok => "ok",
            Self::Over => "over",
            Self::Promoted => "promoted",
            Self::Conflicted => "conflicted",
            Self::Applied => "applied",
            Self::Stranded => "stranded",
            // The milestone name is rendered separately by the serializer
            // (it lives on `AfterBlock.milestone`), so the bare keyword is
            // all `as_str` carries here.
            Self::Reaches => "reaches",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CaseBlock {
    pub scrutinee: String,
    pub branches: Vec<CaseBranch>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CaseBranch {
    pub pattern: String,
    pub binding: Option<String>,
    pub guard: Option<String>,
    pub body: Vec<BodyStmt>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TerminalStmt {
    pub kind: TerminalKind,
    pub name: String,
    /// `complete <T> from <binding>`: a bounded-type projection egress — the payload
    /// is the source binding projected to `T`'s fields (the shorthand copies), the
    /// dual of `record <T> from <binding>`. `None` for the ordinary explicit-field
    /// form. Only meaningful for `Complete`.
    pub from: Option<String>,
    pub fields: Vec<FieldAssign>,
    /// A bare scalar payload: `complete result 0.9` / `fail error "reason"`. Set
    /// when the terminal is written without a `{ … }` block; mutually exclusive
    /// with `fields` (which is empty) and `from` (a projection needs a block).
    /// Validated against a scalar (`number`/`string`/`bool`) output/failure
    /// contract. `None` for the ordinary field-block form.
    pub scalar: Option<FieldValue>,
    pub span: SourceSpan,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TerminalKind {
    Complete,
    Fail,
}

/// A field assignment extracted from a record/payload body without braces.
/// `value` is `None` for shorthand-copy fields; otherwise it is the exact
/// source text of the value expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SplitFieldAssignment {
    pub name: String,
    pub value: Option<String>,
}

/// Token-level field splitting for record/terminal/table-row bodies. The
/// structure comes from tokens, never from line breaks, so single-line and
/// multi-line blocks behave identically. Shorthand (bare name, `from` blocks
/// only at the call site) is line-delimited: a name with no same-line value
/// is shorthand.
/// The source text of every token that appeared where a FIELD NAME was
/// expected, and was therefore skipped.
///
/// The splitter drops such a token silently, which loses what the author wrote
/// with no diagnostic anywhere:
///
/// ```text
/// record Out {
///   title
///   "hello"
/// }
/// ```
///
/// `title` is a line-delimited shorthand field (documented, and correct), and
/// `"hello"` is then a value with no field name. That compiled clean and the
/// recorded fact took the shorthand's value instead, so the author's literal
/// was silently replaced by a different one.
///
/// This shares ONE scan with `split_field_assignments` rather than mirroring
/// it. A second copy would drift, and two scans of the same text disagreeing is
/// the defect this exists to report.
pub fn stray_value_tokens(source: &str) -> Vec<String> {
    let mut stray = Vec::new();
    split_fields_inner(source, Some(&mut stray));
    stray
}

pub fn split_field_assignments(source: &str) -> Vec<SplitFieldAssignment> {
    split_fields_inner(source, None)
}

fn split_fields_inner(
    source: &str,
    mut stray: Option<&mut Vec<String>>,
) -> Vec<SplitFieldAssignment> {
    let mut diagnostics = Vec::new();
    let tokens = lex_body(source, 0, &mut diagnostics);
    let mut parser = BodyParser {
        source,
        base: 0,
        tokens,
        pos: 0,
        diagnostics,
    };
    let mut assignments = Vec::new();
    while let Some(token) = parser.peek() {
        let name_line = token.line;
        let (stray_start, stray_end) = (token.start, token.end);
        let Tok::Ident(name) = token.tok.clone() else {
            if let Some(sink) = stray.as_deref_mut() {
                sink.push(
                    source
                        .get(stray_start..stray_end)
                        .unwrap_or_default()
                        .to_owned(),
                );
            }
            parser.pos += 1;
            continue;
        };
        parser.pos += 1;
        let is_shorthand = match parser.peek() {
            None => true,
            Some(next) => next.line != name_line,
        };
        if is_shorthand {
            assignments.push(SplitFieldAssignment { name, value: None });
            continue;
        }
        let value_start = parser.pos;
        if !parser.consume_value_atom() {
            parser.pos += 1;
            continue;
        }
        loop {
            match parser.peek().map(|t| t.tok.clone()) {
                Some(Tok::Op(_)) | Some(Tok::Sym('+')) | Some(Tok::Sym('-'))
                | Some(Tok::Sym('*')) | Some(Tok::Sym('/')) | Some(Tok::Sym('<'))
                | Some(Tok::Sym('>')) => {
                    parser.pos += 1;
                    if !parser.consume_value_atom() {
                        break;
                    }
                }
                Some(Tok::Ident(word)) if word == "and" || word == "or" || word == "in" => {
                    parser.pos += 1;
                    if !parser.consume_value_atom() {
                        break;
                    }
                }
                Some(Tok::Sym('[')) => {
                    parser.consume_balanced('[', ']');
                }
                // A brace body after a value atom is a nested payload —
                // variant construction `Approved { score 0.9 }`
                // (spec/sum-types.md) — captured whole, not flattened.
                Some(Tok::Sym('{')) => {
                    parser.consume_balanced('{', '}');
                    break;
                }
                _ => break,
            }
        }
        let first = &parser.tokens[value_start];
        let last = &parser.tokens[parser.pos - 1];
        assignments.push(SplitFieldAssignment {
            name,
            value: Some(source[first.start..last.end].to_owned()),
        });
    }
    assignments
}

// ---------------------------------------------------------------------------
// Lexer
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
enum Tok {
    Ident(String),
    Str(String),
    TripleStr {
        text: String,
        content_type: Option<String>,
    },
    Number(String),
    Sym(char),
    Arrow,    // ->
    FatArrow, // =>
    Op(&'static str),
}

#[derive(Clone, Debug)]
struct Token {
    tok: Tok,
    start: usize,
    end: usize,
    line: usize,
}

fn line_of(source: &str, offset: usize) -> usize {
    source[..offset].bytes().filter(|b| *b == b'\n').count()
}

fn lex_body(source: &str, base: usize, diagnostics: &mut Vec<Diagnostic>) -> Vec<Token> {
    let bytes = source.as_bytes();
    let mut tokens = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i] as char;
        if c.is_whitespace() {
            i += 1;
            continue;
        }
        let start = i;
        if source[i..].starts_with("\"\"\"") {
            // Triple-quoted prompt with optional content-type on the opener.
            let opener_end = source[i + 3..]
                .find('\n')
                .map(|offset| i + 3 + offset)
                .unwrap_or(source.len());
            let annotation = source[i + 3..opener_end].trim();
            let content_type = (!annotation.is_empty()).then(|| annotation.to_owned());
            let Some(close) = source[opener_end..].find("\"\"\"").map(|o| opener_end + o) else {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: SourceSpan {
                        start: base + start,
                        end: base + source.len(),
                    },
                    message: "unterminated multiline string".to_owned(),
                    suggestion: Some("close the prompt with `\"\"\"`".to_owned()),
                });
                break;
            };
            let raw = &source[opener_end..close];
            let text = dedent_prompt(raw);
            tokens.push(Token {
                tok: Tok::TripleStr { text, content_type },
                start,
                end: close + 3,
                line: line_of(source, start),
            });
            i = close + 3;
            continue;
        }
        if c == '"' {
            let mut j = i + 1;
            let mut value = String::new();
            let mut closed = false;
            while j < bytes.len() {
                let cj = bytes[j] as char;
                if cj == '\\' && j + 1 < bytes.len() {
                    value.push(bytes[j + 1] as char);
                    j += 2;
                    continue;
                }
                if cj == '"' {
                    closed = true;
                    break;
                }
                if cj == '\n' {
                    break;
                }
                value.push(cj);
                j += 1;
            }
            if !closed {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: SourceSpan {
                        start: base + start,
                        end: base + j,
                    },
                    message: "unterminated string".to_owned(),
                    suggestion: Some("close the string with `\"`".to_owned()),
                });
                i = j;
                continue;
            }
            tokens.push(Token {
                tok: Tok::Str(value),
                start,
                end: j + 1,
                line: line_of(source, start),
            });
            i = j + 1;
            continue;
        }
        if c.is_ascii_digit()
            || (c == '-'
                && bytes
                    .get(i + 1)
                    .is_some_and(|b| (*b as char).is_ascii_digit()))
        {
            let mut j = i + 1;
            while j < bytes.len() {
                let cj = bytes[j] as char;
                if cj.is_ascii_alphanumeric() || cj == '.' || cj == '_' {
                    j += 1;
                } else {
                    break;
                }
            }
            tokens.push(Token {
                tok: Tok::Number(source[i..j].to_owned()),
                start,
                end: j,
                line: line_of(source, start),
            });
            i = j;
            continue;
        }
        if c.is_ascii_alphabetic() || c == '_' {
            let mut j = i + 1;
            while j < bytes.len() {
                let cj = bytes[j] as char;
                if cj.is_ascii_alphanumeric() || cj == '_' || cj == '.' {
                    j += 1;
                } else {
                    break;
                }
            }
            // Trailing dots belong to punctuation, not identifiers.
            let mut end = j;
            while end > i && bytes[end - 1] as char == '.' {
                end -= 1;
            }
            tokens.push(Token {
                tok: Tok::Ident(source[i..end].to_owned()),
                start,
                end,
                line: line_of(source, start),
            });
            i = end.max(i + 1);
            continue;
        }
        if source[i..].starts_with("->") {
            tokens.push(Token {
                tok: Tok::Arrow,
                start,
                end: i + 2,
                line: line_of(source, i),
            });
            i += 2;
            continue;
        }
        if source[i..].starts_with("=>") {
            tokens.push(Token {
                tok: Tok::FatArrow,
                start,
                end: i + 2,
                line: line_of(source, i),
            });
            i += 2;
            continue;
        }
        let two_char = [
            ("==", "=="),
            ("!=", "!="),
            ("<=", "<="),
            (">=", ">="),
            ("&&", "&&"),
            ("||", "||"),
        ]
        .iter()
        .find(|(text, _)| source[i..].starts_with(text))
        .map(|(_, op)| *op);
        if let Some(op) = two_char {
            tokens.push(Token {
                tok: Tok::Op(op),
                start,
                end: i + 2,
                line: line_of(source, i),
            });
            i += 2;
            continue;
        }
        if c == '#' || (c == '/' && bytes.get(i + 1) == Some(&b'/')) {
            // Full-line `#` / `//` comments are legal in rule bodies (ruling
            // 2026-07-21), matching the top-level lexer's two markers: a line
            // whose first non-whitespace characters open a comment is skipped
            // to its end. A comment after code on the same line falls through
            // (trailing comments stay top-level-only; a mid-line `/` is the
            // division operator).
            let mut k = i;
            let mut line_leading = true;
            while k > 0 {
                let prev = bytes[k - 1] as char;
                if prev == '\n' {
                    break;
                }
                if prev != ' ' && prev != '\t' {
                    line_leading = false;
                    break;
                }
                k -= 1;
            }
            if line_leading {
                while i < bytes.len() && bytes[i] as char != '\n' {
                    i += 1;
                }
                continue;
            }
        }
        match c {
            '{' | '}' | '[' | ']' | '(' | ')' | ',' | '.' | '+' | '-' | '*' | '/' | '<' | '>'
            | '!' | ':' | ';' => {
                tokens.push(Token {
                    tok: Tok::Sym(c),
                    start,
                    end: i + 1,
                    line: line_of(source, start),
                });
                i += 1;
            }
            _ => {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: SourceSpan {
                        start: base + i,
                        end: base + i + 1,
                    },
                    message: format!("unexpected character `{c}` in rule body"),
                    suggestion: None,
                });
                i += 1;
            }
        }
    }
    tokens
}

/// Blanks full-line `#` comments in rule-body TEXT, byte-preservingly: every
/// byte of a comment line except its newline becomes a space, so all spans
/// and offsets downstream still point at the original source. Raw-string
/// (`"""`) interiors are untouched -- a markdown heading inside a prompt is
/// content, not a comment. The compile path runs this once per rule body
/// before action/`then` expansion, so the kernel and every line-based
/// analysis see comment-free text, while `whip fmt` (which re-emits the raw
/// body text) preserves the comments.
pub fn blank_full_line_comments(text: &str) -> String {
    let mut out: Vec<u8> = Vec::with_capacity(text.len());
    let mut in_fence = false;
    for line in text.split_inclusive('\n') {
        let (content, has_newline) = match line.strip_suffix('\n') {
            Some(content) => (content, true),
            None => (line, false),
        };
        let lead = content.trim_start();
        if !in_fence && (lead.starts_with('#') || lead.starts_with("//")) {
            out.resize(out.len() + content.len(), b' ');
        } else {
            out.extend_from_slice(content.as_bytes());
            if content.matches("\"\"\"").count() % 2 == 1 {
                in_fence = !in_fence;
            }
        }
        if has_newline {
            out.push(b'\n');
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn dedent_prompt(raw: &str) -> String {
    let lines: Vec<&str> = raw.lines().collect();
    let indent = lines
        .iter()
        .filter(|line| !line.trim().is_empty())
        .map(|line| line.len() - line.trim_start().len())
        .min()
        .unwrap_or(0);
    let mut text = lines
        .iter()
        .map(|line| {
            if line.len() >= indent {
                &line[indent..]
            } else {
                line.trim_start()
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    while text.starts_with('\n') {
        text.remove(0);
    }
    while text.ends_with('\n') || text.ends_with(' ') {
        text.pop();
    }
    text
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Parses exactly ONE statement from the front of `source` (used by `then`
/// expansion to consume the chained effect statement without parsing — and
/// spuriously diagnosing — the remainder of the enclosing block). Returns the
/// statement and only the diagnostics that single parse produced.
pub fn parse_first_statement(source: &str, base: usize) -> (Option<BodyStmt>, Vec<Diagnostic>) {
    let mut diagnostics = Vec::new();
    let tokens = lex_body(source, base, &mut diagnostics);
    let mut parser = BodyParser {
        source,
        base,
        tokens,
        pos: 0,
        diagnostics,
    };
    let statement = parser.parse_statement();
    (statement, parser.diagnostics)
}

pub fn parse_rule_body(source: &str, base: usize) -> (BodyAst, Vec<Diagnostic>) {
    let mut diagnostics = Vec::new();
    let tokens = lex_body(source, base, &mut diagnostics);
    let mut parser = BodyParser {
        source,
        base,
        tokens,
        pos: 0,
        diagnostics,
    };
    let statements = parser.parse_statements(false);
    (BodyAst { statements }, parser.diagnostics)
}

struct BodyParser<'a> {
    source: &'a str,
    base: usize,
    tokens: Vec<Token>,
    pos: usize,
    diagnostics: Vec<Diagnostic>,
}

impl<'a> BodyParser<'a> {
    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn peek_at(&self, offset: usize) -> Option<&Token> {
        self.tokens.get(self.pos + offset)
    }

    fn advance(&mut self) -> Option<Token> {
        let token = self.tokens.get(self.pos).cloned();
        if token.is_some() {
            self.pos += 1;
        }
        token
    }

    fn at_ident(&self, value: &str) -> bool {
        matches!(self.peek().map(|t| &t.tok), Some(Tok::Ident(v)) if v == value)
    }

    fn at_sym(&self, value: char) -> bool {
        matches!(self.peek().map(|t| &t.tok), Some(Tok::Sym(v)) if *v == value)
    }

    fn consume_ident(&mut self, value: &str) -> bool {
        if self.at_ident(value) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn consume_sym(&mut self, value: char) -> bool {
        if self.at_sym(value) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn span_here(&self) -> SourceSpan {
        match self.peek() {
            Some(token) => SourceSpan {
                start: self.base + token.start,
                end: self.base + token.end,
            },
            None => SourceSpan {
                start: self.base + self.source.len(),
                end: self.base + self.source.len(),
            },
        }
    }

    fn span_from(&self, start_token: usize) -> SourceSpan {
        let start = self
            .tokens
            .get(start_token)
            .map(|t| self.base + t.start)
            .unwrap_or(self.base);
        let end = self
            .tokens
            .get(self.pos.saturating_sub(1))
            .map(|t| self.base + t.end)
            .unwrap_or(start);
        SourceSpan { start, end }
    }

    fn error(&mut self, span: SourceSpan, message: impl Into<String>, suggestion: Option<String>) {
        self.diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: message.into(),
            suggestion,
        });
    }

    fn ident_text(&mut self, what: &str) -> Option<String> {
        match self.peek().map(|t| t.tok.clone()) {
            Some(Tok::Ident(value)) => {
                self.pos += 1;
                Some(value)
            }
            _ => {
                let span = self.span_here();
                self.error(span, format!("expected {what}"), None);
                None
            }
        }
    }

    /// Skip to a safe resync point after an error: the next statement keyword
    /// at the current depth or a closing brace.
    fn recover(&mut self) {
        let mut depth = 0usize;
        while let Some(token) = self.peek() {
            match &token.tok {
                Tok::Sym('{') => depth += 1,
                Tok::Sym('}') if depth == 0 => return,
                Tok::Sym('}') => depth -= 1,
                Tok::Ident(value)
                    if depth == 0
                        && STATEMENT_KEYWORDS.contains(&value.as_str())
                        && self.pos != 0 =>
                {
                    return
                }
                _ => {}
            }
            self.pos += 1;
        }
    }

    fn parse_statements(&mut self, in_block: bool) -> Vec<BodyStmt> {
        let mut statements = Vec::new();
        loop {
            if self.peek().is_none() {
                if in_block {
                    let span = self.span_here();
                    self.error(
                        span,
                        "unclosed block in rule body",
                        Some("add `}`".to_owned()),
                    );
                }
                return statements;
            }
            if self.at_sym('}') {
                if in_block {
                    self.pos += 1;
                }
                return statements;
            }
            let before = self.pos;
            if let Some(statement) = self.parse_statement() {
                statements.push(statement);
            }
            if self.pos == before {
                // No progress: recover to avoid an infinite loop.
                self.pos += 1;
                self.recover();
            }
        }
    }

    fn parse_statement(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        let keyword = match self.peek().map(|t| t.tok.clone()) {
            Some(Tok::Ident(value)) => value,
            _ => {
                let span = self.span_here();
                let package_verbs = EFFECT_OPERATION_GRAMMAR
                    .iter()
                    .map(|spec| spec.keyword)
                    .collect::<Vec<_>>()
                    .join(", ");
                self.error(
                    span,
                    "expected a rule body statement".to_owned(),
                    Some(format!(
                        "statements start with record, done, consume, during, until, tell, \
                         coerce, prompt, decide, call, invoke, read, write, import, export, \
                         after, case, complete, fail, timer, cancel, exec, file, claim, \
                         release, finish, acquire, renew, append, emit, redact, or a package \
                         effect verb ({package_verbs})"
                    )),
                );
                self.recover();
                return None;
            }
        };
        // Data-driven `effect_operation` constructs (DR-0011): a leading keyword
        // registered in the compiled-in grammar table is parsed generically.
        if let Some(spec) = effect_operation_spec(&keyword) {
            return self.parse_effect_operation(spec);
        }
        match keyword.as_str() {
            "record" => self.parse_record_statement().map(BodyStmt::Record),
            // `consume <counter> for <key> ...` is the counter verb
            // (spec/coordination.md). The bare `consume <binding>` alias for
            // `done` was removed after its deprecation window (shipped v0.2).
            "consume" if self.looks_like_counter_consume() => self.parse_counter_consume(),
            "consume" => self.removed_consume_alias(),
            "done" => self.parse_done_statement(),
            "during" => self.parse_region(false),
            "until" => self.parse_region(true),
            "tell" => self.parse_tell(),
            "coerce" => self.parse_coerce_call(),
            "prompt" => self.parse_prompt_effect(),
            "decide" => self.parse_decide(),
            "call" => self.parse_call(),
            "invoke" => self.parse_invoke(),
            "read" => self.parse_read(),
            "write" => self.parse_write(),
            "import" => self.parse_import(),
            "export" => self.parse_export(),
            "after" => self.parse_after(),
            "case" => self.parse_case(),
            "complete" | "fail" => self.parse_terminal(),
            "timer" => self.parse_timer(),
            "cancel" => self.parse_cancel(),
            "exec" => self.parse_exec(),
            "file" => self.parse_tracker_file(),
            "claim" => self.parse_tracker_claim(),
            "release" => self.parse_tracker_release(),
            "finish" => self.parse_tracker_finish(),
            "acquire" => self.parse_lease_acquire(),
            "renew" => self.parse_lease_renew(),
            "append" => self.parse_ledger_append(),
            "emit" => self.parse_emit_signal(),
            "redact" => self.parse_redact(),
            "when" | "on" => {
                let span = self.span_here();
                self.error(
                    span,
                    format!("`{keyword}` blocks are not rule body statements"),
                    Some(
                        "branch with `case`, guard the rule's `when` clause, or chain \
                         effects with `then <binding> <- <effect>`"
                            .to_owned(),
                    ),
                );
                self.pos += 1;
                self.recover();
                None
            }
            other => {
                let span = self.span_here();
                self.error(
                    span,
                    format!("unknown rule body statement `{other}`"),
                    Some(
                        "statements start with record, done, tell, coerce, claim, \
                         release, finish, file, call, recall, invoke, emit, after, case, complete, \
                         fail, timer, cancel, decide, prompt, or exec"
                            .to_owned(),
                    ),
                );
                self.pos += 1;
                self.recover();
                None
            }
        }
        .inspect(|_| {
            let _ = start;
        })
    }

    // -- record ------------------------------------------------------------

    fn parse_record_statement(&mut self) -> Option<RecordStmt> {
        let start = self.pos;
        self.pos += 1; // record
        let schema = self.ident_text("class name after `record`")?;
        let from = if self.consume_ident("from") {
            Some(self.ident_text("binding name after `from`")?)
        } else {
            None
        };
        let fields = self.parse_field_block(from.is_some())?;
        Some(RecordStmt {
            schema,
            from,
            fields,
            span: self.span_from(start),
        })
    }

    fn parse_done_statement(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // `done`
        let binding = self.ident_text("fact binding after `done`")?;
        let replacement = if matches!(self.peek().map(|t| &t.tok), Some(Tok::Arrow)) {
            self.pos += 1;
            if !self.consume_ident("record") {
                let span = self.span_here();
                self.error(span, "expected `record` after `->`", None);
                return None;
            }
            self.pos -= 1; // parse_record_statement expects to consume `record`
            Some(self.parse_record_statement()?)
        } else {
            None
        };
        Some(BodyStmt::Done {
            binding,
            replacement,
            span: self.span_from(start),
        })
    }

    /// The bare `consume <binding>` alias for `done` was removed after its
    /// deprecation window (one release; shipped in v0.2). Emit a clear
    /// diagnostic instead of the generic unknown-statement error. The live
    /// counter verb `consume <counter> for ...` is dispatched ahead of this by
    /// `looks_like_counter_consume`, so only the removed alias reaches here.
    fn removed_consume_alias(&mut self) -> Option<BodyStmt> {
        let span = self.span_here();
        self.error(
            span,
            "`consume` was removed; use `done`",
            Some("replace `consume` with `done`".to_owned()),
        );
        // Swallow the whole statement (binding and any `-> record { ... }`) so
        // the removed alias yields ONE diagnostic, not a cascade from the
        // leftover binding being re-scanned as an unknown statement.
        self.pos += 1; // past `consume`
        self.recover();
        None
    }

    /// Parse `{ field value ... }`. Values are expressions; in `from` blocks a
    /// bare field name is shorthand-copy. Single-line and multi-line forms are
    /// equivalent: structure comes from tokens, never line breaks.
    fn parse_field_block(&mut self, allow_shorthand: bool) -> Option<Vec<FieldAssign>> {
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(span, "expected `{` to open a field block", None);
            return None;
        }
        let mut fields = Vec::new();
        loop {
            if self.consume_sym('}') {
                return Some(fields);
            }
            if self.peek().is_none() {
                let span = self.span_here();
                self.error(span, "unclosed field block", Some("add `}`".to_owned()));
                return Some(fields);
            }
            let field_start = self.pos;
            let Some(name) = self.ident_text("field name") else {
                self.recover();
                continue;
            };
            // Nested typed payload: `binding Schema { ... }`.
            if matches!(self.peek().map(|t| &t.tok), Some(Tok::Ident(next))
                if next.chars().next().is_some_and(char::is_uppercase))
                && matches!(self.peek_at(1).map(|t| &t.tok), Some(Tok::Sym('{')))
            {
                let schema = self.ident_text("payload class name")?;
                let nested = self.parse_field_block(false)?;
                fields.push(FieldAssign {
                    name,
                    value: FieldValue::Nested {
                        schema,
                        fields: nested,
                    },
                    span: self.span_from(field_start),
                });
                continue;
            }
            // `from` blocks support shorthand: a bare field name copies the
            // same-named field. Shorthand is line-delimited (the historical
            // and documented form): a name is shorthand when the next token
            // sits on a different line or closes the block.
            if allow_shorthand {
                let name_line = self
                    .tokens
                    .get(field_start)
                    .map(|t| t.line)
                    .unwrap_or_default();
                let is_shorthand = match self.peek() {
                    None => true,
                    Some(token) => matches!(token.tok, Tok::Sym('}')) || token.line != name_line,
                };
                if is_shorthand {
                    fields.push(FieldAssign {
                        name,
                        value: FieldValue::Shorthand,
                        span: self.span_from(field_start),
                    });
                    continue;
                }
            }
            let Some((source, expr)) = self.parse_value_expression() else {
                self.recover();
                continue;
            };
            fields.push(FieldAssign {
                name,
                value: FieldValue::Expr { source, expr },
                span: self.span_from(field_start),
            });
        }
    }

    /// Capture one expression's source slice by walking atoms and operators,
    /// then parse it with the shared expression parser.
    fn parse_value_expression(&mut self) -> Option<(String, Expr)> {
        let start_token = self.pos;
        if !self.consume_value_atom() {
            let span = self.span_here();
            self.error(span, "expected a field value expression", None);
            return None;
        }
        loop {
            match self.peek().map(|t| t.tok.clone()) {
                Some(Tok::Op(_)) | Some(Tok::Sym('+')) | Some(Tok::Sym('-'))
                | Some(Tok::Sym('*')) | Some(Tok::Sym('/')) | Some(Tok::Sym('<'))
                | Some(Tok::Sym('>')) => {
                    self.pos += 1;
                    if !self.consume_value_atom() {
                        let span = self.span_here();
                        self.error(span, "expected expression after operator", None);
                        return None;
                    }
                }
                Some(Tok::Ident(word)) if word == "and" || word == "or" || word == "in" => {
                    self.pos += 1;
                    if !self.consume_value_atom() {
                        let span = self.span_here();
                        self.error(span, "expected expression after operator", None);
                        return None;
                    }
                }
                Some(Tok::Sym('[')) => {
                    // index continuation
                    self.consume_balanced('[', ']');
                }
                _ => break,
            }
        }
        let first = self.tokens.get(start_token)?;
        let last = self.tokens.get(self.pos.saturating_sub(1))?;
        let source = self.source[first.start..last.end].to_owned();
        match parse_expression(&source) {
            Ok(expr) => Some((source, expr)),
            Err(message) => {
                let span = SourceSpan {
                    start: self.base + first.start,
                    end: self.base + last.end,
                };
                self.error(
                    span,
                    format!("invalid field value expression: {message}"),
                    None,
                );
                None
            }
        }
    }

    fn consume_value_atom(&mut self) -> bool {
        match self.peek().map(|t| t.tok.clone()) {
            Some(Tok::Str(_)) | Some(Tok::Number(_)) | Some(Tok::TripleStr { .. }) => {
                self.pos += 1;
                true
            }
            Some(Tok::Sym('[')) => self.consume_balanced('[', ']'),
            Some(Tok::Sym('{')) => self.consume_balanced('{', '}'),
            Some(Tok::Sym('(')) => self.consume_balanced('(', ')'),
            Some(Tok::Sym('!')) | Some(Tok::Sym('-')) => {
                self.pos += 1;
                self.consume_value_atom()
            }
            Some(Tok::Ident(word)) if word == "not" => {
                self.pos += 1;
                self.consume_value_atom()
            }
            Some(Tok::Ident(_)) => {
                self.pos += 1;
                // call like count(...) / exists(...)
                if self.at_sym('(') {
                    self.consume_balanced('(', ')');
                }
                true
            }
            _ => false,
        }
    }

    fn consume_balanced(&mut self, open: char, close: char) -> bool {
        if !self.consume_sym(open) {
            return false;
        }
        let mut depth = 1;
        while depth > 0 {
            match self.advance().map(|t| t.tok) {
                Some(Tok::Sym(c)) if c == open => depth += 1,
                Some(Tok::Sym(c)) if c == close => depth -= 1,
                Some(_) => {}
                None => {
                    let span = self.span_here();
                    self.error(span, format!("unclosed `{open}`"), None);
                    return false;
                }
            }
        }
        true
    }

    // -- effects -----------------------------------------------------------

    fn parse_effect_modifiers(
        &mut self,
        binding: &mut Option<String>,
        requires: &mut Vec<String>,
        timeout_seconds: &mut Option<u64>,
    ) -> bool {
        loop {
            if self.consume_ident("as") {
                match self.ident_text("binding name after `as`") {
                    Some(name) => *binding = Some(name),
                    None => return false,
                }
                continue;
            }
            if self.consume_ident("requires") {
                match self.parse_string_array() {
                    Some(values) => *requires = values,
                    None => return false,
                }
                continue;
            }
            if self.consume_ident("timeout") {
                let span = self.span_here();
                let Some(Tok::Number(value)) = self.peek().map(|t| t.tok.clone()) else {
                    self.error(
                        span,
                        "expected a duration after `timeout`".to_owned(),
                        Some(
                            "use `<n><unit>` with unit s, m, h, or d, e.g. `timeout 10m`"
                                .to_owned(),
                        ),
                    );
                    return false;
                };
                self.pos += 1;
                match parse_short_duration_seconds(&value) {
                    Some(seconds) if seconds > 0 => *timeout_seconds = Some(seconds),
                    _ => {
                        self.error(
                            span,
                            format!("invalid timeout duration `{value}`"),
                            Some("use `<n><unit>` with unit s, m, h, or d".to_owned()),
                        );
                        return false;
                    }
                }
                continue;
            }
            return true;
        }
    }

    fn parse_string_array(&mut self) -> Option<Vec<String>> {
        if !self.consume_sym('[') {
            let span = self.span_here();
            self.error(span, "expected `[` to open a string list", None);
            return None;
        }
        let mut values = Vec::new();
        loop {
            if self.consume_sym(']') {
                return Some(values);
            }
            match self.advance().map(|t| t.tok) {
                Some(Tok::Str(value)) => values.push(value),
                Some(Tok::Sym(',')) => {}
                other => {
                    let span = self.span_here();
                    self.error(
                        span,
                        format!("expected a string in list, found {other:?}"),
                        None,
                    );
                    return None;
                }
            }
        }
    }

    fn parse_prompt(&mut self) -> Option<Prompt> {
        match self.advance().map(|t| t.tok) {
            Some(Tok::Str(text)) => Some(Prompt {
                text,
                content_type: None,
            }),
            Some(Tok::TripleStr { text, content_type }) => Some(Prompt { text, content_type }),
            _ => {
                let span = self.span_here();
                self.error(span, "expected a prompt string", None);
                None
            }
        }
    }

    fn parse_tell(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // tell
        let target = self.ident_text("agent target after `tell`")?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        let mut access_grants = Vec::new();
        let mut skills = Vec::new();
        let mut on_stream = None;
        // Pre-prompt modifiers may interleave the standard ones (`as`/`requires`/
        // `timeout`) with `with access to` grants, `with skills [...]`, and
        // `on stream <name>`.
        if !self.parse_effect_modifiers_with_access(
            &mut binding,
            &mut requires,
            &mut timeout_seconds,
            &mut access_grants,
            Some(&mut skills),
            Some(&mut on_stream),
        ) {
            return None;
        }
        let prompt = self.parse_prompt()?;
        if !self.parse_effect_modifiers_with_access(
            &mut binding,
            &mut requires,
            &mut timeout_seconds,
            &mut access_grants,
            Some(&mut skills),
            Some(&mut on_stream),
        ) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Tell {
                target,
                access_grants,
                skills,
                on_stream,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: Some(prompt),
            span: self.span_from(start),
        }))
    }

    /// Parse effect modifiers, interleaving the shared effect modifiers with
    /// `with access to` grants until neither matches.
    fn parse_effect_modifiers_with_access(
        &mut self,
        binding: &mut Option<String>,
        requires: &mut Vec<String>,
        timeout_seconds: &mut Option<u64>,
        access_grants: &mut Vec<AccessGrant>,
        mut skills: Option<&mut Vec<String>>,
        mut on_stream: Option<&mut Option<String>>,
    ) -> bool {
        loop {
            if !self.parse_effect_modifiers(binding, requires, timeout_seconds) {
                return false;
            }
            // `on stream <name>` (std.vcs): only where a homing slot is
            // offered (`tell`); elsewhere `on` is not consumed.
            if self.at_ident("on")
                && matches!(self.peek_at(1).map(|t| &t.tok), Some(Tok::Ident(v)) if v == "stream")
            {
                if let Some(slot) = on_stream.as_deref_mut() {
                    self.pos += 2; // on stream
                    let Some(name) = self.ident_text("stream name after `on stream`") else {
                        return false;
                    };
                    *slot = Some(name);
                    continue;
                }
            }
            if self.at_ident("with") {
                // Turn-scoped `with skills [...]` (Phase 7) vs `with access to …`.
                // `with skills` is only valid where a skills accumulator is offered
                // (`tell`); elsewhere it falls through to the access-grant error.
                if matches!(self.peek_at(1).map(|t| &t.tok), Some(Tok::Ident(v)) if v == "skills") {
                    if let Some(acc) = skills.as_deref_mut() {
                        if !self.parse_with_skills(acc) {
                            return false;
                        }
                        continue;
                    }
                }
                if !self.parse_access_grant(access_grants) {
                    return false;
                }
                continue;
            }
            return true;
        }
    }

    /// Parse `with skills ["a", "b"]` (context-assembly Phase 7): turn-scoped skills
    /// pinned into the turn's provenance. Assumes the cursor is at `with`.
    fn parse_with_skills(&mut self, skills: &mut Vec<String>) -> bool {
        self.pos += 1; // with
        self.pos += 1; // skills (peeked by the caller)
        if !self.at_sym('[') {
            let span = self.span_here();
            self.error(
                span,
                "expected `[\"skill\", …]` after `with skills`".to_owned(),
                None,
            );
            return false;
        }
        match self.parse_string_array() {
            Some(values) => {
                skills.extend(values);
                true
            }
            None => false,
        }
    }

    /// Parse `with access to <resource> { <op clauses> }`, or the resource-less
    /// shorthand `with access to { <resource> { <op clauses> } ... }`. Each clause is
    /// an operation name with an optional `for <target>` ref and/or `["glob", …]`
    /// paths. `with context`/`with skills` modifiers are not yet supported and are
    /// reported as such.
    fn parse_access_grant(&mut self, grants: &mut Vec<AccessGrant>) -> bool {
        let start = self.pos;
        self.pos += 1; // with
        if !self.consume_ident("access") {
            let span = self.span_here();
            let detail = if self.at_ident("context") || self.at_ident("skills") {
                "`with context`/`with skills` turn modifiers are not supported yet"
            } else {
                "expected `access to <resource> { ... }` after `with`"
            };
            self.error(span, detail.to_owned(), None);
            return false;
        }
        if !self.consume_ident("to") {
            let span = self.span_here();
            self.error(span, "expected `to` after `with access`".to_owned(), None);
            return false;
        }
        if self.consume_sym('{') {
            let mut resources = 0usize;
            loop {
                if self.consume_sym('}') {
                    break;
                }
                resources += 1;
                let grant_start = self.pos;
                let Some(resource) =
                    self.ident_text("resource in the access-grant shorthand block")
                else {
                    return false;
                };
                if !self.consume_sym('{') {
                    let span = self.span_here();
                    self.error(
                        span,
                        "expected `{` to open the resource access-grant block".to_owned(),
                        None,
                    );
                    return false;
                }
                let Some(operations) = self.parse_access_grant_operations() else {
                    return false;
                };
                grants.push(AccessGrant {
                    resource,
                    operations,
                    span: self.span_from(grant_start),
                });
            }
            if resources == 0 {
                let span = self.span_from(start);
                self.error(
                    span,
                    "access-grant shorthand block grants no resources".to_owned(),
                    Some(
                        "write `with access to <resource> { ... }`, or add resource blocks inside the shorthand"
                            .to_owned(),
                    ),
                );
                return false;
            }
            return true;
        }
        let Some(resource) = self.ident_text("resource after `with access to`") else {
            return false;
        };
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(
                span,
                "expected `{` to open the access-grant block".to_owned(),
                None,
            );
            return false;
        }
        let Some(operations) = self.parse_access_grant_operations() else {
            return false;
        };
        grants.push(AccessGrant {
            resource,
            operations,
            span: self.span_from(start),
        });
        true
    }

    fn parse_access_grant_operations(&mut self) -> Option<Vec<AccessGrantOp>> {
        let mut operations = Vec::new();
        loop {
            if self.consume_sym('}') {
                return Some(operations);
            }
            let op_start = self.pos;
            let operation = self.ident_text("operation in the access-grant block")?;
            let mut target = None;
            if self.consume_ident("for") {
                target = Some(self.ident_text("target after `for`")?);
            }
            let mut globs = Vec::new();
            if self.at_sym('[') {
                globs = self.parse_string_array()?;
            }
            operations.push(AccessGrantOp {
                operation,
                target,
                globs,
                span: self.span_from(op_start),
            });
        }
    }

    fn parse_coerce_call(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // coerce
        let name = self.ident_text("coerce function name")?;
        if !self.consume_sym('(') {
            let span = self.span_here();
            self.error(span, "expected `(` after coerce function name", None);
            return None;
        }
        let mut args = Vec::new();
        loop {
            if self.consume_sym(')') {
                break;
            }
            if self.peek().is_none() {
                let span = self.span_here();
                self.error(span, "unclosed coerce argument list", None);
                return None;
            }
            let (source, _) = self.parse_value_expression()?;
            args.push(source);
            self.consume_sym(',');
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        // optional trailing source-crossing markers (I-IFC3); must come last.
        let mut endorsed = false;
        let mut declassified = false;
        loop {
            if self.consume_ident("endorsed") {
                endorsed = true;
            } else if self.consume_ident("declassified") {
                declassified = true;
            } else {
                break;
            }
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Coerce {
                name,
                args,
                endorsed,
                declassified,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_prompt_effect(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // prompt
        let prompt = self.parse_prompt()?;
        let provider = if self.consume_ident("using") {
            Some(self.ident_text("provider after `using`")?)
        } else {
            None
        };
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`prompt` requires an `as` binding".to_owned(),
                Some("write `prompt \"Summarize this\" as summary`".to_owned()),
            );
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Prompt { provider },
            binding,
            requires,
            timeout_seconds,
            prompt: Some(prompt),
            span: self.span_from(start),
        }))
    }

    fn parse_decide(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // decide
        let prompt = self.parse_prompt()?;
        if !matches!(self.advance().map(|t| t.tok), Some(Tok::Arrow)) {
            let span = self.span_here();
            self.error(
                span,
                "expected `->` after the decide prompt".to_owned(),
                Some("write `decide \"...\" -> { field type, ... } as name`".to_owned()),
            );
            return None;
        }
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(span, "expected `{` to open the decide result shape", None);
            return None;
        }
        let mut result_fields = Vec::new();
        loop {
            if self.consume_sym('}') {
                break;
            }
            let name = self.ident_text("result field name")?;
            let ty = self.ident_text("result field type")?;
            result_fields.push((name, ty));
            self.consume_sym(',');
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`decide` requires an `as` binding".to_owned(),
                Some(
                    "the typed result is only reachable through `after <binding> succeeds`"
                        .to_owned(),
                ),
            );
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Decide { result_fields },
            binding,
            requires,
            timeout_seconds,
            prompt: Some(prompt),
            span: self.span_from(start),
        }))
    }

    fn parse_call(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // call
        let capability = self.ident_text("package capability after `call`")?;
        let argument = if self.consume_ident("for") {
            Some(self.ident_text("argument binding after `for`")?)
        } else {
            None
        };
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Call {
                capability,
                argument,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    /// Parse a data-driven `effect_operation` construct (DR-0011). Reproduces
    /// the byte-identical success lowering the hand-written `recall`/`send`
    /// parsers emitted: consume the keyword, then each slot (its connective, if
    /// any, then its value), then the optional payload block (required/unknown
    /// checks, expression-typed, in encounter order), then the effect modifiers,
    /// enforcing the binding mode, and build one `ConstructCapabilityCall` whose
    /// fields are the slots followed by the payload fields, in order.
    fn parse_effect_operation(&mut self, spec: &EffectOperationSpec) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // keyword
        let mut fields: Vec<ConstructUseField> = Vec::new();
        for slot in spec.slots {
            if let Some(connective) = slot.connective {
                if !self.consume_ident(connective) {
                    let span = self.span_here();
                    self.error(
                        span,
                        format!("expected `{connective}` after `{}`", spec.keyword),
                        None,
                    );
                    return None;
                }
            }
            let source = match slot.kind {
                SlotKind::Identifier => self.ident_text(slot.name)?,
                SlotKind::Expression => self.parse_value_expression()?.0,
            };
            fields.push(ConstructUseField {
                name: slot.name.to_owned(),
                source,
            });
        }
        if let Some(payload) = spec.payload {
            let block_fields = self.parse_field_block(false)?;
            let mut seen: Vec<&'static str> = Vec::new();
            for field in &block_fields {
                let Some(field_spec) = payload.iter().find(|f| f.name == field.name) else {
                    self.error(
                        field.span,
                        format!("unknown `{}` block field `{}`", spec.keyword, field.name),
                        None,
                    );
                    return None;
                };
                let FieldValue::Expr { source, .. } = &field.value else {
                    self.error(
                        field.span,
                        format!(
                            "`{}` field `{}` must be an expression",
                            spec.keyword, field.name
                        ),
                        None,
                    );
                    return None;
                };
                seen.push(field_spec.name);
                fields.push(ConstructUseField {
                    name: field.name.clone(),
                    source: source.clone(),
                });
            }
            for required in payload.iter().filter(|f| f.required) {
                if !seen.contains(&required.name) {
                    let span = self.span_from(start);
                    self.error(
                        span,
                        format!("`{}` requires a `{}` field", spec.keyword, required.name),
                        None,
                    );
                    return None;
                }
            }
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        match spec.binding {
            BindingMode::Required if binding.is_none() => {
                let span = self.span_from(start);
                self.error(
                    span,
                    format!("`{}` requires an `as` binding", spec.keyword),
                    None,
                );
                return None;
            }
            BindingMode::None if binding.is_some() => {
                let span = self.span_from(start);
                self.error(
                    span,
                    format!("`{}` does not take an `as` binding", spec.keyword),
                    None,
                );
                return None;
            }
            _ => {}
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::ConstructCapabilityCall {
                keyword: spec.keyword.to_owned(),
                target_capability: spec.target_capability.to_owned(),
                fields,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_read(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // read
        let usage = "write `read <format> from <store> at <path> as <binding>`".to_owned();
        let format = self.ident_text("file format after `read`")?;
        // v0 `read` is a body read: `text`/`markdown` decode to a UTF-8 content
        // body. Structured codecs (json/jsonl/csv) are typed row/value data —
        // that is the `import` surface (fact-batch admission), not `read`; and
        // `bytes` (an artifact with a content hash) is a deferred read codec.
        // Reject anything else here so `read <format>` is honest rather than
        // silently decoding every format as text.
        if !matches!(format.as_str(), "text" | "markdown") {
            let span = self.span_from(start);
            self.error(
                span,
                format!(
                    "`read {format}` is not supported in v0 — `read` decodes only `text` or `markdown` bodies"
                ),
                Some(
                    "use `read text`/`read markdown` for a body, `import <format> <Schema>` for structured rows, or `read text` + `coerce` to interpret structured content".to_owned(),
                ),
            );
            return None;
        }
        if !self.consume_ident("from") {
            let span = self.span_here();
            self.error(
                span,
                "expected `from` after read format".to_owned(),
                Some(usage),
            );
            return None;
        }
        let store = self.ident_text("file store after `from`")?;
        if !self.consume_ident("at") {
            let span = self.span_here();
            self.error(
                span,
                "expected `at` after read store".to_owned(),
                Some(usage),
            );
            return None;
        }
        let (path, _) = self.parse_value_expression()?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`read` requires an `as` binding".to_owned(),
                Some(usage),
            );
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::FileRead {
                format,
                store,
                path,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_write(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // write
        let usage =
            "write `write <format> to <store> at <path> { body <expr> mode <mode> } as <binding>`"
                .to_owned();
        let format = self.ident_text("file format after `write`")?;
        // v0 `write` renders the `text`/`markdown` body codecs (UTF-8 bodies).
        // Rendering typed values as json/csv is `export` (deferred, fact-batch).
        if !matches!(format.as_str(), "text" | "markdown") {
            let span = self.span_from(start);
            self.error(
                span,
                format!(
                    "`write {format}` is not supported in v0 — `write` renders only `text` or `markdown` bodies"
                ),
                Some(
                    "use `write text`/`write markdown` for a body; structured `export <format> <Schema>` is deferred".to_owned(),
                ),
            );
            return None;
        }
        if !self.consume_ident("to") {
            let span = self.span_here();
            self.error(
                span,
                "expected `to` after write format".to_owned(),
                Some(usage),
            );
            return None;
        }
        let store = self.ident_text("file store after `to`")?;
        if !self.consume_ident("at") {
            let span = self.span_here();
            self.error(
                span,
                "expected `at` after write store".to_owned(),
                Some(usage),
            );
            return None;
        }
        let (path, _) = self.parse_value_expression()?;
        let fields = self.parse_field_block(false)?;
        let mut body = None;
        let mut mode = None;
        for field in &fields {
            match field.name.as_str() {
                "body" => {
                    if let FieldValue::Expr { source, .. } = &field.value {
                        body = Some(source.clone());
                    }
                }
                "mode" => {
                    if let FieldValue::Expr { source, .. } = &field.value {
                        mode = Some(source.trim().trim_matches('"').to_owned());
                    }
                }
                other => {
                    self.error(
                        field.span,
                        format!(
                            "unknown `write` block field `{other}` (expected `body` or `mode`)"
                        ),
                        Some(usage.clone()),
                    );
                    return None;
                }
            }
        }
        let Some(body) = body else {
            let span = self.span_from(start);
            self.error(
                span,
                "`write` requires a `body` field".to_owned(),
                Some(usage),
            );
            return None;
        };
        // The mode is required: "no silent overwrite" (spec/files.md).
        let Some(mode) = mode else {
            let span = self.span_from(start);
            self.error(
                span,
                "`write` requires an explicit `mode` (create/replace/upsert/append) — no silent overwrite".to_owned(),
                Some(usage),
            );
            return None;
        };
        if !matches!(mode.as_str(), "create" | "replace" | "upsert" | "append") {
            let span = self.span_from(start);
            self.error(
                span,
                format!("unknown write mode `{mode}` (expected create/replace/upsert/append)"),
                Some(usage),
            );
            return None;
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`write` requires an `as` binding".to_owned(),
                Some(usage),
            );
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::FileWrite {
                format,
                store,
                path,
                body,
                mode,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_import(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // import
        let usage =
            "write `import <format> <Schema> from <store> at <path> as <binding>`".to_owned();
        let format = self.ident_text("import format after `import`")?;
        // v0 `import` decodes the structured row codecs into typed facts.
        if !matches!(format.as_str(), "jsonl" | "json" | "csv") {
            let span = self.span_from(start);
            self.error(
                span,
                format!(
                    "`import {format}` is not supported in v0 — `import` decodes `jsonl`, `json`, or `csv`"
                ),
                Some(usage),
            );
            return None;
        }
        let schema = self.ident_text("row schema after import format")?;
        if !self.consume_ident("from") {
            let span = self.span_here();
            self.error(
                span,
                "expected `from` after import schema".to_owned(),
                Some(usage),
            );
            return None;
        }
        let store = self.ident_text("file store after `from`")?;
        if !self.consume_ident("at") {
            let span = self.span_here();
            self.error(
                span,
                "expected `at` after import store".to_owned(),
                Some(usage),
            );
            return None;
        }
        let (path, _) = self.parse_value_expression()?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`import` requires an `as` binding".to_owned(),
                Some(usage),
            );
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::FileImport {
                format,
                schema,
                store,
                path,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_export(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // export
        let usage =
            "write `export <format> <Schema> to <store> at <path> { [where <pred>] mode <mode> } as <binding>`"
                .to_owned();
        let format = self.ident_text("export format after `export`")?;
        if !matches!(format.as_str(), "jsonl" | "json" | "csv") {
            let span = self.span_from(start);
            self.error(
                span,
                format!(
                    "`export {format}` is not supported in v0 — `export` writes `jsonl`, `json`, or `csv`"
                ),
                Some(usage),
            );
            return None;
        }
        let schema = self.ident_text("row schema after export format")?;
        if !self.consume_ident("to") {
            let span = self.span_here();
            self.error(
                span,
                "expected `to` after export schema".to_owned(),
                Some(usage),
            );
            return None;
        }
        let store = self.ident_text("file store after `to`")?;
        if !self.consume_ident("at") {
            let span = self.span_here();
            self.error(
                span,
                "expected `at` after export store".to_owned(),
                Some(usage),
            );
            return None;
        }
        let (path, _) = self.parse_value_expression()?;
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(
                span,
                "expected `{` to open the export block".to_owned(),
                Some(usage),
            );
            return None;
        }
        // Block: an optional `where <pred>` collection filter (DR-0022) + a
        // required `mode`. The schema's facts are the collection; `where` narrows
        // it. `mode` follows the `write` policy (no silent overwrite).
        let mut predicate = None;
        let mut mode = None;
        loop {
            if self.consume_sym('}') {
                break;
            }
            if self.peek().is_none() {
                let span = self.span_here();
                self.error(span, "unclosed export block".to_owned(), Some(usage));
                return None;
            }
            if self.consume_ident("where") {
                let (source, _) = self.parse_value_expression()?;
                predicate = Some(source);
            } else if self.consume_ident("mode") {
                let value = self.ident_text("write mode after `mode`")?;
                mode = Some(value);
            } else {
                let span = self.span_here();
                self.error(
                    span,
                    "unknown export block field (expected `where` or `mode`)".to_owned(),
                    Some(usage.clone()),
                );
                self.recover();
            }
        }
        let Some(mode) = mode else {
            let span = self.span_from(start);
            self.error(
                span,
                "`export` requires an explicit `mode` (create/replace/upsert/append) — no silent overwrite".to_owned(),
                Some(usage),
            );
            return None;
        };
        if !matches!(mode.as_str(), "create" | "replace" | "upsert" | "append") {
            let span = self.span_from(start);
            self.error(
                span,
                format!("unknown write mode `{mode}` (expected create/replace/upsert/append)"),
                Some(usage),
            );
            return None;
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`export` requires an `as` binding".to_owned(),
                Some(usage),
            );
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::FileExport {
                format,
                schema,
                store,
                path,
                predicate,
                mode,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_invoke(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // invoke
        let workflow = self.ident_text("workflow name after `invoke`")?;
        let payload = self.parse_field_block(false)?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        let mut access_grants = Vec::new();
        if !self.parse_effect_modifiers_with_access(
            &mut binding,
            &mut requires,
            &mut timeout_seconds,
            &mut access_grants,
            None,
            None,
        ) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Invoke {
                workflow,
                payload,
                access_grants,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_timer(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // timer
        let span = self.span_here();
        // Absolute deadline: `timer until <time-expr>` (spec/scheduled-time.md).
        if matches!(self.peek().map(|t| &t.tok), Some(Tok::Ident(word)) if word == "until") {
            self.pos += 1; // until
            let until = match self.peek().map(|t| t.tok.clone()) {
                Some(Tok::Str(literal)) => {
                    self.pos += 1;
                    if !is_iso8601_instant(&literal) {
                        self.error(
                            span,
                            format!("invalid time literal `{literal}`"),
                            Some(
                                "use an ISO-8601 instant such as `\"2026-06-15T09:00:00Z\"`"
                                    .to_owned(),
                            ),
                        );
                        return None;
                    }
                    literal
                }
                Some(Tok::Ident(path)) => {
                    // a time-typed path, possibly dotted
                    let mut text = path;
                    self.pos += 1;
                    while matches!(self.peek().map(|t| &t.tok), Some(Tok::Sym('.'))) {
                        self.pos += 1;
                        if let Some(Tok::Ident(seg)) = self.peek().map(|t| t.tok.clone()) {
                            text.push('.');
                            text.push_str(&seg);
                            self.pos += 1;
                        } else {
                            break;
                        }
                    }
                    text
                }
                _ => {
                    self.error(
                        span,
                        "expected a time literal or path after `timer until`".to_owned(),
                        Some("e.g. `timer until \"2026-06-15T09:00:00Z\" as deadline` or `timer until ticket.dueAt as deadline`".to_owned()),
                    );
                    return None;
                }
            };
            let mut binding = None;
            let mut requires = Vec::new();
            let mut timeout_seconds = None;
            if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
                return None;
            }
            if binding.is_none() {
                let span = self.span_from(start);
                self.error(
                    span,
                    "`timer` requires an `as` binding".to_owned(),
                    Some("rules react to the timer with `after <binding> succeeds`".to_owned()),
                );
            }
            return Some(BodyStmt::Effect(EffectStmt {
                kind: BodyEffectKind::Timer {
                    duration_seconds: 0,
                    duration_source: String::new(),
                    until: Some(until),
                },
                binding,
                requires,
                timeout_seconds,
                prompt: None,
                span: self.span_from(start),
            }));
        }
        let Some(Tok::Number(value)) = self.peek().map(|t| t.tok.clone()) else {
            self.error(
                span,
                "expected a duration after `timer`".to_owned(),
                Some(
                    "use `<n><unit>` with unit s, m, h, or d, e.g. `timer 24h as deadline`"
                        .to_owned(),
                ),
            );
            return None;
        };
        self.pos += 1;
        let Some(duration_seconds) = parse_short_duration_seconds(&value).filter(|s| *s > 0) else {
            self.error(
                span,
                format!("invalid timer duration `{value}`"),
                Some("use `<n><unit>` with unit s, m, h, or d".to_owned()),
            );
            return None;
        };
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`timer` requires an `as` binding".to_owned(),
                Some("rules react to the timer with `after <binding> succeeds`".to_owned()),
            );
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Timer {
                duration_seconds,
                duration_source: value,
                until: None,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_cancel(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // cancel
        let binding = self.ident_text("effect binding after `cancel`")?;
        Some(BodyStmt::Cancel {
            binding,
            span: self.span_from(start),
        })
    }

    /// `redact <source> keep [<field>, …] as <out>` (DR-0027): an explicit
    /// information-flow projection. Parses the source binding, the bracketed
    /// comma-separated kept-field list, and the `as` output binding. A redaction
    /// must keep at least one field (keeping nothing releases nothing).
    fn parse_redact(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // redact
        let source = self.ident_text("binding to redact after `redact`")?;
        if !self.consume_ident("keep") {
            let span = self.span_here();
            self.error(
                span,
                "expected `keep [<field>, …]` after the binding".to_owned(),
                Some("write `redact customer keep [id, status] as safe`".to_owned()),
            );
            return None;
        }
        if !self.consume_sym('[') {
            let span = self.span_here();
            self.error(
                span,
                "expected `[` to open the kept-field list".to_owned(),
                Some("write `keep [id, status]`".to_owned()),
            );
            return None;
        }
        let mut keep = Vec::new();
        loop {
            if self.consume_sym(']') {
                break;
            }
            if self.peek().is_none() {
                let span = self.span_here();
                self.error(
                    span,
                    "unclosed kept-field list".to_owned(),
                    Some("add `]`".to_owned()),
                );
                return None;
            }
            let field = self.ident_text("kept field name")?;
            keep.push(field);
            if !self.consume_sym(',') && !self.at_sym(']') {
                let span = self.span_here();
                self.error(
                    span,
                    "expected `,` or `]` in the kept-field list".to_owned(),
                    None,
                );
                return None;
            }
        }
        if !self.consume_ident("as") {
            let span = self.span_here();
            self.error(
                span,
                "`redact` requires an `as <binding>`".to_owned(),
                Some("write `redact customer keep [id] as safe`".to_owned()),
            );
            return None;
        }
        let binding = self.ident_text("output binding after `as`")?;
        if keep.is_empty() {
            let span = self.span_from(start);
            self.error(
                span,
                "`redact` must keep at least one field".to_owned(),
                Some("a redaction that keeps nothing has no value to release".to_owned()),
            );
            return None;
        }
        Some(BodyStmt::Redact {
            source,
            keep,
            binding,
            span: self.span_from(start),
        })
    }

    /// `acquire <lease> for <key-expr> [until ttl] as <slot>`: one atomic
    /// attempt with branchable `held`/`contended` outcomes
    /// (spec/coordination.md).
    fn parse_lease_acquire(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // acquire
        let resource = self.ident_text("lease name after `acquire`")?;
        if !self.consume_ident("for") {
            let span = self.span_here();
            self.error(
                span,
                "expected `for <key>` after the lease name".to_owned(),
                Some("write `acquire deploy_slot for r.env as slot`".to_owned()),
            );
            return None;
        }
        let key_expr = self.dotted_path_text("lease key expression")?;
        let mut until_ttl = false;
        if self.at_ident("until") {
            self.pos += 1;
            if !self.consume_ident("ttl") {
                let span = self.span_here();
                self.error(
                    span,
                    "expected `ttl` after `until`".to_owned(),
                    Some("`acquire ... until ttl` is the fire-and-forget form".to_owned()),
                );
                return None;
            }
            until_ttl = true;
        }
        // `wait <duration>`: bounded retry on contention (spec/coordination.md). The
        // acquire re-attempts on each worker pass until it is `held` or the wait
        // elapses, then reports `contended`.
        let mut wait_seconds = None;
        if self.at_ident("wait") {
            self.pos += 1; // wait
            let span = self.span_here();
            let Some(Tok::Number(value)) = self.peek().map(|t| t.tok.clone()) else {
                self.error(
                    span,
                    "expected a duration after `wait`".to_owned(),
                    Some("use `<n><unit>` with unit s, m, h, or d, e.g. `wait 30s`".to_owned()),
                );
                return None;
            };
            self.pos += 1;
            match parse_short_duration_seconds(&value) {
                Some(seconds) if seconds > 0 => wait_seconds = Some(seconds),
                _ => {
                    self.error(
                        span,
                        format!("invalid wait duration `{value}`"),
                        Some("use `<n><unit>` with unit s, m, h, or d".to_owned()),
                    );
                    return None;
                }
            }
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`acquire` requires an `as` binding".to_owned(),
                Some(
                    "branch on it with `after <binding> held` and `after <binding> contended`"
                        .to_owned(),
                ),
            );
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::LeaseAcquire {
                resource,
                key_expr,
                until_ttl,
                wait_seconds,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    /// `renew <acquire-binding> [until <ttl>] as <b>`: extend a held lease's
    /// TTL before it expires (spec/coordination.md). It names the `as` binding
    /// of the `acquire` it extends, so resource/key never drift, and yields a
    /// branchable `renewed`/`notHeld` outcome.
    fn parse_lease_renew(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // renew
        let acquire_binding = self.ident_text("lease binding after `renew`")?;
        // `until <duration>`: the new TTL. Unlike `acquire`'s `until ttl` keyword
        // (fire-and-forget), renew's `until` takes a duration value, e.g.
        // `until 300s`.
        let mut ttl_seconds = None;
        if self.at_ident("until") {
            self.pos += 1; // until
            let span = self.span_here();
            let Some(Tok::Number(value)) = self.peek().map(|t| t.tok.clone()) else {
                self.error(
                    span,
                    "expected a duration after `until`".to_owned(),
                    Some("use `<n><unit>` with unit s, m, h, or d, e.g. `until 300s`".to_owned()),
                );
                return None;
            };
            self.pos += 1;
            match parse_short_duration_seconds(&value) {
                Some(seconds) if seconds > 0 => ttl_seconds = Some(seconds),
                _ => {
                    self.error(
                        span,
                        format!("invalid ttl duration `{value}`"),
                        Some("use `<n><unit>` with unit s, m, h, or d".to_owned()),
                    );
                    return None;
                }
            }
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`renew` requires an `as` binding".to_owned(),
                Some(
                    "branch on it with `after <binding> renewed` and `after <binding> notHeld`"
                        .to_owned(),
                ),
            );
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::LeaseRenew {
                acquire_binding,
                ttl_seconds,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    /// `append <Schema> { fields } to <ledger> [as x]` (spec/coordination.md).
    fn parse_ledger_append(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // append
        let schema = self.ident_text("entry schema after `append`")?;
        let fields = self.parse_field_block(false)?;
        if !self.consume_ident("to") {
            let span = self.span_here();
            self.error(
                span,
                "expected `to <ledger>` after the entry payload".to_owned(),
                Some("write `append Decision { ... } to decisions`".to_owned()),
            );
            return None;
        }
        let ledger = self.ident_text("ledger name after `to`")?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::LedgerAppend {
                ledger,
                schema,
                fields,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn looks_like_counter_consume(&self) -> bool {
        matches!(self.peek_at(1).map(|t| &t.tok), Some(Tok::Ident(_)))
            && matches!(self.peek_at(2).map(|t| &t.tok), Some(Tok::Ident(word)) if word == "for")
    }

    /// `consume <counter> for <key-expr> amount <expr> as <binding>`: one
    /// atomic consume with branchable `ok`/`over` outcomes
    /// (spec/coordination.md).
    fn parse_counter_consume(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // consume
        let counter = self.ident_text("counter name after `consume`")?;
        if !self.consume_ident("for") {
            let span = self.span_here();
            self.error(
                span,
                "expected `for <key>` after the counter name".to_owned(),
                Some(
                    "write `consume model_budget for t.customer amount t.estTokens as spend`"
                        .to_owned(),
                ),
            );
            return None;
        }
        let key_expr = self.dotted_path_text("counter key expression")?;
        if !self.consume_ident("amount") {
            let span = self.span_here();
            self.error(
                span,
                "expected `amount <expr>` after the counter key".to_owned(),
                Some(
                    "write `consume model_budget for t.customer amount t.estTokens as spend`"
                        .to_owned(),
                ),
            );
            return None;
        }
        let amount_expr = match self.peek().map(|t| t.tok.clone()) {
            Some(Tok::Number(value)) => {
                self.pos += 1;
                value
            }
            Some(Tok::Ident(_)) => self.dotted_path_text("consume amount")?,
            _ => {
                let span = self.span_here();
                self.error(
                    span,
                    "expected a number or path after `amount`".to_owned(),
                    None,
                );
                return None;
            }
        };
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        if binding.is_none() {
            let span = self.span_from(start);
            self.error(
                span,
                "`consume` requires an `as` binding".to_owned(),
                Some(
                    "branch on it with `after <binding> ok` and `after <binding> over`".to_owned(),
                ),
            );
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::CounterConsume {
                counter,
                key_expr,
                amount_expr,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    /// `emit signal <dotted.name> to <instance-expr> { payload }`.
    fn parse_emit_signal(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // emit
                       // `emit milestone "<name>" [of <PayloadClass>] { fields }` (Family C): a
                       // synchronous milestone projection, distinct from the directed
                       // `emit signal ... to ...` effect.
        if self.at_ident("milestone") {
            return self.parse_emit_milestone(start);
        }
        if !self.consume_ident("signal") {
            let span = self.span_here();
            self.error(
                span,
                "the bare `emit <name>` statement was removed from the language; \
                 `emit` must be followed by `signal` or `milestone`"
                    .to_owned(),
                Some("write `emit signal deploy.finished to peer.id { ... }`".to_owned()),
            );
            return None;
        }
        let event = self.dotted_path_text("signal name after `signal`")?;
        if !self.consume_ident("to") {
            let span = self.span_here();
            self.error(
                span,
                "expected `to <target>` after the signal name".to_owned(),
                Some("write `emit signal deploy.finished to peer.id { ... }`".to_owned()),
            );
            return None;
        }
        let target_expr = self.dotted_path_text("target instance after `to`")?;
        // S6: optional `from <binding>` projection (the `record … from`
        // precedent) — shorthand fields become allowed inside the block.
        let from = if self.consume_ident("from") {
            Some(self.ident_text("binding name after `from`")?)
        } else {
            None
        };
        let fields = if from.is_some() && !self.at_sym('{') {
            Vec::new()
        } else {
            self.parse_field_block(from.is_some())?
        };
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Notify {
                target_expr,
                event,
                from,
                fields,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    /// `emit milestone "<name>" [of <PayloadClass>] { fields }` (Family C). The
    /// caller has consumed `emit`; `self` is positioned at the `milestone`
    /// keyword. `start` is the `emit` token index for span tracking.
    fn parse_emit_milestone(&mut self, start: usize) -> Option<BodyStmt> {
        self.pos += 1; // milestone
        let Some(Tok::Str(name)) = self.peek().map(|t| t.tok.clone()) else {
            let span = self.span_here();
            self.error(
                span,
                "expected a quoted milestone name after `milestone`".to_owned(),
                Some(
                    "write `emit milestone \"canary_live\" of CanaryInfo { region \"us\" }`"
                        .to_owned(),
                ),
            );
            return None;
        };
        self.pos += 1;
        // `of <PayloadClass>` is optional: a bare milestone carries no payload
        // and the parent observes it with `after p reaches "<name>"` (no `as`).
        let payload_class = if self.consume_ident("of") {
            Some(self.ident_text("payload class after `of`")?)
        } else {
            None
        };
        let fields = if matches!(self.peek().map(|t| &t.tok), Some(Tok::Sym('{'))) {
            self.parse_field_block(false)?
        } else {
            Vec::new()
        };
        Some(BodyStmt::Milestone {
            name,
            payload_class,
            fields,
            span: self.span_from(start),
        })
    }

    /// A possibly-dotted identifier path, returned as source text.
    fn dotted_path_text(&mut self, label: &str) -> Option<String> {
        let mut text = self.ident_text(label)?;
        while matches!(self.peek().map(|t| &t.tok), Some(Tok::Sym('.'))) {
            self.pos += 1;
            let Some(Tok::Ident(segment)) = self.peek().map(|t| t.tok.clone()) else {
                break;
            };
            text.push('.');
            text.push_str(&segment);
            self.pos += 1;
        }
        Some(text)
    }

    fn parse_exec(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // exec
        let target = match self.advance().map(|t| t.tok) {
            Some(Tok::Str(value)) => ExecTarget::RawCommand(value),
            Some(Tok::Ident(name)) => {
                if !self.at_ident("with") {
                    let span = self.span_here();
                    self.error(
                        span,
                        "expected `with <binding>` after exec capability name".to_owned(),
                        Some(format!(
                            "write `exec {name} with input -> Report as result`"
                        )),
                    );
                    return None;
                }
                self.pos += 1; // with
                let Some(Tok::Ident(stdin_binding)) = self.peek().map(|t| t.tok.clone()) else {
                    let span = self.span_here();
                    self.error(
                        span,
                        "expected a record binding after `with`".to_owned(),
                        Some(format!(
                            "write `exec {name} with input -> Report as result`"
                        )),
                    );
                    return None;
                };
                self.pos += 1;
                ExecTarget::Capability {
                    name,
                    stdin_binding,
                }
            }
            _ => {
                let span = self.span_here();
                self.error(
                    span,
                    "expected a command string or capability name after `exec`".to_owned(),
                    Some(
                        "write `exec \"scripts/run-tests.sh\" as tests` or `exec backup_repo with input -> Report as result`"
                            .to_owned(),
                    ),
                );
                return None;
            }
        };
        // `-> Schema` / `-> each Schema`: typed stdout ingestion
        // (spec/json-ingestion.md).
        let mut parse_target = None;
        if matches!(self.peek().map(|t| &t.tok), Some(Tok::Arrow)) {
            self.pos += 1; // ->
            let each = if self.at_ident("each") {
                self.pos += 1;
                true
            } else {
                false
            };
            let Some(Tok::Ident(schema)) = self.peek().map(|t| t.tok.clone()) else {
                let span = self.span_here();
                self.error(
                    span,
                    "expected a schema name after `->`".to_owned(),
                    Some(
                        "write `exec \"report.sh\" -> Report as x` or `exec \"list.sh\" -> each WorkItem`"
                            .to_owned(),
                    ),
                );
                return None;
            };
            self.pos += 1;
            parse_target = Some(ExecParse { schema, each });
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        match &parse_target {
            Some(parse) if parse.each && binding.is_some() => {
                let span = self.span_from(start);
                self.error(
                    span,
                    "`-> each` produces a stream of facts, not a single binding".to_owned(),
                    Some("drop the `as` binding and react with `when <Schema> as item`".to_owned()),
                );
            }
            Some(parse) if !parse.each && binding.is_none() => {
                let span = self.span_from(start);
                self.error(
                    span,
                    "`->` without `each` parses one value and needs an `as` binding".to_owned(),
                    Some("write `exec \"report.sh\" -> Report as x` and read it with `after x succeeds as r`".to_owned()),
                );
            }
            _ => {}
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::Exec {
                target,
                parse_target,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    // -- tracker verbs ---------------------------------------------------------

    fn parse_tracker_file(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // file
        if !self.consume_ident("issue") {
            let span = self.span_here();
            self.error(
                span,
                "expected `issue` after `file`",
                Some("write `file issue into <tracker> { ... }`".to_owned()),
            );
            return None;
        }
        if !self.consume_ident("into") {
            let span = self.span_here();
            self.error(span, "expected `into <tracker>` after `file issue`", None);
            return None;
        }
        let queue = self.ident_text("tracker name")?;
        let fields = self.parse_field_block(false)?;
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::TrackerFile { queue, fields },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_tracker_claim(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // claim
        let item = self.ident_text("issue binding after `claim`")?;
        if self.at_ident("with") {
            let span = self.span_here();
            self.error(
                span,
                "`claim <issue> with ...` is not supported".to_owned(),
                Some("declare a `tracker` and write `claim <issue> [ttl <dur>] [as x]`".to_owned()),
            );
            self.pos += 1;
            let _ = self.advance();
        }
        // `ttl <duration>`: the claim-TTL clause (spec/std-tracker.md, T3). It
        // takes a duration value, e.g. `claim issue ttl 30m as c`.
        let mut ttl_seconds = None;
        if self.at_ident("ttl") {
            self.pos += 1; // ttl
            let span = self.span_here();
            let Some(Tok::Number(value)) = self.peek().map(|t| t.tok.clone()) else {
                self.error(
                    span,
                    "expected a duration after `ttl`".to_owned(),
                    Some("use `<n><unit>` with unit s, m, h, or d, e.g. `ttl 30m`".to_owned()),
                );
                return None;
            };
            self.pos += 1;
            match parse_short_duration_seconds(&value) {
                Some(seconds) if seconds > 0 => ttl_seconds = Some(seconds),
                _ => {
                    self.error(
                        span,
                        format!("invalid ttl duration `{value}`"),
                        Some("use `<n><unit>` with unit s, m, h, or d".to_owned()),
                    );
                    return None;
                }
            }
        }
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        // The trailing `endorsed` source marker (DR-0051 §2); must come last,
        // exactly as on a `coerce`.
        let endorsed = self.consume_ident("endorsed");
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::TrackerClaim {
                item,
                ttl_seconds,
                endorsed,
            },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_tracker_release(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // release
        let item = self.ident_text("issue binding after `release`")?;
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::TrackerRelease { item },
            binding: None,
            requires: Vec::new(),
            timeout_seconds: None,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    fn parse_tracker_finish(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // finish
        let item = self.ident_text("issue binding after `finish`")?;
        let fields = if self.at_sym('{') {
            self.parse_field_block(false)?
        } else {
            Vec::new()
        };
        // `as <binding>` after the payload — required for `then x <- finish
        // item { … }`, whose desugar re-serializes the finish with a synthetic
        // handle and observes it with `after`.
        let mut binding = None;
        let mut requires = Vec::new();
        let mut timeout_seconds = None;
        if !self.parse_effect_modifiers(&mut binding, &mut requires, &mut timeout_seconds) {
            return None;
        }
        Some(BodyStmt::Effect(EffectStmt {
            kind: BodyEffectKind::TrackerFinish { item, fields },
            binding,
            requires,
            timeout_seconds,
            prompt: None,
            span: self.span_from(start),
        }))
    }

    // -- blocks --------------------------------------------------------------

    /// `during <cond> { … } on lapse [as x] { … }` / `until <cond> { … }`
    /// (DR-0043 Decision 5). The arm is mandatory; the parser accepts the arm
    /// on the region's closing line (`}} on lapse {{`) or on its own line —
    /// tokens carry no line structure.
    fn parse_region(&mut self, until: bool) -> Option<BodyStmt> {
        let start = self.pos;
        let keyword = if until { "until" } else { "during" };
        self.pos += 1;
        let cond_start = self.pos;
        while self.pos < self.tokens.len() && !self.at_sym('{') {
            self.pos += 1;
        }
        if !self.at_sym('{') {
            let span = self.span_here();
            self.error(
                span,
                format!("expected `{{` to open the `{keyword}` region"),
                Some(format!(
                    "write `{keyword} <condition> {{ … }} on lapse {{ … }}`"
                )),
            );
            return None;
        }
        let condition = if self.pos > cond_start {
            let from = self.tokens[cond_start].start;
            let to = self.tokens[self.pos - 1].end;
            self.source[from..to].trim().to_owned()
        } else {
            String::new()
        };
        if condition.is_empty() {
            let span = self.span_from(start);
            self.error(
                span,
                format!("`{keyword}` requires a condition"),
                Some("the condition is a pure query expression, like a guard".to_owned()),
            );
            return None;
        }
        let body_open = self.pos;
        self.pos += 1; // {
        let body_content_start = self
            .tokens
            .get(self.pos)
            .map(|token| self.base + token.start)
            .unwrap_or_else(|| self.base + self.tokens[body_open].end);
        let body = self.parse_statements(true);
        // parse_statements consumed the closing `}` (token before self.pos).
        let body_content_end = self
            .tokens
            .get(self.pos.saturating_sub(1))
            .map(|token| self.base + token.start)
            .unwrap_or(body_content_start);
        let body_span = SourceSpan {
            start: body_content_start,
            end: body_content_end,
        };
        if !(self.consume_ident("on") && self.consume_ident("lapse")) {
            let span = self.span_here();
            self.error(
                span,
                format!("a `{keyword}` region requires its `on lapse {{ … }}` arm"),
                Some(
                    "a reactive condition with no declared consequence would lapse silently; \
                     write `on lapse { … }` (optionally `on lapse as <view> { … }`)"
                        .to_owned(),
                ),
            );
            return None;
        }
        let lapse_binding = if self.consume_ident("as") {
            Some(self.ident_text("progress-view binding after `as`")?)
        } else {
            None
        };
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(span, "expected `{` to open the `on lapse` arm", None);
            return None;
        }
        let lapse_open = self.pos - 1;
        let lapse_content_start = self
            .tokens
            .get(self.pos)
            .map(|token| self.base + token.start)
            .unwrap_or_else(|| self.base + self.tokens[lapse_open].end);
        let lapse_body = self.parse_statements(true);
        let lapse_content_end = self
            .tokens
            .get(self.pos.saturating_sub(1))
            .map(|token| self.base + token.start)
            .unwrap_or(lapse_content_start);
        Some(BodyStmt::Region(RegionBlock {
            until,
            condition,
            body,
            lapse_binding,
            lapse_body,
            body_span,
            lapse_span: SourceSpan {
                start: lapse_content_start,
                end: lapse_content_end,
            },
            span: self.span_from(start),
        }))
    }

    fn parse_after(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // after
        let binding = self.ident_text("effect binding after `after`")?;
        let mut milestone = None;
        let predicate = match self.advance().map(|t| t.tok) {
            Some(Tok::Ident(word)) => match word.as_str() {
                "succeeds" => AfterPredicate::Succeeds,
                "fails" => AfterPredicate::Fails,
                "completes" => AfterPredicate::Completes,
                "cancelled" => AfterPredicate::Cancelled,
                // `after p reaches "<name>" as m` (Family C): the next token is a
                // string literal naming the child milestone being observed. The
                // name is stashed on `AfterBlock.milestone`.
                "reaches" => {
                    let Some(Tok::Str(name)) = self.peek().map(|t| t.tok.clone()) else {
                        let span = self.span_here();
                        self.error(
                            span,
                            "expected a quoted milestone name after `reaches`".to_owned(),
                            Some("write `after p reaches \"canary_live\" as m { ... }`".to_owned()),
                        );
                        return None;
                    };
                    self.pos += 1;
                    milestone = Some(name);
                    AfterPredicate::Reaches
                }
                // `times out` is the two-token spelling of the `TimedOut`
                // terminal status (spec/expression-kernel.md).
                "times" => {
                    if !self.consume_ident("out") {
                        let span = self.span_here();
                        self.error(span, "expected `out` after `times`", None);
                        return None;
                    }
                    AfterPredicate::TimedOut
                }
                "held" => AfterPredicate::Held,
                "contended" => AfterPredicate::Contended,
                "ok" => AfterPredicate::Ok,
                "over" => AfterPredicate::Over,
                "promoted" => AfterPredicate::Promoted,
                "conflicted" => AfterPredicate::Conflicted,
                "applied" => AfterPredicate::Applied,
                "stranded" => AfterPredicate::Stranded,
                other => {
                    let span = self.span_from(start);
                    self.error(
                        span,
                        format!("unsupported `after` predicate `{other}`"),
                        Some(
                            "use `succeeds`, `fails`, `completes`, `times out`, `cancelled`, or a coordination outcome (`held`, `contended`, `ok`, `over`)"
                                .to_owned(),
                        ),
                    );
                    return None;
                }
            },
            _ => {
                let span = self.span_here();
                self.error(
                    span,
                    "expected `succeeds`, `fails`, `completes`, `times out`, or `cancelled`",
                    None,
                );
                return None;
            }
        };
        let alias = if self.consume_ident("as") {
            Some(self.ident_text("alias after `as`")?)
        } else {
            None
        };
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(span, "expected `{` to open the `after` block", None);
            return None;
        }
        let body = self.parse_statements(true);
        Some(BodyStmt::After(AfterBlock {
            binding,
            predicate,
            alias,
            milestone,
            body,
            span: self.span_from(start),
        }))
    }

    fn parse_case(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        self.pos += 1; // case
        let scrutinee = self.ident_text("case scrutinee path")?;
        if !self.consume_sym('{') {
            let span = self.span_here();
            self.error(span, "expected `{` to open the `case` block", None);
            return None;
        }
        let mut branches = Vec::new();
        loop {
            if self.consume_sym('}') {
                break;
            }
            if self.peek().is_none() {
                let span = self.span_here();
                self.error(span, "unclosed `case` block", Some("add `}`".to_owned()));
                break;
            }
            let branch_start = self.pos;
            let pattern = match self.advance().map(|t| t.tok) {
                Some(Tok::Ident(value)) => value,
                Some(Tok::Str(value)) => format!("{value:?}"),
                _ => {
                    let span = self.span_here();
                    self.error(span, "expected a case pattern", None);
                    self.recover();
                    continue;
                }
            };
            let binding = match self.peek().map(|t| t.tok.clone()) {
                // `Variant as binding` (sum types, spec/sum-types.md) — `as`
                // is how every other binding in the language is introduced.
                Some(Tok::Ident(value)) if value == "as" => {
                    self.pos += 1;
                    match self.peek().map(|t| t.tok.clone()) {
                        Some(Tok::Ident(name)) => {
                            self.pos += 1;
                            Some(name)
                        }
                        _ => {
                            let span = self.span_here();
                            self.error(
                                span,
                                "expected a binding name after `as`".to_owned(),
                                Some("write `Variant as payload => { ... }`".to_owned()),
                            );
                            None
                        }
                    }
                }
                Some(Tok::Ident(value)) if value != "where" => {
                    self.pos += 1;
                    Some(value)
                }
                _ => None,
            };
            let guard = if self.consume_ident("where") {
                let guard_start = self.pos;
                // Consume guard tokens up to `=>`.
                while self.peek().is_some()
                    && !matches!(self.peek().map(|t| &t.tok), Some(Tok::FatArrow))
                {
                    self.pos += 1;
                }
                let first = self.tokens.get(guard_start);
                let last = self.tokens.get(self.pos.saturating_sub(1));
                match (first, last) {
                    (Some(first), Some(last)) if guard_start < self.pos => {
                        Some(self.source[first.start..last.end].to_owned())
                    }
                    _ => None,
                }
            } else {
                None
            };
            if !matches!(self.advance().map(|t| t.tok), Some(Tok::FatArrow)) {
                let span = self.span_here();
                self.error(span, "expected `=>` after case pattern", None);
                self.recover();
                continue;
            }
            if !self.consume_sym('{') {
                let span = self.span_here();
                self.error(span, "expected `{` to open the case branch", None);
                self.recover();
                continue;
            }
            let body = self.parse_statements(true);
            branches.push(CaseBranch {
                pattern,
                binding,
                guard,
                body,
                span: self.span_from(branch_start),
            });
        }
        Some(BodyStmt::Case(CaseBlock {
            scrutinee,
            branches,
            span: self.span_from(start),
        }))
    }

    fn parse_terminal(&mut self) -> Option<BodyStmt> {
        let start = self.pos;
        let keyword = match self.advance()?.tok {
            Tok::Ident(value) => value,
            _ => return None,
        };
        let kind = if keyword == "complete" {
            TerminalKind::Complete
        } else {
            TerminalKind::Fail
        };
        let name = self.ident_text("terminal contract name")?;
        // `complete <T> from <binding> { … }`: bounded-type projection. Only valid on
        // `complete` (a failure carries an explicit payload). Shorthand fields in the
        // block copy the source binding's same-named fields, as in `record … from`.
        let from = if kind == TerminalKind::Complete && self.consume_ident("from") {
            Some(self.ident_text("binding name after `from`")?)
        } else {
            None
        };
        // A field block (`complete result { … }`) is the class-shaped form; a bare
        // value (`complete result 0.9`) is the scalar form. `from` always projects
        // fields, so it requires a block.
        let (fields, scalar) =
            if from.is_none() && !matches!(self.peek().map(|t| &t.tok), Some(Tok::Sym('{'))) {
                let (source, expr) = self.parse_value_expression()?;
                (Vec::new(), Some(FieldValue::Expr { source, expr }))
            } else {
                (self.parse_field_block(from.is_some())?, None)
            };
        Some(BodyStmt::Terminal(TerminalStmt {
            kind,
            name,
            from,
            fields,
            scalar,
            span: self.span_from(start),
        }))
    }
}

const STATEMENT_KEYWORDS: &[&str] = &[
    "record", "done", "consume", "tell", "coerce", "prompt", "claim", "release", "renew", "finish",
    "file", "call", "recall", "send", "invoke", "read", "write", "import", "export", "after",
    "case", "complete", "fail", "timer", "cancel", "decide", "exec", "when", "on", "else", "then",
    "redact",
];

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

    fn parse_ok(source: &str) -> BodyAst {
        let (ast, diagnostics) = parse_rule_body(source, 0);
        assert!(diagnostics.is_empty(), "diagnostics: {diagnostics:?}");
        ast
    }

    #[test]
    fn full_line_comments_tokenize_as_nothing() {
        let ast = parse_ok(
            "# leading comment\nrecord Done {\n  note \"x\"\n}\n  # indented comment with braces { } and \"quotes\"\n// slash comments match the top-level lexer\ndone item\n",
        );
        assert_eq!(ast.statements.len(), 2, "comments contribute no statements");
    }

    #[test]
    fn trailing_hash_still_errors() {
        let (_, diagnostics) = parse_rule_body("done item # trailing\n", 0);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("unexpected character `#`")),
            "trailing comments stay illegal: {diagnostics:?}"
        );
    }

    #[test]
    fn blank_full_line_comments_is_byte_preserving_and_fence_aware() {
        let text = "  # a comment\n  tell a as t \"\"\"markdown\n  # heading is content\n  \"\"\"\n  # after fence\n";
        let blanked = blank_full_line_comments(text);
        assert_eq!(blanked.len(), text.len(), "byte length preserved");
        assert!(!blanked.contains("# a comment"));
        assert!(!blanked.contains("# after fence"));
        assert!(
            blanked.contains("# heading is content"),
            "fence interior untouched: {blanked}"
        );
    }

    #[test]
    fn generated_effect_operation_grammar_covers_the_std_constructs() {
        // Drift canary for the build.rs codegen: the table generated from the
        // embedded std manifests (std/manifests/*.json) must contain exactly
        // the seven shipped effect_operation keywords with their target
        // capabilities. A manifest edit that adds, drops, or retargets a
        // keyword shows up here before it shows up in parse behavior.
        let table = EFFECT_OPERATION_GRAMMAR
            .iter()
            .map(|spec| (spec.keyword, spec.target_capability))
            .collect::<Vec<_>>();
        assert_eq!(
            table,
            vec![
                ("recall", "memory.query"),
                ("learn", "memory.write"),
                ("curate", "memory.curate"),
                ("send", "messaging.send"),
                ("promote", "vcs.promote"),
                ("undo", "vcs.undo"),
                ("transport", "vcs.transport"),
            ]
        );
    }

    #[test]
    fn parses_redact_projection() {
        let ast = parse_ok("redact customer keep [id, status] as safe");
        let BodyStmt::Redact {
            source,
            keep,
            binding,
            ..
        } = &ast.statements[0]
        else {
            panic!("expected redact, got {:?}", ast.statements[0]);
        };
        assert_eq!(source, "customer");
        assert_eq!(keep, &["id".to_owned(), "status".to_owned()]);
        assert_eq!(binding, "safe");
    }

    #[test]
    fn parses_complete_from_projection() {
        let ast = parse_ok("complete result from cust {\n  id\n  status\n}");
        let BodyStmt::Terminal(terminal) = &ast.statements[0] else {
            panic!("expected terminal, got {:?}", ast.statements[0]);
        };
        assert_eq!(terminal.kind, TerminalKind::Complete);
        assert_eq!(terminal.name, "result");
        assert_eq!(terminal.from.as_deref(), Some("cust"));
        assert_eq!(terminal.fields.len(), 2);
        assert!(terminal
            .fields
            .iter()
            .all(|f| matches!(f.value, FieldValue::Shorthand)));
    }

    #[test]
    fn rejects_redact_keeping_nothing() {
        let (_, diagnostics) = parse_rule_body("redact customer keep [] as safe", 0);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("keep at least one field")),
            "expected empty-keep rejection, got {diagnostics:?}"
        );
    }

    #[test]
    fn parses_single_line_record_fields() {
        let ast = parse_ok(r#"record Item { id "a" status "done" }"#);
        let BodyStmt::Record(record) = &ast.statements[0] else {
            panic!("expected record");
        };
        assert_eq!(record.schema, "Item");
        assert_eq!(record.fields.len(), 2);
        assert_eq!(record.fields[0].name, "id");
        assert_eq!(record.fields[1].name, "status");
    }

    #[test]
    fn parses_multi_line_record_with_expressions() {
        let ast = parse_ok(
            "record Job {\n  id job.id\n  attempts job.attempts + 1\n  status \"pending\"\n}",
        );
        let BodyStmt::Record(record) = &ast.statements[0] else {
            panic!("expected record");
        };
        assert_eq!(record.fields[1].name, "attempts");
        let FieldValue::Expr { source, .. } = &record.fields[1].value else {
            panic!("expected expression value");
        };
        assert_eq!(source, "job.attempts + 1");
    }

    #[test]
    fn parses_done_with_replacement() {
        let ast = parse_ok("done task -> record Done {\n  id task.id\n}");
        let BodyStmt::Done {
            binding,
            replacement,
            ..
        } = &ast.statements[0]
        else {
            panic!("expected done");
        };
        assert_eq!(binding, "task");
        assert!(replacement.is_some());
    }

    #[test]
    fn consume_done_alias_is_removed() {
        // The bare `consume <binding>` alias for `done` was removed; it now
        // errors with a migration hint rather than parsing as a done terminal.
        let (ast, diagnostics) = parse_rule_body("consume task", 0);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("`consume` was removed")),
            "expected a removed-alias diagnostic, got {diagnostics:?}"
        );
        assert!(
            !matches!(ast.statements.first(), Some(BodyStmt::Done { .. })),
            "removed alias must not parse as a done terminal"
        );
    }

    #[test]
    fn counter_consume_verb_still_parses() {
        // The live counter verb `consume <counter> for ...` is unaffected.
        let ast = parse_ok("consume budget for t.id amount 1 as spend");
        assert!(
            matches!(
                ast.statements.first(),
                Some(BodyStmt::Effect(EffectStmt {
                    kind: BodyEffectKind::CounterConsume { .. },
                    ..
                }))
            ),
            "counter consume must still parse, got {:?}",
            ast.statements.first()
        );
    }

    #[test]
    fn parses_tell_with_modifiers_and_prompt() {
        let ast = parse_ok(
            "tell worker requires [\"agent.tell\"] as turn timeout 10m \"\"\"markdown\nDo it.\n\"\"\"",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        assert_eq!(effect.binding.as_deref(), Some("turn"));
        assert_eq!(effect.requires, vec!["agent.tell".to_owned()]);
        assert_eq!(effect.timeout_seconds, Some(600));
        let prompt = effect.prompt.as_ref().expect("prompt");
        assert_eq!(prompt.content_type.as_deref(), Some("markdown"));
        assert_eq!(prompt.text, "Do it.");
    }

    #[test]
    fn parses_prompt_effect() {
        let ast = parse_ok(
            "prompt \"\"\"markdown\nSummarize this.\n\"\"\" using fixture requires [\"model.invoke\"] as answer timeout 10m",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Prompt { provider } = &effect.kind else {
            panic!("expected prompt");
        };
        assert_eq!(provider.as_deref(), Some("fixture"));
        assert_eq!(effect.binding.as_deref(), Some("answer"));
        assert_eq!(effect.requires, vec!["model.invoke".to_owned()]);
        assert_eq!(effect.timeout_seconds, Some(600));
        let prompt = effect.prompt.as_ref().expect("prompt");
        assert_eq!(prompt.content_type.as_deref(), Some("markdown"));
        assert_eq!(prompt.text, "Summarize this.");
    }

    #[test]
    fn parses_tell_with_access_grants() {
        let ast = parse_ok(
            "tell coder as turn\n  with access to project_memory {\n    recall for issue\n    learn for issue\n  }\n  with access to project_files {\n    read [\"docs/**\"]\n  }\n\"Work the issue.\"",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Tell {
            target,
            access_grants,
            ..
        } = &effect.kind
        else {
            panic!("expected tell");
        };
        assert_eq!(target, "coder");
        assert_eq!(effect.binding.as_deref(), Some("turn"));
        assert_eq!(access_grants.len(), 2);

        let memory = &access_grants[0];
        assert_eq!(memory.resource, "project_memory");
        assert_eq!(memory.operations.len(), 2);
        assert_eq!(memory.operations[0].operation, "recall");
        assert_eq!(memory.operations[0].target.as_deref(), Some("issue"));
        assert_eq!(memory.operations[1].operation, "learn");

        let files = &access_grants[1];
        assert_eq!(files.resource, "project_files");
        assert_eq!(files.operations.len(), 1);
        assert_eq!(files.operations[0].operation, "read");
        assert_eq!(files.operations[0].globs, vec!["docs/**".to_owned()]);
    }

    #[test]
    fn reports_unsupported_with_context_modifier() {
        let (_, diagnostics) = parse_rule_body("tell coder with context memory \"go\"", 0);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("not supported yet")),
            "{diagnostics:?}"
        );
    }

    #[test]
    fn parses_tell_with_turn_scoped_skills() {
        // `with skills [...]` interleaves with `with access to` around the prompt.
        let ast = parse_ok(
            "tell coder as turn\n  with skills [\"review\", \"lint\"]\n  with access to project_files {\n    read [\"src/**\"]\n  }\n\"Work it.\"",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Tell {
            skills,
            access_grants,
            ..
        } = &effect.kind
        else {
            panic!("expected tell");
        };
        assert_eq!(skills, &vec!["review".to_owned(), "lint".to_owned()]);
        assert_eq!(
            access_grants.len(),
            1,
            "access grant still parsed alongside"
        );

        // `invoke ... with skills` is NOT accepted (skills are tell-scoped).
        let (_, diagnostics) = parse_rule_body("invoke Build { x task.x } with skills [\"a\"]", 0);
        assert!(
            !diagnostics.is_empty(),
            "invoke must reject a turn-scoped skills pin"
        );
    }

    #[test]
    fn rejects_unknown_statement() {
        let (_, diagnostics) = parse_rule_body("frobnicate task", 0);
        assert!(diagnostics.iter().any(|d| d
            .message
            .contains("unknown rule body statement `frobnicate`")));
    }

    #[test]
    fn parses_emit_signal() {
        let ast = parse_ok(
            "emit signal deploy.finished to peer.id {\n  service deployed.service\n  status deployed.status\n} as sent",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        assert_eq!(effect.binding.as_deref(), Some("sent"));
        let BodyEffectKind::Notify {
            target_expr,
            event,
            fields,
            ..
        } = &effect.kind
        else {
            panic!("expected signal delivery effect");
        };
        assert_eq!(target_expr, "peer.id");
        assert_eq!(event, "deploy.finished");
        assert_eq!(fields.len(), 2);
    }

    #[test]
    fn rejects_emit_without_signal_delivery_shape() {
        let (_, diagnostics) = parse_rule_body("emit event.name", 0);
        assert!(diagnostics
            .iter()
            .any(|d| d.message.contains("was removed from the language")));
    }

    #[test]
    fn parses_nested_after_blocks() {
        let ast = parse_ok(
            "tell worker as turn \"go\"\n\nafter turn succeeds as done {\n  coerce review(done.summary) as verdict\n\n  after verdict succeeds as v {\n    record Out {\n      ok v.ok\n    }\n  }\n}",
        );
        assert_eq!(ast.statements.len(), 2);
        let BodyStmt::After(after) = &ast.statements[1] else {
            panic!("expected after");
        };
        assert_eq!(after.predicate, AfterPredicate::Succeeds);
        assert_eq!(after.alias.as_deref(), Some("done"));
        assert!(matches!(after.body[1], BodyStmt::After(_)));
    }

    #[test]
    fn parses_after_times_out_branch() {
        let ast = parse_ok(
            "exec \"report.sh\" -> Report as job\n\nafter job times out as t {\n  cancel job\n}",
        );
        let BodyStmt::After(after) = &ast.statements[1] else {
            panic!("expected after");
        };
        assert_eq!(after.predicate, AfterPredicate::TimedOut);
        assert_eq!(after.predicate.as_str(), "times out");
        assert_eq!(after.alias.as_deref(), Some("t"));
    }

    #[test]
    fn parses_after_cancelled_branch() {
        let ast = parse_ok(
            "exec \"report.sh\" -> Report as job\n\nafter job cancelled as c {\n  cancel job\n}",
        );
        let BodyStmt::After(after) = &ast.statements[1] else {
            panic!("expected after");
        };
        assert_eq!(after.predicate, AfterPredicate::Cancelled);
        assert_eq!(after.predicate.as_str(), "cancelled");
        assert_eq!(after.alias.as_deref(), Some("c"));
    }

    #[test]
    fn rejects_times_without_out() {
        let (_, diagnostics) = parse_rule_body("after job times { cancel job }", 0);
        assert!(diagnostics
            .iter()
            .any(|d| d.message.contains("expected `out` after `times`")));
    }

    #[test]
    fn rejects_unknown_after_predicate() {
        let (_, diagnostics) = parse_rule_body("after job explodes { cancel job }", 0);
        assert!(diagnostics.iter().any(|d| d
            .message
            .contains("unsupported `after` predicate `explodes`")));
    }

    #[test]
    fn parses_timer_and_cancel() {
        let ast =
            parse_ok("timer 24h as deadline\n\nafter deadline succeeds {\n  cancel signoff\n}");
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected timer effect");
        };
        assert!(matches!(
            effect.kind,
            BodyEffectKind::Timer {
                duration_seconds: 86400,
                ..
            }
        ));
        let BodyStmt::After(after) = &ast.statements[1] else {
            panic!("expected after");
        };
        assert!(matches!(after.body[0], BodyStmt::Cancel { .. }));
    }

    #[test]
    fn parses_decide_with_result_shape() {
        let ast = parse_ok("decide \"Fixed?\" -> { fixed bool, reason string } as verdict");
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Decide { result_fields } = &effect.kind else {
            panic!("expected decide");
        };
        assert_eq!(result_fields.len(), 2);
        assert_eq!(effect.binding.as_deref(), Some("verdict"));
    }

    #[test]
    fn parses_tracker_verbs() {
        let ast = parse_ok(
            "file issue into backlog {\n  title \"Fix login\"\n  body \"Repro...\"\n}\n\nclaim item as lease\nrelease item\nfinish item {\n  summary turn.summary\n}",
        );
        assert_eq!(ast.statements.len(), 4);
        assert!(matches!(
            &ast.statements[0],
            BodyStmt::Effect(EffectStmt { kind: BodyEffectKind::TrackerFile { queue, .. }, .. }) if queue == "backlog"
        ));
        assert!(matches!(
            &ast.statements[1],
            BodyStmt::Effect(EffectStmt { kind: BodyEffectKind::TrackerClaim { .. }, binding: Some(b), .. }) if b == "lease"
        ));
    }

    #[test]
    fn parses_exec() {
        let ast = parse_ok("exec \"scripts/run-tests.sh\" as tests timeout 5m");
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        assert!(matches!(&effect.kind, BodyEffectKind::Exec {
                target: ExecTarget::RawCommand(command),
                ..
            } if command == "scripts/run-tests.sh"));
        assert_eq!(effect.timeout_seconds, Some(300));
    }

    #[test]
    fn parses_coerce_endorsed_marker() {
        // the trailing `endorsed` source marker (I-IFC3) sets the flag.
        let ast = parse_ok("coerce classify(msg.content) as verdict endorsed");
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        assert!(matches!(
            &effect.kind,
            BodyEffectKind::Coerce { name, endorsed: true, .. } if name == "classify"
        ));
        // without the marker, the flag is false.
        let plain = parse_ok("coerce classify(msg.content) as verdict");
        let BodyStmt::Effect(effect) = &plain.statements[0] else {
            panic!("expected effect");
        };
        assert!(matches!(
            &effect.kind,
            BodyEffectKind::Coerce {
                endorsed: false,
                declassified: false,
                ..
            }
        ));
        // `declassified` sets its flag; both markers may appear together.
        let both = parse_ok("coerce classify(msg.content) as verdict endorsed declassified");
        let BodyStmt::Effect(effect) = &both.statements[0] else {
            panic!("expected effect");
        };
        assert!(matches!(
            &effect.kind,
            BodyEffectKind::Coerce {
                endorsed: true,
                declassified: true,
                ..
            }
        ));
    }

    #[test]
    fn parses_exec_capability() {
        let ast = parse_ok("exec backup_repo with request -> Report as result");
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        assert!(matches!(&effect.kind, BodyEffectKind::Exec {
            target: ExecTarget::Capability { name, stdin_binding },
            parse_target: Some(ExecParse { schema, each: false }),
        } if name == "backup_repo" && stdin_binding == "request" && schema == "Report"));
        assert_eq!(effect.binding.as_deref(), Some("result"));
    }

    #[test]
    fn parses_case_with_branches() {
        let ast = parse_ok(
            "after turn completes {\n  case turn {\n    Completed as done => {\n      record Ok {\n        summary done.summary\n      }\n    }\n    Failed as failure => {\n      record Bad {\n        reason failure.reason\n      }\n    }\n  }\n}",
        );
        let BodyStmt::After(after) = &ast.statements[0] else {
            panic!("expected after");
        };
        let BodyStmt::Case(case) = &after.body[0] else {
            panic!("expected case");
        };
        assert_eq!(case.branches.len(), 2);
        assert_eq!(case.branches[0].pattern, "Completed");
        assert_eq!(case.branches[0].binding.as_deref(), Some("done"));
    }

    #[test]
    fn rule_mode_rejects_flow_statements() {
        let (_, diagnostics) = parse_rule_body("on fails {\n  cancel x\n}", 0);
        assert!(diagnostics
            .iter()
            .any(|d| d.message.contains("not rule body statements")));
    }

    #[test]
    fn unknown_effect_modifier_is_rejected_with_span() {
        let (_, diagnostics) = parse_rule_body("tell worker as turn frobnicate \"go\"", 0);
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("expected a prompt string")),
            "{diagnostics:?}"
        );
    }

    #[test]
    fn from_block_supports_shorthand_and_overrides() {
        let ast = parse_ok(
            "done task -> record ReviewedPoem from task {\n  provider poet\n  language\n  topic\n  turn poemTurn\n  status \"reviewed\"\n}",
        );
        let BodyStmt::Done {
            replacement: Some(record),
            ..
        } = &ast.statements[0]
        else {
            panic!("expected replacement record");
        };
        assert_eq!(record.from.as_deref(), Some("task"));
        let names: Vec<_> = record.fields.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["provider", "language", "topic", "turn", "status"]
        );
        assert!(matches!(record.fields[1].value, FieldValue::Shorthand));
        assert!(matches!(record.fields[3].value, FieldValue::Expr { .. }));
    }

    #[test]
    fn invoke_with_nested_payload() {
        let ast = parse_ok(
            "invoke ReviewPhase {\n  phase PhaseReviewRequest {\n    id phase.id\n    title phase.title\n  }\n} as review",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Invoke {
            workflow, payload, ..
        } = &effect.kind
        else {
            panic!("expected invoke");
        };
        assert_eq!(workflow, "ReviewPhase");
        assert!(matches!(payload[0].value, FieldValue::Nested { .. }));
    }

    #[test]
    fn parses_invoke_with_access_grants() {
        let ast = parse_ok(
            "invoke Child {\n  task Task { id ticket.id }\n}\n  with access to project_files {\n    read [\"docs/**\"]\n  }\n  as child",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Invoke {
            workflow,
            payload,
            access_grants,
        } = &effect.kind
        else {
            panic!("expected invoke");
        };
        assert_eq!(workflow, "Child");
        assert_eq!(effect.binding.as_deref(), Some("child"));
        assert!(matches!(payload[0].value, FieldValue::Nested { .. }));
        assert_eq!(access_grants.len(), 1);
        assert_eq!(access_grants[0].resource, "project_files");
        assert_eq!(access_grants[0].operations[0].operation, "read");
        assert_eq!(
            access_grants[0].operations[0].globs,
            vec!["docs/**".to_owned()]
        );
    }

    #[test]
    fn parses_invoke_with_resource_less_access_grant_shorthand() {
        let ast = parse_ok(
            "invoke Child {\n  task Task { id ticket.id }\n}\n  with access to {\n    project_memory {\n      recall for ticket\n    }\n    project_files {\n      read [\"docs/**\"]\n    }\n  }\n  as child",
        );
        let BodyStmt::Effect(effect) = &ast.statements[0] else {
            panic!("expected effect");
        };
        let BodyEffectKind::Invoke { access_grants, .. } = &effect.kind else {
            panic!("expected invoke");
        };
        assert_eq!(effect.binding.as_deref(), Some("child"));
        assert_eq!(access_grants.len(), 2);

        let memory = &access_grants[0];
        assert_eq!(memory.resource, "project_memory");
        assert_eq!(memory.operations[0].operation, "recall");
        assert_eq!(memory.operations[0].target.as_deref(), Some("ticket"));

        let files = &access_grants[1];
        assert_eq!(files.resource, "project_files");
        assert_eq!(files.operations[0].operation, "read");
        assert_eq!(files.operations[0].globs, vec!["docs/**".to_owned()]);
    }

    #[test]
    fn rejects_empty_resource_less_access_grant_shorthand() {
        let (_, diagnostics) = parse_rule_body(
            "invoke Child { task task }\n  with access to {\n  }\n  as child",
            0,
        );
        assert!(
            diagnostics
                .iter()
                .any(|d| d.message.contains("grants no resources")),
            "{diagnostics:?}"
        );
    }

    #[test]
    fn single_line_terminal_payload_parses() {
        let ast = parse_ok("complete result { total 2 }");
        let BodyStmt::Terminal(terminal) = &ast.statements[0] else {
            panic!("expected terminal");
        };
        assert_eq!(terminal.fields.len(), 1);
        assert_eq!(terminal.fields[0].name, "total");
    }

    #[test]
    fn spans_are_absolute() {
        let (ast, _) = parse_rule_body("record Item {\n  id \"a\"\n}", 100);
        let BodyStmt::Record(record) = &ast.statements[0] else {
            panic!("expected record");
        };
        assert_eq!(record.span.start, 100);
        assert!(record.span.end > 100);
    }
}