whipplescript-parser 0.5.2

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
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
//! Source parser for `.whip` programs.
//!
//! The v0 grammar is still stabilizing, so this crate uses a small
//! hand-written parser. It preserves source spans and keeps rule/effect bodies
//! as source text until the typed IR is ready to lower them.

mod action_expand;
mod canonical;
pub use canonical::{canonical_declarations, canonical_program_hash, DeclCanon};
pub mod body;
mod body_print;
mod format;
mod lowering;
use format::*;
pub use format::{format_program, format_program_preserving_comments, FormatOutput};
use lowering::*;
mod syntax;
// The lexer/parser front end moved out whole; these three were public API
// before the move and are re-exported so the crate's surface is unchanged.
use syntax::*;
pub use syntax::{lex_comments, parse_program, parser_stage, string_and_comment_spans};
mod then_expand;

use std::{
    collections::{BTreeMap, BTreeSet, VecDeque},
    fmt,
};
use whipplescript_core::{
    ContractRegistry, EffectContract, LibraryRegistration, TypedOutputValidation,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SourceSpan {
    pub start: usize,
    pub end: usize,
}

impl SourceSpan {
    fn join(self, other: Self) -> Self {
        Self {
            start: self.start,
            end: other.end,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Diagnostic {
    pub span: SourceSpan,
    pub message: String,
    pub suggestion: Option<String>,
    /// Secondary spans carrying supporting context (spec/error-handling.md "Spans
    /// And Labels"): a `note`-style related-information label pointing at a
    /// definition, prior claim, or other related site. Empty for most
    /// diagnostics; surfaced in CLI text, JSON reports, and LSP
    /// `relatedInformation`.
    pub related: Vec<RelatedInfo>,
}

/// A secondary span + short label attached to a [`Diagnostic`] as related
/// information (never a top-level diagnostic of its own).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RelatedInfo {
    pub span: SourceSpan,
    pub message: String,
}

impl Diagnostic {
    /// Attaches a related-information label at `span` (builder style, so the
    /// common no-related case stays a plain struct literal that only needs the
    /// new field defaulted).
    pub fn with_related(mut self, span: SourceSpan, message: impl Into<String>) -> Self {
        self.related.push(RelatedInfo {
            span,
            message: message.into(),
        });
        self
    }
}

/// The marker that introduced a comment, preserved so a formatter can re-emit it
/// faithfully.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CommentMarker {
    /// `# …`
    Hash,
    /// `// …`
    Slash,
}

/// A source comment captured by the lexer. Comments are kept out of the token
/// stream (so the parser is unaffected) but retained here so tooling — `whip fmt`,
/// the LSP — can preserve them. `text` is the trimmed content after the marker;
/// `span` covers the marker through end of line (exclusive of the newline).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Comment {
    pub marker: CommentMarker,
    pub text: String,
    pub span: SourceSpan,
}

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

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Program {
    pub workflow: Option<Ident>,
    pub workflow_tags: Vec<TagDecl>,
    pub workflow_description: Option<StringLiteral>,
    pub explicit_workflow_body: bool,
    pub workflows: Vec<WorkflowDecl>,
    pub patterns: Vec<PatternDecl>,
    pub items: Vec<Item>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkflowDecl {
    pub name: Ident,
    pub tags: Vec<TagDecl>,
    pub description: Option<StringLiteral>,
    pub items: Vec<Item>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Item {
    Include(IncludeDecl),
    Use(UseDecl),
    Pattern(PatternDecl),
    Apply(ApplyDecl),
    WorkflowContract(WorkflowContractDecl),
    Harness(HarnessDecl),
    Tracker(TrackerDecl),
    Channel(ChannelDecl),
    Credential(CredentialDecl),
    Stream(StreamDecl),
    Gauge(GaugeDecl),
    Mark(MarkDecl),
    Campaign(CampaignDecl),
    FileStore(FileStoreDecl),
    MemoryPool(MemoryPoolDecl),
    Action(ActionDecl),
    Agent(AgentDecl),
    Enum(EnumDecl),
    Event(EventDecl),
    // Boxed: SourceDecl carries the ingress path/url/emit surface and is by far
    // the largest Item variant; boxing keeps the enum small (clippy large_enum_variant).
    Source(Box<SourceDecl>),
    Test(TestDecl),
    Lease(LeaseDecl),
    Ledger(LedgerDecl),
    Counter(CounterDecl),
    Class(ClassDecl),
    Table(TableDecl),
    Coerce(CoerceDecl),
    Assert(AssertDecl),
    Rule(RuleDecl),
}

impl Item {
    /// Source span of this top-level item, used to interleave preserved comments.
    fn span(&self) -> SourceSpan {
        match self {
            Self::Include(decl) => decl.path.span,
            Self::Use(decl) => decl.name.span,
            Self::Pattern(decl) => decl.span,
            Self::Apply(decl) => decl.span,
            Self::WorkflowContract(decl) => decl.span,
            Self::Harness(decl) => decl.span,
            Self::Tracker(decl) => decl.span,
            Self::Channel(decl) => decl.span,
            Self::Credential(decl) => decl.span,
            Self::Stream(decl) => decl.span,
            Self::Gauge(decl) => decl.span,
            Self::Mark(decl) => decl.span,
            Self::Campaign(decl) => decl.span,
            Self::FileStore(decl) => decl.span,
            Self::MemoryPool(decl) => decl.span,
            Self::Action(decl) => decl.span,
            Self::Agent(decl) => decl.span,
            Self::Enum(decl) => decl.span,
            Self::Event(decl) => decl.span,
            Self::Source(decl) => decl.span,
            Self::Test(decl) => decl.span,
            Self::Lease(decl) => decl.span,
            Self::Ledger(decl) => decl.span,
            Self::Counter(decl) => decl.span,
            Self::Class(decl) => decl.span,
            Self::Table(decl) => decl.span,
            Self::Coerce(decl) => decl.span,
            Self::Assert(decl) => decl.span,
            Self::Rule(decl) => decl.span,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PatternDecl {
    pub name: Ident,
    pub type_params: Vec<Ident>,
    pub items: Vec<Item>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApplyDecl {
    pub pattern: Ident,
    pub type_args: Vec<TypeSyntax>,
    pub alias: Ident,
    pub body: BlockSource,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IncludeDecl {
    pub path: StringLiteral,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkflowContractDecl {
    pub kind: WorkflowContractKind,
    pub name: Ident,
    pub ty: TypeSyntax,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WorkflowContractKind {
    Input,
    Output,
    Failure,
}

impl WorkflowContractKind {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Input => "input",
            Self::Output => "output",
            Self::Failure => "failure",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AssertDecl {
    pub tags: Vec<TagDecl>,
    pub description: Option<StringLiteral>,
    pub expr: String,
    pub span: SourceSpan,
}

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UseDecl {
    pub name: StringLiteral,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HarnessDecl {
    pub name: Ident,
    pub kind: Ident,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TrackerDecl {
    pub name: Ident,
    pub provider: Ident,
    pub span: SourceSpan,
}

/// `channel <name> { provider <p> [workspace <w>] [destination "<d>"] }`
/// (std.messaging): a named communication route through a provider. The bare
/// `channel` construct shape is reserved by the platform for `std.messaging`
/// (spec/messaging.md), so third-party packages cannot author channel-like
/// semantics with weaker guarantees. Lowers to a `metadata_only` declaration
/// (like `queue`); the runtime messaging provider is later-stage work.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChannelDecl {
    pub name: Ident,
    pub provider: Ident,
    pub workspace: Option<Ident>,
    pub destination: Option<StringLiteral>,
    pub span: SourceSpan,
}

/// `credential <name> { kind <kind> }` (std.custody; DR-0053 §5): a bare
/// handle naming a custodian entry — governance supplies reality via
/// `grant credential … -> credential:<addr>`, and material never appears in
/// source. `kind` exists so the checker can statically reject an operation
/// the credential cannot perform (`sign … with` a `bearer`); the custodian's
/// registered kind is authoritative and mismatch is a check error. Kinds are
/// spelled with underscores in source (`hmac_sha256`) and normalize to the
/// protocol's kebab-case.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CredentialDecl {
    pub name: Ident,
    pub kind: Ident,
    pub span: SourceSpan,
}

/// `stream <name> { members [<agent>, ...] [staleness <duration>] }`
/// (std.vcs; DR-0052 Decision 5): a declared collaboration — a named
/// shared line whose member agents' session lines home to it, syncing
/// greedily in-stream and promoting to mainline through one gated
/// boundary. Members are agent declarations (every session of that
/// agent homes here); `staleness` is the §7.1 bound. Metadata-only
/// lowering, like `queue`/`channel`; the runtime workstream tier is the
/// enforcement seam.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StreamDecl {
    pub name: Ident,
    pub members: Vec<Ident>,
    pub staleness_seconds: Option<u64>,
    pub span: SourceSpan,
}

/// `mark "<name>" after <site>` (experimentation subsystem §4.2): a named
/// cut point. The runtime stamps a `mark.reached` event when the named
/// site commits on any run, so every run's meaningful moments are
/// addressable — `whip pin <run> at <mark>` freezes the prefix as a
/// scenario, and regeneration replays that prefix and re-executes only
/// the suffix. Names are stable across edits (event offsets shift, marks
/// don't). Deliberately a separate declaration from `milestone`
/// (child→parent lifecycle signaling vs. event-log position).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MarkDecl {
    pub name: StringLiteral,
    /// The committing site the cut rides: a rule name (dotted for
    /// flow-generated segments).
    pub site: String,
    pub site_span: SourceSpan,
    pub span: SourceSpan,
}

/// `gauge <name> [on <site>] { judge via ... [expect ...] [inputs ...] }`
/// (experimentation subsystem §4.2): a named quality dimension — a site, a
/// judge, optionally a bar. The sibling of `test`: deterministic expectation
/// vs. stochastic expectation, one family. Core grammar (hand-parsed): the
/// `judge via` tagged union and the bar form are outside the declaration
/// family's shape. Bars use the word forms `at least` / `at most` because
/// the declaration tokenizer deliberately steps over `>=`/`<=` (the same
/// reason field presence conditions use `is`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GaugeDecl {
    pub name: Ident,
    /// Optional `on <dotted.site>` designation. v1 records it (identity and
    /// forward-compat with site-scoped judging); ambient scoring judges the
    /// run's terminal view.
    pub site: Option<String>,
    pub site_span: Option<SourceSpan>,
    pub judge: GaugeJudge,
    pub expect: Option<GaugeBar>,
    /// Derived gauges: other gauges whose scores feed this gauge's exec
    /// judge (`inputs a, b`). Deterministic composition — the settled cure
    /// for composite objectives (no weights feature, ever).
    pub inputs: Vec<GaugeRef>,
    pub span: SourceSpan,
}

/// The generalized judge slot: `judge via coerce <Name>(<args>) |
/// prompt "<t>" | exec "<cmd>" | labels "<source>"`. Coerce judges carry
/// EXPLICIT argument paths (settled 2026-07-14): each names the record
/// value feeding the parameter (`input.ticket.title`,
/// `facts.Assessment.priority`), or the single reserved `record` passes
/// the whole judge-input record — the binding is written down and
/// versioned, never inferred.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GaugeJudge {
    Coerce(Ident, Vec<String>),
    Prompt(StringLiteral),
    Exec(StringLiteral),
    Labels(StringLiteral),
}

/// An optional bar: the default decision bar for settle/campaign gates.
/// `expect P(<field>) at least 0.9` (chance-shaped) or
/// `expect p10 at least 0.7` / `expect mean at most 800` (stat-shaped).
/// Thresholds keep their exact source text (`Eq`-safe, format-exact);
/// consumers parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GaugeBar {
    pub subject: GaugeBarSubject,
    /// `true` = `at least`, `false` = `at most`.
    pub at_least: bool,
    pub threshold: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GaugeBarSubject {
    /// `P(<field>)`: probability the judge's boolean output field holds.
    Chance { field: Ident },
    /// A named statistic of the score distribution: `mean`, `p10`, `p90`, …
    Stat { stat: Ident },
}

/// A (possibly dotted) gauge reference: user gauges are bare idents, the
/// built-in resource gauges are namespaced (`std.spend` / `std.latency` /
/// `std.tokens`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GaugeRef {
    pub name: String,
    pub span: SourceSpan,
}

/// `campaign <name> { ascend … [reach …] [guard …] [sacrifice …] }`
/// (improve design note §3): versioned, diffable objective intent at higher
/// ceremony than a CLI invocation — the partition of the gauge vector.
/// Unnamed gauges are guarded by default; `guard` widens a band, `sacrifice`
/// releases a gauge, `reach` sets a target that becomes a hard bound.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignDecl {
    pub name: Ident,
    pub ascend: Vec<GaugeRef>,
    pub reach: Vec<CampaignReach>,
    pub guard: Vec<CampaignGuard>,
    pub sacrifice: Vec<GaugeRef>,
    /// `proposer redacted`: campaign-attached stratified reflection — the
    /// proposer sees aggregates only, never scenario contents (leakage
    /// policy, improve note §7; settled 2026-07-11).
    pub proposer_redacted: bool,
    pub span: SourceSpan,
}

/// `reach <gauge> at least 0.9` / `reach std.latency at most 800ms`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignReach {
    pub gauge: GaugeRef,
    pub at_least: bool,
    pub threshold: String,
    /// Optional trailing unit ident (`ms`, `s`); recorded verbatim.
    pub unit: Option<String>,
    pub span: SourceSpan,
}

/// `guard <gauge> within 2 percent`: an indifference-band override.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignGuard {
    pub gauge: GaugeRef,
    pub band_percent: String,
    pub span: SourceSpan,
}

/// `file store <name> { root "<dir>" }` (std.files): a capability-scoped file
/// store identity with a literal root directory. v0 is a local storage boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileStoreDecl {
    pub name: Ident,
    pub root: String,
    pub read_globs: Vec<String>,
    pub write_globs: Vec<String>,
    /// Optional `provider <name>` clause (std.files v1, spec/std-files.md
    /// "Surface"): the store's backing provider, defaulting to `local` when
    /// absent. Unknown providers are rejected at check time.
    pub provider: Option<Ident>,
    /// Source spans of each clause keyword (`root` / the `allow` of read / write),
    /// so `whip fmt` can interleave own-line and trailing body comments by position
    /// (the body otherwise rebuilds from the AST, dropping comments).
    pub root_span: Option<SourceSpan>,
    pub read_span: Option<SourceSpan>,
    pub write_span: Option<SourceSpan>,
    pub provider_span: Option<SourceSpan>,
    pub span: SourceSpan,
}

/// `memory pool <name> { context limit <n> }` (std.memory, MEM-1): a named
/// durable memory place. Mirrors `file store` as a `declaration_block` /
/// `metadata_only` construct providing `Resource<MemoryPool>`. v1 pools are
/// provider-less; `context limit <n>` (optional, non-negative) is the recall
/// packing budget. Unknown clauses are rejected (file-store precedent).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MemoryPoolDecl {
    pub name: Ident,
    pub context_limit: Option<u64>,
    /// Source span of the `context` clause keyword, so `whip fmt` can interleave
    /// body comments by position (file-store precedent).
    pub context_limit_span: Option<SourceSpan>,
    pub span: SourceSpan,
}

/// One typed parameter of an `action` template (DR-0023).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ActionParam {
    pub name: Ident,
    pub ty: TypeSyntax,
    pub span: SourceSpan,
}

/// `action <name>(<param: type>, …) { <effect chain> }` (DR-0023): a static,
/// hygienic, inline-expanded template over rule-body effect chains. Consumed by
/// `expand_action_calls` before lowering; never a runtime construct.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ActionDecl {
    pub name: Ident,
    pub params: Vec<ActionParam>,
    pub body: BlockSource,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AgentDecl {
    pub name: Ident,
    pub harness: Option<Ident>,
    /// `agent Foo delegated to <provider>` (DR-0034 Decision 2): the surface
    /// spelling of a Delegated agent. Names the foreign provider kind directly;
    /// `agent Foo { … }` without it is Managed by default.
    pub delegated_to: Option<Ident>,
    pub fields: Vec<AgentField>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AgentField {
    Provider(Ident),
    Profile(StringLiteral),
    Capacity(u32, SourceSpan),
    Skills(Vec<StringLiteral>, SourceSpan),
    Capabilities(Vec<StringLiteral>, SourceSpan),
    /// `requires [session.resume, turn.cancel]`: portable feature-class
    /// requirements (DR-0015 taxonomy; spec/std-agent.md slice 6). Entries are
    /// dotted feature-class names, validated for taxonomy membership at
    /// lowering and against the provider's feature report by the CLI.
    Requires(Vec<Ident>, SourceSpan),
    /// `tools [Foo, Bar]`: the workflows this agent may invoke as typed tools
    /// (DR-0025). Entries are workflow names resolved against the program/packages.
    Tools(Vec<Ident>, SourceSpan),
    /// `compaction <strategy>`: the owned-harness conversation-compaction strategy
    /// (context-assembly Phase 5). One of `summarize`, `hard_reset`, `tool_results`,
    /// `none`.
    Compaction(Ident),
    /// `thread <mode>`: owned-harness conversation continuation across tells
    /// (the chat-shaped instance v1). `continue` seeds each
    /// new tell from the agent's latest completed-turn transcript in this
    /// instance; `fresh` (the default) starts every tell from scratch.
    Thread(Ident),
    /// `settings <sources>`: which ambient-config sources a Delegated harness may
    /// read when assembling its own context (DR-0034 Decision 4). One of `project`,
    /// `user`, `none`. Unset means the provider's own default.
    Settings(Ident),
    Unknown {
        name: Ident,
        span: SourceSpan,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumDecl {
    pub name: Ident,
    pub variants: Vec<EnumVariantDecl>,
    pub span: SourceSpan,
}

/// One enum variant: bare (`Accept`) or data-carrying with a brace body that
/// reuses the class field grammar (sum types, spec/sum-types.md).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumVariantDecl {
    pub name: Ident,
    pub fields: Vec<ClassField>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassDecl {
    pub name: Ident,
    pub fields: Vec<ClassField>,
    pub span: SourceSpan,
}

/// Coordination resources (spec/coordination.md): a closed family of shared,
/// workspace-scoped resources with typed keys, atomic branchable operations,
/// and mandatory bounds (`ttl`/`retain`/`cap`+`reset`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeaseDecl {
    pub name: Ident,
    pub key_type: Ident,
    pub slots: u32,
    pub ttl_seconds: u64,
    pub shared: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LedgerDecl {
    pub name: Ident,
    pub entry_schema: Ident,
    pub partition_field: Ident,
    pub retain_seconds: u64,
    pub shared: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CounterDecl {
    pub name: Ident,
    pub key_type: Ident,
    pub cap: i64,
    pub reset: String,
    /// IANA timezone anchoring the reset-period boundary (std.coord slice 3);
    /// `None` anchors to UTC and draws a default-UTC warning.
    pub timezone: Option<String>,
    pub shared: bool,
    pub span: SourceSpan,
}

/// A typed external-signal declaration (`signal deploy.finished { ... }`):
/// the ingress manifest naming a dotted event and its payload schema
/// (spec/event-ingress.md).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EventDecl {
    /// Dotted lowercase signal name (`deploy.finished`).
    pub name: String,
    pub name_span: SourceSpan,
    pub fields: Vec<ClassField>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassField {
    pub name: Ident,
    pub ty: TypeSyntax,
    /// `@key`: this field is the class's natural key (used for import per-row
    /// idempotency, spec/std-library/files.md). At most one per class in v0.
    pub is_key: bool,
    /// Family B (discriminant-string schemas): `<field> <Type> when <disc> == "<lit>"`
    /// — this field is present only when the literal-union discriminant field `disc`
    /// equals `lit`. `(discriminant field name, required literal)`.
    pub presence_condition: Option<(String, String)>,
    pub span: SourceSpan,
}

/// A top-level source declaration: `source <provider> as <name> { ... }` or
/// `source clock as <name> { ... }`. Lowers through the `source_declaration`
/// construct family to a `signal_source` (generic provider) or `clock_source`
/// (the `clock` provider) admission template (spec/std-time.md,
/// spec/construct-grammar.md). A source admits a durable signal fact; it never
/// fires a rule directly.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceDecl {
    /// `as <name>` — the source instance name.
    pub name: Ident,
    /// The provider keyword (`clock`) or a generic provider identifier.
    pub provider: Ident,
    /// Recurrence/timezone/missed policy; `Some` only for the `clock` provider.
    pub clock: Option<ClockPolicy>,
    /// `path "<file>"` — `file` provider, line mode (exactly one of
    /// `path`/`watch`); rejected elsewhere. The file is read line-by-line; each
    /// non-empty line is admitted once as a durable signal fact
    /// (spec/std-time.md admission semantics, append-only).
    pub path: Option<StringLiteral>,
    /// `watch "<glob>"` — `file` provider, occurrence mode (exactly one of
    /// `path`/`watch`); rejected elsewhere (spec/std-ingress.md I2a). Each
    /// matched file is admitted once per new (path, content-hash) occurrence:
    /// a dropped file admits once, an unchanged file never re-admits, a
    /// content change re-admits. Content READING stays std.files.
    pub watch: Option<StringLiteral>,
    /// `url "<url>"` — required for the `http` provider, rejected elsewhere. The
    /// URL is GET'd and its JSON-array body admitted one element per signal,
    /// keyed by (source, element index) so re-polls are idempotent (append-only).
    pub url: Option<StringLiteral>,
    /// `dedup <observe>.<field>` — optional provider delivery-id source for
    /// `file` (line mode) and `http` sources (spec/std-ingress.md I2a): the
    /// named observation field becomes the admission key instead of the
    /// positional ordinal, so a re-ordered or head-inserted feed still admits
    /// each delivery exactly once.
    pub dedup: Option<SourceValue>,
    /// `observe as <binding>` — binds the provider observation schema.
    pub observe_binding: Ident,
    /// `emit <signal> { <field> <value> ... }` — maps the observation into the
    /// declared signal payload.
    pub emit: SourceEmit,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClockPolicy {
    pub recurrence: Recurrence,
    pub timezone: Option<StringLiteral>,
    pub missed: Option<MissedPolicy>,
    pub span: SourceSpan,
}

/// Recurrence forms from spec/std-time.md (conservative first surface).
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Recurrence {
    /// `at <hh:mm>` — a single scheduled occurrence.
    At { time: TimeOfDay, span: SourceSpan },
    /// `every <duration>` — interval occurrences.
    EveryDuration {
        seconds: u64,
        source: String,
        span: SourceSpan,
    },
    /// `every <calendar-pattern> at <hh:mm>` — calendar occurrences.
    EveryCalendar {
        pattern: CalendarPattern,
        time: TimeOfDay,
        span: SourceSpan,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CalendarPattern {
    Day,
    Weekday,
    Weekly(Weekday),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TimeOfDay {
    pub hour: u8,
    pub minute: u8,
    pub span: SourceSpan,
}

/// Missed-occurrence policy from spec/std-time.md. No silent default: a recurring
/// source must declare one (enforced by the checker).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MissedPolicy {
    Skip,
    Coalesce,
    CatchUp { limit: u32 },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceEmit {
    /// Dotted lowercase signal name materialized by this source.
    pub signal: String,
    pub signal_span: SourceSpan,
    /// S6: `emit <signal> from <binding> [{ overrides }]` — copy the
    /// observation's same-named fields, bounded to the signal's declared
    /// fields, with the block overriding (the `record … from` semantics).
    pub from: Option<Ident>,
    pub fields: Vec<SourceEmitField>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceEmitField {
    pub name: Ident,
    pub value: SourceValue,
    pub span: SourceSpan,
}

/// A value mapped into an emitted signal field: an observation path
/// (`tick.scheduled_at`) or a literal.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SourceValue {
    Path {
        binding: Ident,
        segments: Vec<Ident>,
        span: SourceSpan,
    },
    String(StringLiteral),
    Number(String, SourceSpan),
}

/// A deterministic test scenario (spec/workflow-testing.md). Validated by
/// `whip check`; excluded from compile/run IR; executed by `whip test`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TestDecl {
    pub name: StringLiteral,
    /// Optional `workflow <Name>` header binding the scenario to one workflow
    /// in a multi-workflow bundle (spec/workflow-testing.md). Single-workflow
    /// files may omit it and bind implicitly.
    pub workflow: Option<Ident>,
    pub clauses: Vec<TestClause>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TestClause {
    Given(GivenClause),
    Stub(StubClause),
    Run(RunClause),
    Expect(ExpectClause),
}

/// A `<field> <expr>` mapping inside a `given` record body. `value` is the source
/// text of the expression (parsed via `parse_expression` when validated), matching
/// how guards and assertions capture expressions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TestField {
    pub name: Ident,
    pub value: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GivenClause {
    Input {
        fields: Vec<TestField>,
        span: SourceSpan,
    },
    Fact {
        ty: Ident,
        fields: Vec<TestField>,
        span: SourceSpan,
    },
    Signal {
        name: String,
        fields: Vec<TestField>,
        span: SourceSpan,
    },
    Clock {
        at: StringLiteral,
        span: SourceSpan,
    },
    Tracker {
        tracker: String,
        fields: Vec<TestField>,
        span: SourceSpan,
    },
    /// `given file <store> at <path> "<content>"` seeds a fixture file in the
    /// named `file store` so a `read` during `whip test` resolves deterministic
    /// content (the harness redirects the store root to a temp dir).
    File {
        store: String,
        path: StringLiteral,
        content: StringLiteral,
        span: SourceSpan,
    },
}

/// `stub <surface…> <outcome> [record | string]`. The surface path and outcome
/// are kept as tokens; provider-specific validation happens in the harness.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StubClause {
    /// Surface path segments (each may be dotted, e.g. `script.run`); the trailing
    /// segment is the outcome.
    pub surface: Vec<String>,
    pub outcome: String,
    pub payload: Option<StubPayload>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StubPayload {
    Record(Vec<TestField>),
    Message(StringLiteral),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RunClause {
    pub kind: RunKind,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RunKind {
    UntilIdle,
    UntilWorkflowCompleted,
    UntilWorkflowFailed,
    ForSteps(u32),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExpectClause {
    pub target: ExpectTarget,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExpectTarget {
    WorkflowCompleted,
    WorkflowFailed { failure: Option<Ident> },
    Rule { name: Ident, status: RuleStatus },
    Effect { name: String, status: EffectStatus },
    Diagnostic { code: String },
    NoEffect { name: String },
    Projection(ProjQuery),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RuleStatus {
    Fired,
    FiredTimes(u32),
    DidNotFire,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EffectStatus {
    Requested,
    Completed,
    Failed,
}

/// A projection query: `<noun> exists | count <predicate> is <N> | where <predicate>`.
/// The predicate reuses the guard expression kernel, restricted to projection
/// fields. The noun is a dotted fact name, so a scenario can assert over runtime
/// facts such as `agent.turn.completed` as well as single-identifier user facts.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjQuery {
    pub noun: String,
    pub kind: ProjQueryKind,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProjQueryKind {
    Exists,
    Count { predicate: String, count: u32 },
    Where { predicate: String },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TableDecl {
    pub name: Ident,
    pub tags: Vec<TagDecl>,
    pub description: Option<StringLiteral>,
    pub schema: Ident,
    pub rows: Vec<TableRow>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TableRow {
    pub body: BlockSource,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CoerceDecl {
    pub name: Ident,
    pub params: Vec<ParamDecl>,
    pub output: TypeSyntax,
    pub body: BlockSource,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParamDecl {
    pub name: Ident,
    pub ty: TypeSyntax,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TypeSyntax {
    Primitive {
        name: String,
        span: SourceSpan,
    },
    LiteralString {
        value: String,
        span: SourceSpan,
    },
    Ref {
        name: Ident,
    },
    AgentRef {
        agents: Vec<Ident>,
        span: SourceSpan,
    },
    Optional {
        inner: Box<TypeSyntax>,
        span: SourceSpan,
    },
    Array {
        inner: Box<TypeSyntax>,
        span: SourceSpan,
    },
    Map {
        inner: Box<TypeSyntax>,
        span: SourceSpan,
    },
    Union {
        variants: Vec<TypeSyntax>,
        span: SourceSpan,
    },
}

impl TypeSyntax {
    fn span(&self) -> SourceSpan {
        match self {
            Self::Primitive { span, .. }
            | Self::LiteralString { span, .. }
            | Self::Optional { span, .. }
            | Self::Array { span, .. }
            | Self::Map { span, .. }
            | Self::Union { span, .. }
            | Self::AgentRef { span, .. } => *span,
            Self::Ref { name } => name.span,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuleDecl {
    pub name: Ident,
    pub tags: Vec<TagDecl>,
    pub description: Option<StringLiteral>,
    pub whens: Vec<WhenClause>,
    pub body: BlockSource,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WhenClause {
    pub text: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BlockSource {
    pub text: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseOutput {
    pub program: Program,
    pub diagnostics: Vec<Diagnostic>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompileOutput {
    pub ir: Option<IrProgram>,
    pub diagnostics: Vec<Diagnostic>,
    /// Non-fatal diagnostics (deprecations, style); never block compilation.
    pub warnings: Vec<Diagnostic>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrProgram {
    pub workflow: String,
    pub source_tags: Vec<IrSourceTag>,
    pub source_descriptions: Vec<IrSourceDescription>,
    pub includes: Vec<IrInclude>,
    pub pattern_applications: Vec<IrPatternApplication>,
    pub workflow_contracts: Vec<IrWorkflowContract>,
    pub uses: Vec<IrUse>,
    pub harnesses: Vec<IrHarness>,
    pub trackers: Vec<IrTracker>,
    pub streams: Vec<IrStream>,
    pub channels: Vec<IrChannel>,
    pub credentials: Vec<IrCredential>,
    pub gauges: Vec<IrGauge>,
    pub marks: Vec<IrMark>,
    pub campaigns: Vec<IrCampaign>,
    pub file_stores: Vec<IrFileStore>,
    pub memory_pools: Vec<IrMemoryPool>,
    pub events: Vec<IrEvent>,
    pub sources: Vec<IrSource>,
    pub tests: Vec<IrTest>,
    pub leases: Vec<IrLease>,
    pub ledgers: Vec<IrLedger>,
    pub counters: Vec<IrCounter>,
    pub shared_coordination_usage: Vec<IrSharedCoordinationUsage>,
    pub schemas: Vec<IrSchema>,
    pub agents: Vec<IrAgent>,
    pub coerces: Vec<IrCoerce>,
    pub assertions: Vec<IrAssertion>,
    pub rules: Vec<IrRule>,
    pub rule_dependencies: Vec<IrRuleDependency>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrSharedCoordinationUsage {
    pub resource: String,
    pub workflow_principals: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrSourceTag {
    pub name: String,
    pub target_kind: String,
    pub target: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrSourceDescription {
    pub value: String,
    pub target_kind: String,
    pub target: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrPatternApplication {
    pub pattern: String,
    pub alias: String,
    pub type_args: Vec<IrType>,
    pub value_args: Vec<IrPatternArgument>,
    pub generated: Vec<String>,
    /// Source span of the `pattern <Name> { ... }` DEFINITION this application
    /// expanded, so provenance can point back at where the reused shape lives.
    pub definition_span: SourceSpan,
    /// Source span of the `apply <Name> as <alias> { ... }` APPLICATION site.
    pub application_span: SourceSpan,
}

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrWorkflowContract {
    pub kind: IrWorkflowContractKind,
    pub name: String,
    pub ty: IrType,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrWorkflowContractKind {
    Input,
    Output,
    Failure,
}

impl IrWorkflowContractKind {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Input => "input",
            Self::Output => "output",
            Self::Failure => "failure",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrInclude {
    pub path: String,
    pub source_hash: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrAssertion {
    pub expr: IrExpression,
    pub projection_reads: Vec<IrProjectionRead>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrExpression {
    pub source: String,
    pub expr: Expr,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrUse {
    pub kind: IrUseKind,
    pub name: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrUseKind {
    Package,
}

/// One lowered `stream` declaration (std.vcs): the workstream tier's
/// declared membership + staleness bound. Runtime homing reads this.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrStream {
    pub name: String,
    pub members: Vec<String>,
    pub member_spans: Vec<SourceSpan>,
    pub staleness_seconds: Option<u64>,
    pub span: SourceSpan,
}

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

/// A lowered `channel` declaration (std.messaging): the channel identity, its
/// provider, and optional workspace/destination config. Lowering class is
/// `metadata_only`; the runtime messaging provider consumes it later.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrChannel {
    pub name: String,
    pub provider: String,
    pub workspace: Option<String>,
    pub destination: Option<String>,
    pub span: SourceSpan,
}

/// A lowered `credential` declaration (DR-0053 §5): a handle plus its
/// declared kind, normalized to the custody protocol's kebab-case. Metadata
/// only — reality (material, sealing rung, grants) lives with the custodian
/// and governance, never in the program.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCredential {
    pub name: String,
    /// Kebab-case credential kind (`bearer`, `hmac-sha256`, …).
    pub kind: String,
    pub span: SourceSpan,
}

/// A lowered `mark` declaration: a named cut point riding a committing
/// site. `metadata_only`; the runtime stamps `mark.reached` events, the
/// improve store pins scenarios at them.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrMark {
    pub name: String,
    pub site: String,
    pub span: SourceSpan,
}

/// A lowered `gauge` declaration (experimentation subsystem): the binding of
/// a judge to a quality dimension, versioning with the program. Lowering
/// class is `metadata_only`; the evidence engine (`whip evidence` /
/// `whip improve`) consumes it at runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrGauge {
    pub name: String,
    pub site: Option<String>,
    /// `coerce` | `prompt` | `exec` | `labels`.
    pub judge_kind: String,
    /// The judge target: coerce name, prompt template, exec command, or
    /// labels source path.
    pub judge_target: String,
    /// Coerce judges only: the explicit record paths feeding the coerce
    /// function's parameters, in declaration order (`input.…`,
    /// `facts.<Class>.<field>`, or the single reserved `record`). Empty =
    /// declared without arguments (parses, but is not scoreable).
    pub judge_args: Vec<String>,
    pub expect: Option<IrGaugeBar>,
    pub inputs: Vec<String>,
    pub span: SourceSpan,
}

/// A lowered gauge bar. `form` is `chance` (`P(field)`) or `stat`
/// (`p10`/`mean`/…); `op` is `>=` (`at least`) or `<=` (`at most`);
/// `threshold` keeps its exact source text — consumers parse.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrGaugeBar {
    pub form: String,
    pub subject: String,
    pub op: String,
    pub threshold: String,
}

/// A lowered `campaign` declaration (improve design note §3): the named,
/// versioned partition of the gauge vector. `metadata_only`; consumed by
/// `whip improve <name>`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCampaign {
    pub name: String,
    pub ascend: Vec<String>,
    pub reach: Vec<IrCampaignReach>,
    pub guard: Vec<IrCampaignGuard>,
    pub sacrifice: Vec<String>,
    /// Campaign-attached stratified reflection (`proposer redacted`).
    pub proposer_redacted: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCampaignReach {
    pub gauge: String,
    pub op: String,
    pub threshold: String,
    pub unit: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCampaignGuard {
    pub gauge: String,
    pub band_percent: String,
}

/// A lowered `file store` declaration (std.files): the store identity + its
/// literal local root directory, consumed by the runtime file provider.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrFileStore {
    pub name: String,
    pub root: String,
    /// Path globs (relative to `root`) a `read` may touch; empty = any path
    /// inside the root (mounting the root is the read consent). Enforced at
    /// runtime in addition to root-containment.
    pub read_globs: Vec<String>,
    /// Path globs a `write` may touch. S4: stores are READ-ONLY by default —
    /// empty means writes are DENIED (checked at compile time and enforced
    /// fail-closed at runtime); declaring `allow write [...]` permits and
    /// bounds them.
    pub write_globs: Vec<String>,
    /// Declared `provider <name>` clause; `None` = the default `local`
    /// provider (spec/std-files.md "Providers"). Serialized to the snapshot
    /// only when declared, so provider-less stores keep their prior `.ir`.
    pub provider: Option<String>,
}

/// A lowered `memory pool` declaration (std.memory, MEM-1): the pool identity +
/// its optional recall context-limit budget. `metadata_only` — provides
/// `Resource<MemoryPool>`; providers read `context_limit` from the effect input.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrMemoryPool {
    pub name: String,
    /// Optional recall packing budget (`context limit <n>`); providers read it
    /// from the `capability.call` effect input like any other argument.
    pub context_limit: Option<u64>,
}

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrSchema {
    Enum(IrEnum),
    Class(IrClass),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrEnum {
    pub name: String,
    pub variants: Vec<String>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrClass {
    pub name: String,
    pub fields: Vec<IrClassField>,
    pub span: SourceSpan,
}

/// A declared external event: the typed ingress manifest
/// (spec/event-ingress.md). Dotted name, class-shaped payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrEvent {
    pub name: String,
    pub fields: Vec<IrClassField>,
    pub span: SourceSpan,
}

/// A lowered source declaration (spec/std-time.md). `is_clock` selects the
/// `clock_source` lowering; otherwise `signal_source`. Both lower through the
/// `source_declaration` construct family and admit a durable signal fact.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrSource {
    pub name: String,
    pub provider: String,
    pub is_clock: bool,
    /// The `file` provider: reads `path` line-by-line and admits one signal per
    /// non-empty line, keyed by (source, line index) so re-reads are idempotent.
    pub is_file: bool,
    /// The `http` provider: GETs `url`, parses a JSON array, and admits one
    /// signal per element, keyed by (source, element index) so re-polls are
    /// idempotent.
    pub is_http: bool,
    pub recurrence: Option<Recurrence>,
    pub timezone: Option<String>,
    pub missed: Option<MissedPolicy>,
    /// `path "<file>"` — the file read line-by-line by a `file` source in line
    /// mode (`None` otherwise; exactly one of `path`/`watch`).
    pub path: Option<String>,
    /// `watch "<glob>"` — the glob a `file` source polls in occurrence mode
    /// (`None` otherwise): one signal per new (path, content-hash) occurrence.
    pub watch: Option<String>,
    /// `url "<url>"` — the endpoint GET'd by an `http` source (`None` otherwise).
    pub url: Option<String>,
    /// `dedup <observe>.<field>` — the observation field carrying the provider
    /// delivery id for `file` (line mode) / `http` sources; replaces the
    /// positional-ordinal admission key when declared.
    pub dedup_field: Option<String>,
    pub observe_binding: String,
    pub emit_signal: String,
    /// S6 `emit … from` — the projection source binding; when set, the
    /// signal's declared fields not overridden in `emit_fields` are expanded
    /// to copies off this binding after all declarations lower.
    pub emit_from: Option<String>,
    pub emit_fields: Vec<IrSourceEmitField>,
    pub span: SourceSpan,
}

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

/// A lowered test scenario (spec/workflow-testing.md). Tests are excluded from
/// the executable IR (`compile`/`run` ignore them); `whip check` validates them
/// and `whip test` runs them. The clause detail is retained for the harness.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrTest {
    pub name: String,
    pub workflow: Option<String>,
    pub clauses: Vec<TestClause>,
    pub span: SourceSpan,
}

/// Coordination resources (spec/coordination.md), lowered.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrLease {
    pub name: String,
    pub key_type: String,
    pub slots: u32,
    pub ttl_seconds: u64,
    pub shared: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrLedger {
    pub name: String,
    pub entry_schema: String,
    pub partition_field: String,
    pub retain_seconds: u64,
    pub shared: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCounter {
    pub name: String,
    pub key_type: String,
    pub cap: i64,
    pub reset: String,
    /// IANA timezone anchoring the reset-period boundary; `None` = UTC.
    pub timezone: Option<String>,
    pub shared: bool,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrClassField {
    pub name: String,
    pub ty: IrType,
    /// `@key`: this field is the class's natural key (import per-row idempotency).
    pub is_key: bool,
    /// Family B presence condition: `(discriminant field name, required literal)`.
    /// When set, the field is present only when the discriminant equals the literal
    /// (spec/decision-records/discriminated-families-design.md §5.7).
    pub presence_condition: Option<(String, String)>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrType {
    Primitive(IrPrimitiveType),
    LiteralString(String),
    Ref(String),
    AgentRef(Vec<String>),
    Object(Vec<IrClassField>),
    Optional(Box<IrType>),
    Array(Box<IrType>),
    Map(Box<IrType>),
    Union(Vec<IrType>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrPrimitiveType {
    String,
    Int,
    Float,
    Bool,
    Null,
    Duration,
    Time,
    Image,
    Audio,
    Pdf,
    Video,
    /// DR-0053 §5: the carrier of credential custody. A `secret` value can be
    /// bound, passed, stored in a field, and placed in an effect position —
    /// and no operation anywhere in the language or runtime yields its
    /// material (`models/maude/credential-no-eliminator.maude`).
    Secret,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrAgent {
    pub name: String,
    /// Where the declaration sits, so a diagnostic about this agent's PROVIDER
    /// can point at the line that binds it rather than only at the `tell` that
    /// tripped over it (DR-0062). The binding is per-agent and the fix is almost
    /// always here, not at the call site.
    ///
    /// Not part of the `.ir` snapshot: analysis-facing metadata, like
    /// `IrEffectNode::agent`.
    pub span: SourceSpan,
    pub harness: Option<String>,
    pub provider: Option<String>,
    pub profile: Option<String>,
    pub capacity: Option<u32>,
    pub skills: Vec<String>,
    pub capabilities: Vec<String>,
    /// Portable feature requirements (`requires [<feature.class>]`, DR-0015 /
    /// spec/std-agent.md slice 6): taxonomy classes the selected provider's
    /// accepted feature report must state as supported.
    pub requires: Vec<String>,
    /// Workflows this agent may invoke as typed tools (DR-0025 `tools [...]`).
    pub tools: Vec<String>,
    /// Owned-harness conversation-compaction strategy (context-assembly Phase 5):
    /// `summarize` (default), `hard_reset`, `tool_results`, or `none`. `None` uses
    /// the harness default.
    pub compaction: Option<String>,
    /// Owned-harness thread continuation across tells:
    /// `continue` or `fresh`. `None` = `fresh` (every tell starts from scratch).
    pub thread: Option<String>,
    /// Ambient-config sources a Delegated harness may read (DR-0034 Decision 4):
    /// `project`, `user`, or `none`. `None` means the provider's own default —
    /// deliberately NOT the crippled empty set.
    pub settings: Option<String>,
    /// The harness class (DR-0034): `Managed` (WhippleScript is the runtime) vs
    /// `Delegated` (a foreign runtime that assembles its own context). Derived from
    /// the resolved provider/harness kind at lowering.
    pub harness_class: HarnessClass,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrCoerce {
    pub name: String,
    /// Where the declaration sits, so a diagnostic about the endpoint this
    /// coerce reaches can point at its `provider` clause (DR-0062), the same way
    /// an agent's does. Not part of the `.ir` snapshot.
    pub span: SourceSpan,
    pub params: Vec<IrParam>,
    pub output: IrType,
    pub body: String,
    /// The backend named by the declaration's `provider <name>` clause, surfaced
    /// so information-flow analysis can treat THIS endpoint as the principal a
    /// `coerce` egresses to (DR-0062). `None` when the declaration names none —
    /// the backend is then whatever the selection ladder resolves at runtime, so
    /// there is no static endpoint identity to govern by.
    ///
    /// Not part of the `.ir` snapshot: like `IrEffectNode::agent`, this is
    /// analysis-facing metadata, not lowered program shape.
    pub provider: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrParam {
    pub name: String,
    pub ty: IrType,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRule {
    pub name: String,
    pub whens: Vec<IrWhen>,
    pub body: String,
    pub metadata: IrRuleMetadata,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrWhen {
    pub source: String,
    pub pattern: String,
    pub guard: Option<IrExpression>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRuleDependency {
    pub producer: String,
    pub consumer: String,
    pub fact: String,
}

/// DR-0043 Decision 5: one effect the region contains, with the level-1
/// `after` scope the kernel keys its effect id under.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRegionEffect {
    pub binding: String,
    pub scope: Option<(String, String)>,
}

/// DR-0043 Decision 5: a rule's `during`/`until` region, pre-rendered as the
/// three body variants the kernel lowers against. `IrRule.body` itself is the
/// condition-HOLDS variant (region spliced inline), so every existing text
/// scanner and effect-id derivation is untouched; the kernel swaps in
/// `body_removed` (region gone -- post-lapse suppression) or `body_lapsed`
/// (region replaced by its arm) per the region's durable state. NOT rendered
/// into the .ir snapshot (derived, deterministic).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRegion {
    pub until: bool,
    /// Guard-grammar condition text; the kernel parses and evaluates it
    /// atomically inside each advancing commit.
    pub condition: String,
    pub lapse_binding: Option<String>,
    pub effects: Vec<IrRegionEffect>,
    pub body_removed: String,
    pub body_lapsed: String,
    /// The `on lapse` arm's own text, without the ambient statements that
    /// `body_lapsed` splices around it. The arm is the only part of the rule no
    /// other pass sees (the canonical body is the HOLDS variant), so it is
    /// validated separately and must not re-report the ambient lines.
    pub arm_content: String,
    /// The `(scrutinee, pattern)` chain of the `case` arms enclosing the region,
    /// outermost first. Family B narrowing of the lapse arm starts from the
    /// allowances those arms grant, not from the rule top.
    pub arm_case_arms: Vec<(String, String)>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct IrRuleMetadata {
    pub fact_reads: Vec<String>,
    pub projection_reads: Vec<IrProjectionRead>,
    pub fact_writes: Vec<String>,
    pub record_sources: Vec<IrRecordSource>,
    pub fact_consumes: Vec<String>,
    pub effects: Vec<IrEffectNode>,
    pub dependencies: Vec<IrEffectDependency>,
    /// DR-0043: the rule's `during`/`until` region (at most one in v1).
    pub region: Option<IrRegion>,
    pub case_branches: Vec<IrRuleCaseBranch>,
    pub terminal_outputs: Vec<IrTerminalOutput>,
    pub terminal_branches: Vec<IrTerminalCaseBranch>,
    /// The output bindings this rule `complete`s (the `name` of each `complete
    /// <binding> {…}` in the body, recursing into after/case/branch/handler blocks).
    /// Surfaced for the information-flow checker: a `complete result` returns a value
    /// to the workflow's invoker, an egress sink at the invoker boundary (DR-0030 X2).
    /// IFC-only — deliberately NOT rendered in the `.ir` snapshot, so it adds no
    /// golden/hash churn.
    pub terminal_completes: Vec<String>,
    /// The `redact <source> keep [..] as <out>` projections in this rule body
    /// (recursing into after/case/branch/handler blocks). Surfaced for the
    /// information-flow value-flow engine: a redaction is the explicit crossing at
    /// which the rule-level opaque join box is refined — the projected binding
    /// carries only the kept fields' labels (DR-0027, proven in
    /// models/lean/Whipple/Redaction.lean). IFC-only — NOT rendered in the `.ir`
    /// snapshot, so it adds no golden/hash churn.
    pub redactions: Vec<IrRedaction>,
    /// Per egress sink, the set of binding roots its payload references (union
    /// across branches), keyed by the sink string the IFC engine uses: a `complete
    /// <binding>` by its binding, a `record <Schema>` by `fact:<Schema>`, a `send via
    /// <channel>` by the channel. IFC-only (NOT in the `.ir` snapshot). The engine
    /// uses this to recognize a FULLY-REDACTED egress — one whose payload references
    /// only redaction outputs — and govern its leak check by the projection's
    /// per-field label rather than the rule's whole read set (DR-0027 redact, the
    /// static refinement).
    pub egress_payload_reads: BTreeMap<String, BTreeSet<String>>,
    /// The output roots of `coerce … declassified` crossings in this rule: the
    /// coerce's binding plus its `after <binding> succeeds|completes as <alias>`
    /// aliases (the names an egress payload actually references). The IFC engine
    /// waives the read×sink leak check for an egress carried ENTIRELY by these
    /// roots when a matching `grant declassify` covers the sink (DR-0027
    /// I-IFC3 — grants authorize marked crossings only). IFC-only (NOT in the
    /// `.ir` snapshot).
    pub declassified_roots: BTreeSet<String>,
    /// The `endorsed` dual of `declassified_roots`: output roots of `coerce …
    /// endorsed` crossings, and (DR-0051 §2) the claimed *item* of `claim …
    /// endorsed` crossings. Consulted by the inject check. IFC-only (NOT in the
    /// `.ir` snapshot).
    pub endorsed_roots: BTreeSet<String>,
    /// DR-0051 §3: the *item* bindings of `claim … endorsed` effects — the
    /// names a `when <tracker> has ready issue as <binding>` trigger bound, not
    /// the claim's own `as` binding.
    ///
    /// Carried separately from `endorsed_roots` because the two answer different
    /// questions. `endorsed_roots` says which values crossed; this says which
    /// queue the crossing drew its authority from, so the checker can refuse a
    /// marker whose tracker nobody vouched. IFC-only (NOT in the `.ir`
    /// snapshot).
    pub endorsed_claim_items: BTreeSet<String>,
    /// DR-0051 §4: per-field binding roots for each `record <Schema> { … }`
    /// egress — the same shape as `complete_field_reads`, keyed by
    /// `fact:<Schema>` and then by field name.
    ///
    /// `egress_payload_reads` collapses a record's roots to one set, which is
    /// enough to decide whether a *sink* is carried by a marked crossing but not
    /// which *field* it shaped. §4 needs the finer grain: a verdict field shaped
    /// by an endorsement must be schema-closed, while a sibling field holding a
    /// constant is nobody's business. IFC-only (NOT in the `.ir` snapshot).
    pub record_field_reads: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
    /// Per-coerce argument roots: for EVERY `coerce f(args…) as <binding>` in
    /// the rule (marked or not), the binding roots its argument expressions
    /// reference. The IFC engine resolves these to governed sources for
    /// input-side provenance narrowing at marked crossings — including chaining
    /// through unmarked coerces (a model call is a total mixing point: its
    /// output carries the join of all its inputs). IFC-only (NOT in the `.ir`
    /// snapshot).
    pub coerce_input_roots: BTreeMap<String, BTreeSet<String>>,
    /// `after <effect-binding> succeeds|completes as <alias>` → the effect
    /// binding, so the IFC engine can resolve payload and argument roots
    /// through the aliases bodies actually reference. IFC-only (NOT in the
    /// `.ir` snapshot).
    pub after_aliases: BTreeMap<String, String>,
    /// Per egress sink, the binding roots of every enclosing `case` scrutinee
    /// (DR-0046): a sink inside a `case` arm is INFLUENCED by the scrutinee —
    /// branching on model output and recording per-arm constants is the
    /// classic implicit channel. Covers record/complete/milestone/send/write
    /// uniformly. IFC-only (NOT in the `.ir` snapshot).
    pub egress_case_influence: BTreeMap<String, BTreeSet<String>>,
    /// Per `complete <binding>` egress, the binding roots each RESULT FIELD
    /// references — a two-level map `binding -> field -> {roots}`. Where
    /// `egress_payload_reads` joins all of a sink's fields into one set (enough for the
    /// fully-redacted recognizer), this keeps them SEPARATE so the IFC engine can
    /// compute a PER-FIELD flow signature (DR-0030 X2 v2): the reads reaching each
    /// result field, refined at fact granularity. IFC-only (NOT in the `.ir`
    /// snapshot). Union across branches; a `Shorthand` field resolves to the
    /// terminal's `from` binding.
    pub complete_field_reads: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
    /// Per `emit milestone "<name>"` egress, the binding roots each MILESTONE FIELD
    /// references — same shape and purpose as `complete_field_reads`, but keyed by
    /// milestone name. Milestone payloads are child-to-parent egresses, so IFC needs
    /// their per-field flow signature too (D3′). IFC-only (NOT in the `.ir`
    /// snapshot). Union across branches.
    pub milestone_field_reads: BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
    /// Bounded-type projection egresses (`record <T> from <src>`): each is governed
    /// by the kept fields' per-field label join, like an explicit `redact`. IFC-only
    /// (NOT in the `.ir` snapshot). DR-0027 auto-redaction, the bounded-type reading.
    pub bounded_egresses: Vec<IrBoundedEgress>,
    /// Maximum nesting depth of `after` blocks in the rule body (0 = no `after`,
    /// 1 = a top-level `after`, 2 = an `after` inside an `after`, …). Surfaced for the
    /// `lint.deep_after_nesting` maintainability check.
    pub max_after_depth: usize,
}

/// A bounded-type projection egress (`record <T> from <src>`): the recorded fact
/// keeps exactly `T`'s fields, copied from `src`, so the egress carries only the
/// kept fields' per-field labels — the "bounded-type" auto-redaction reading
/// (DR-0027). The bound is the declared target type `T`; the labels are the
/// SOURCE schema's (a target field mislabelled public is still caught against the
/// source's label). The IFC engine governs it exactly like an explicit `redact`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrBoundedEgress {
    /// The engine's sink string (`fact:<T>` for a record).
    pub sink: String,
    /// The schema of the `from` source binding, whose per-field labels bound the
    /// projection.
    pub source_schema: String,
    /// The kept field names (the target type `T`'s fields).
    pub keep: Vec<String>,
}

/// A `redact <source> keep [..] as <binding>` projection, surfaced for the
/// information-flow value-flow engine (DR-0027). `source` is the binding being
/// projected, `keep` the kept field names, `binding` the projected output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRedaction {
    pub source: String,
    pub keep: Vec<String>,
    pub binding: String,
    /// The schema of the source binding, when resolvable (a matched class, a
    /// coerce/decide/exec result, an `after … as` alias, or an earlier redaction's
    /// output). The information-flow engine derives the projection's confidentiality
    /// from the kept fields of this schema (`<schema>.<field>` labels), so a redacted
    /// egress needs only the kept fields' clearance, not the whole record's. `None`
    /// when the source type is not statically known (the engine then stays
    /// conservative for that redaction).
    pub source_schema: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRecordSource {
    pub schema: String,
    pub construct: String,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrProjectionRead {
    pub kind: QueryKind,
    pub head: String,
    pub guard: Option<String>,
}

impl IrProjectionRead {
    fn to_snapshot(&self) -> String {
        let prefix = match self.kind {
            QueryKind::Fact => format!("fact:{}", self.head),
            QueryKind::Effect => format!("effect:{}", self.head),
        };
        match &self.guard {
            Some(guard) => format!("{prefix} where {guard}"),
            None => prefix,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrEffectNode {
    pub id: String,
    pub kind: IrEffectKind,
    pub binding: Option<String>,
    pub required_capabilities: Vec<String>,
    pub construct_use: Option<IrConstructUse>,
    pub idempotency_key: String,
    pub span: SourceSpan,
    /// Creation-anchored deadline from a `timeout <duration>` clause.
    pub timeout_seconds: Option<u64>,
    /// Turn-access grants (`with access to …`) lowered onto an `agent.tell` effect as
    /// authority-narrowing metadata (Proposal A). Empty for non-grant effects.
    pub access_grants: Vec<IrAccessGrant>,
    /// Turn-scoped skills (`with skills [...]`) pinned onto an `agent.tell` effect as
    /// provenance (context-assembly Phase 7). Recorded, not enforced — the owned
    /// catalogue stays discover-all. Empty for effects without a skill pin.
    pub turn_skills: Vec<String>,
    /// `on stream <name>` (std.vcs): the tell's per-turn homing exception.
    /// `None` = the agent's declared membership decides.
    pub on_stream: Option<String>,
    /// The raw selection-slot source of an `undo`/`transport` effect
    /// (std.vcs R4). A string LITERAL validates statically against the
    /// selection grammar; a dynamic expression validates at execution.
    pub selection_source: Option<String>,
    /// The `onto <target>` of a `transport` effect: `mainline` or a
    /// declared stream, validated post-lowering.
    pub transport_onto: Option<String>,
    /// The named resource (file store / channel) a direct effect touches, if any —
    /// e.g. the store of a `read`/`write`. Surfaced so information-flow analysis can
    /// see rule-body data flows, not just turn-access grants. `None` for effects
    /// that touch no named resource. Not part of the `.ir` snapshot.
    pub resource: Option<String>,
    /// The agent a `tell` addresses (its `target`), surfaced so information-flow
    /// analysis can model the turn's egress to that agent's provider. `None` for
    /// non-`tell` effects. Not part of the `.ir` snapshot.
    pub agent: Option<String>,
    /// The `coerce` declaration this effect invokes, surfaced for the same reason
    /// `agent` is: it is how the analysis reaches the declaration's `provider`
    /// clause and so the endpoint this egress actually reaches. `None` for
    /// non-coerce effects AND for an inline `decide`, which names no declaration
    /// and therefore no backend. Not part of the `.ir` snapshot.
    pub coerce_target: Option<String>,
    /// The workflow an `invoke` addresses, surfaced so information-flow analysis can
    /// enumerate and govern invoke membrane ports. `None` for non-`invoke` effects.
    /// Not part of the `.ir` snapshot.
    pub workflow_target: Option<String>,
    /// The `endorsed` source marker (DR-0027 I-IFC3): the author declared this effect
    /// (a `coerce`) an integrity-raising crossing. Surfaced so the trusted surface is
    /// visible at the source crossing point. Not part of the `.ir` snapshot.
    pub endorsed: bool,
    /// The `declassified` source marker (DR-0027 I-IFC3): the author declared this
    /// `coerce` a confidentiality-lowering crossing (its output schema bounds the
    /// leak). Surfaced for audit. Not part of the `.ir` snapshot.
    pub declassified: bool,
    /// The innermost `case <scrutinee> { <pattern> => … }` arm this effect sits in,
    /// as `(scrutinee, pattern)` — the discriminated-families *selector*. Lets the
    /// IFC checker apply NMIF-on-the-selector: a crossing (`endorsed`/`declassified`)
    /// selected by a low-integrity discriminant is rejected (DR §5.6 / §7.4). `None`
    /// for effects outside any `case`. Not part of the `.ir` snapshot.
    pub selected_by: Option<(String, String)>,
    /// The `exec` surface form — raw command string vs manifest capability
    /// (spec/std-script.md "Static checks" item 2) — surfaced so check-time
    /// gates (hosted-raw demotion, manifest resolution) classify the effect
    /// from the AST instead of re-scanning rule-body text. `None` for
    /// non-`exec` effects. Not part of the `.ir` snapshot.
    pub exec_target: Option<IrExecTarget>,
}

/// The two `exec` source forms (spec/std-script.md): a raw command string
/// (`exec "cmd"`, dev-profile only) or an operator-manifest capability
/// (`exec <name> with <record>`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrExecTarget {
    Raw,
    Capability { name: String },
}

/// A lowered turn-access grant: the granted operations narrow the turn's effective
/// authority on `resource` (modeled in `models/maude/turn-access-grant.maude`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrAccessGrant {
    pub resource: String,
    pub operations: Vec<IrAccessGrantOp>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrAccessGrantOp {
    pub operation: String,
    pub target: Option<String>,
    pub globs: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrConstructUse {
    pub keyword: String,
    pub scope: String,
    pub construct_family: String,
    pub lowering_target: String,
    pub target_capability: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrEffectKind {
    AgentTell,
    SchemaCoerce,
    CapabilityCall,
    EventEmit,
    WorkflowInvoke,
    TimerWait,
    ExecCommand,
    TrackerFile,
    TrackerClaim,
    TrackerRenew,
    TrackerRelease,
    TrackerFinish,
    LeaseAcquire,
    LeaseRenew,
    LedgerAppend,
    CounterConsume,
    SignalEmit,
    FileRead,
    FileWrite,
    FileImport,
    FileExport,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrEffectDependency {
    pub upstream: String,
    pub predicate: DependencyPredicate,
    pub downstream: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrRuleCaseBranch {
    pub scrutinee: String,
    pub scrutinee_type: IrType,
    pub pattern: IrCasePattern,
    pub guard: Option<IrExpression>,
    pub body_hash: String,
    pub pattern_span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IrCasePattern {
    EnumVariant(String),
    LiteralString(String),
    Agent(String),
    OptionalSome { binding: String },
    OptionalNone,
    Wildcard,
}

impl IrCasePattern {
    fn to_snapshot(&self) -> String {
        match self {
            IrCasePattern::EnumVariant(value) => format!("enum:{value}"),
            IrCasePattern::LiteralString(value) => format!("literal:\"{value}\""),
            IrCasePattern::Agent(value) => format!("agent:{value}"),
            IrCasePattern::OptionalSome { binding } => format!("some:{binding}"),
            IrCasePattern::OptionalNone => "none".to_owned(),
            IrCasePattern::Wildcard => "_".to_owned(),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrTerminalOutput {
    pub binding: String,
    pub alternatives: Vec<IrTerminalAlternative>,
    pub span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrTerminalAlternative {
    pub tag: String,
    pub payload_type: IrType,
    pub source_span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IrTerminalCaseBranch {
    pub scrutinee: String,
    pub tag: Option<String>,
    pub binding: Option<String>,
    pub guard: Option<IrExpression>,
    pub body_hash: String,
    pub pattern_span: SourceSpan,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DependencyPredicate {
    Succeeds,
    Fails,
    TimedOut,
    Cancelled,
    Completes,
}

#[derive(Clone, Debug)]
struct SemanticContext {
    workflow: Option<String>,
    schemas: SchemaIndex,
    agents: BTreeSet<String>,
    agent_capabilities: BTreeMap<String, BTreeSet<String>>,
    coerce_outputs: BTreeMap<String, TypeSyntax>,
    coerce_params: BTreeMap<String, Vec<ParamDecl>>,
    workflow_inputs: BTreeMap<String, WorkflowInputSurface>,
    /// Declared coordination resources (spec/coordination.md).
    leases: BTreeSet<String>,
    ledgers: BTreeSet<String>,
    counters: BTreeSet<String>,
    /// Declared `channel` names (std.messaging); `send via <channel>` must name one.
    channels: BTreeSet<String>,
    /// Declared channel providers by channel name (std.messaging): the
    /// capability-report-conditioned checks (send requires outbound-capable,
    /// `when message from` requires inbound-capable) resolve the report
    /// through this map.
    channel_providers: BTreeMap<String, String>,
    /// Declared `credential` kinds by name (std.custody; DR-0053 §5): the
    /// kind-conditioned static checks (`sign … with` needs a signing kind,
    /// presentation forms need a presentable kind) resolve through this map.
    /// Kinds are stored kebab-case, matching the custody protocol.
    /// Consumed once `call`/`verify` land; the declaration ships first
    /// (custody-first sequencing).
    #[allow(dead_code)]
    credentials: BTreeMap<String, String>,
    /// Declared `memory pool` names (std.memory); `recall`/`learn`/`curate`
    /// must name one (MEM-1 check 1).
    memory_pools: BTreeSet<String>,
    /// DR-0043 regions by rule name, stashed by `extract_rule_regions` before the
    /// rule body was rewritten to its condition-HOLDS variant. The `on lapse` arm
    /// is spliced out of that body, so it reaches no other pass; analysis reads it
    /// back from here to type the arm (Decision 7 obligation 2).
    regions: BTreeMap<String, IrRegion>,
}

#[derive(Clone, Debug, Default)]
struct WorkflowInputSurface {
    inputs: BTreeMap<String, TypeSyntax>,
    /// The workflow's `output` contract types by name. A parent's
    /// `after <invoke-binding> succeeds as r` binds `r` to this contract so
    /// `r.<field>` type-checks against the child's declared output (the runtime
    /// already carries the child's terminal payload into that binding).
    outputs: BTreeMap<String, TypeSyntax>,
    /// The workflow's `failure` contract types by name. A parent's
    /// `after <invoke-binding> fails as f` binds `f` to this contract (when it is
    /// a shared top-level class) so `f.<field>` type-checks against the child's
    /// declared failure shape, instead of the generic DR-0032 `TerminalFailed`
    /// base. Falls back to the base when the failure class is child-local or the
    /// child declares zero/several failures.
    failures: BTreeMap<String, TypeSyntax>,
    schemas: SchemaIndex,
    /// Milestones the workflow may project (Family C): name -> payload class
    /// (empty string for a bare, payload-less milestone). Derived by scanning the
    /// workflow's rule bodies for `emit milestone "<name>" [of <Class>]`. This is
    /// the `declared(S)` set a parent's `after p reaches "<name>"` validates
    /// against (reject-undeclared) and the source of the observing binding's type.
    milestones: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Default)]
struct SchemaIndex {
    classes: BTreeMap<String, BTreeMap<String, TypeSyntax>>,
    enums: BTreeMap<String, BTreeSet<String>>,
    /// Declared external signals (spec/event-ingress.md); their payload
    /// schemas live in `classes` keyed by the dotted signal name.
    events: BTreeSet<String>,
    /// Family B: per-schema field presence conditions, `schema -> field ->
    /// (discriminant field, required literal)`. A conditioned field is readable
    /// only inside a matching `case <root>.<disc>` arm.
    presence: BTreeMap<String, BTreeMap<String, (String, String)>>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum BlockFrame {
    After {
        binding: String,
        predicate: DependencyPredicate,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum LiteralExpr<'a> {
    String(&'a str),
    Number(&'a str),
    Bool,
    Null,
    Ident(&'a str),
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum ExprType {
    Bool,
    Int,
    Float,
    String,
    Duration,
    Time,
    /// DR-0053: distinct from `String` so no operator, comparison, or
    /// interpolation accepts a secret where prose is expected — the
    /// expression-level face of the no-eliminator property. Deliberately NOT
    /// `Unknown`, which type-checks everywhere.
    Secret,
    Null,
    Object,
    Optional(Box<ExprType>),
    Array(Box<ExprType>),
    Map(Box<ExprType>),
    Finite {
        label: String,
        values: Vec<String>,
    },
    Collection,
    Unknown,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Expr {
    Literal(ExprLiteral),
    Path(Vec<String>),
    Index {
        target: Box<Expr>,
        key: Box<Expr>,
    },
    Array(Vec<Expr>),
    Object(Vec<ExprObjectField>),
    Unary {
        op: UnaryOp,
        expr: Box<Expr>,
    },
    Binary {
        op: BinaryOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Call {
        name: String,
        args: Vec<Expr>,
    },
    Query {
        kind: QueryKind,
        head: String,
        guard: Option<Box<Expr>>,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExprObjectField {
    pub key: String,
    pub value: Expr,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExprLiteral {
    String(String),
    Number(String),
    Bool(bool),
    Null,
    Ident(String),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnaryOp {
    Not,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BinaryOp {
    Or,
    And,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    In,
    NotIn,
    Add,
    Sub,
    Mul,
    Div,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueryKind {
    Fact,
    Effect,
}

/// Parses a deterministic expression used by guards, assertions, and branch guards.
pub fn parse_expression(expr: &str) -> Result<Expr, String> {
    ExprParser::new(expr).parse()
}

impl Expr {
    pub fn to_snapshot(&self) -> String {
        match self {
            Self::Literal(literal) => literal.to_snapshot(),
            Self::Path(path) => path.join("."),
            Self::Index { target, key } => {
                format!(
                    "{}[{}]",
                    target.to_snapshot_with_parentheses(),
                    key.to_snapshot()
                )
            }
            Self::Array(items) => {
                let items = items
                    .iter()
                    .map(Self::to_snapshot)
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("[{items}]")
            }
            Self::Object(fields) => {
                let fields = fields
                    .iter()
                    .map(|field| format!("{} {}", field.key, field.value.to_snapshot()))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{{{fields}}}")
            }
            Self::Unary { op, expr } => match op {
                UnaryOp::Not => format!("!{}", expr.to_snapshot_with_parentheses()),
            },
            Self::Binary { op, left, right } => format!(
                "{} {} {}",
                left.to_snapshot_with_parentheses(),
                op.to_snapshot(),
                right.to_snapshot_with_parentheses()
            ),
            Self::Call { name, args } => {
                let args = args
                    .iter()
                    .map(Self::to_snapshot)
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{name}({args})")
            }
            Self::Query { kind, head, guard } => {
                let prefix = match kind {
                    QueryKind::Fact => head.clone(),
                    QueryKind::Effect => format!("effect {head}"),
                };
                match guard {
                    Some(guard) => format!("{prefix} where {}", guard.to_snapshot()),
                    None => prefix,
                }
            }
        }
    }

    fn to_snapshot_with_parentheses(&self) -> String {
        match self {
            Self::Binary { .. } => format!("({})", self.to_snapshot()),
            _ => self.to_snapshot(),
        }
    }
}

impl ExprLiteral {
    fn to_snapshot(&self) -> String {
        match self {
            Self::String(value) => format!("{value:?}"),
            Self::Number(value) | Self::Ident(value) => value.clone(),
            Self::Bool(value) => value.to_string(),
            Self::Null => "null".to_owned(),
        }
    }
}

impl BinaryOp {
    fn to_snapshot(self) -> &'static str {
        match self {
            Self::Or => "||",
            Self::And => "&&",
            Self::Eq => "==",
            Self::Ne => "!=",
            Self::Lt => "<",
            Self::Le => "<=",
            Self::Gt => ">",
            Self::Ge => ">=",
            Self::In => "in",
            Self::NotIn => "not in",
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
        }
    }
}

/// Parses and lowers a source file into deterministic typed IR.
pub fn compile_program(source: &str) -> CompileOutput {
    compile_program_with_root(source, None)
}

/// Parses and lowers a source bundle into deterministic typed IR with an
/// optional explicit root workflow selection.
pub fn compile_program_with_root(source: &str, root: Option<&str>) -> CompileOutput {
    let parsed = parse_program(source);
    if !parsed.diagnostics.is_empty() {
        return CompileOutput {
            ir: None,
            diagnostics: parsed.diagnostics,
            warnings: Vec::new(),
        };
    }

    // Program-level static check over ALL workflows (before root selection):
    // transitive runtime invocation cycles have no compile-time convergence proof
    // and are rejected (RESOLVED 2026-07-01). Direct self-invocation is caught
    // per-rule during lowering.
    let mut invoke_recursion_diagnostics = Vec::new();
    detect_workflow_invoke_recursion(&parsed.program, &mut invoke_recursion_diagnostics);
    detect_private_workflow_invocations(&parsed.program, &mut invoke_recursion_diagnostics);
    if !invoke_recursion_diagnostics.is_empty() {
        return CompileOutput {
            ir: None,
            diagnostics: invoke_recursion_diagnostics,
            warnings: Vec::new(),
        };
    }

    let workflow_inputs = collect_workflow_input_surfaces(&parsed.program);
    let shared_coordination_usage = collect_shared_coordination_usage(&parsed.program);

    // Whole-program validation (RESOLVED 2026-07-01): when a program declares
    // more than one explicit `workflow`, validate EVERY workflow — not only the
    // selected root — so a broken sibling is caught in a single compile
    // regardless of which `--root` is chosen. Each workflow is lowered against
    // its own scope (top-level globals + that workflow's local block items),
    // which is exactly the scoped program `select_root_workflow` builds for that
    // name. Root selection below still produces the single entry IR for
    // `dev`/`deploy`; this pass only adds validation coverage and never changes
    // the emitted IR (when it finds no errors it returns nothing, so the root is
    // lowered once more, cleanly, below). See models/maude/workflow-scoping.maude.
    if parsed.program.workflows.len() > 1 {
        // Names declared at the top level are global (shared across every
        // workflow); names declared inside a `workflow { ... }` block are private
        // to it. Map each workflow-local name to its owning workflow(s) so that
        // when a workflow references a name that is really a sibling's local, the
        // resulting unknown-name error can point the author at where it lives —
        // the "names do not leak into sibling workflows" guarantee, surfaced.
        let global_names: BTreeSet<String> = parsed
            .program
            .items
            .iter()
            .filter_map(|item| referenced_decl_name(item).map(|(name, _)| name))
            .collect();
        let mut sibling_locals: BTreeMap<String, Vec<(String, SourceSpan)>> = BTreeMap::new();
        for workflow in &parsed.program.workflows {
            for item in &workflow.items {
                if let Some((name, span)) = referenced_decl_name(item) {
                    sibling_locals
                        .entry(name)
                        .or_default()
                        .push((workflow.name.name.clone(), span));
                }
            }
        }

        let mut aggregated = Vec::new();
        for workflow in &parsed.program.workflows {
            let name = workflow.name.name.clone();
            let own_locals: BTreeSet<String> = workflow
                .items
                .iter()
                .filter_map(|item| referenced_decl_name(item).map(|(name, _)| name))
                .collect();
            let mut diagnostics = match select_root_workflow(parsed.program.clone(), Some(&name)) {
                Ok(scoped) => {
                    lower_program(
                        scoped,
                        workflow_inputs.clone(),
                        shared_coordination_usage.clone(),
                    )
                    .diagnostics
                }
                Err(diagnostics) => diagnostics,
            };
            for diagnostic in &mut diagnostics {
                annotate_cross_workflow_leak(
                    diagnostic,
                    &name,
                    &own_locals,
                    &global_names,
                    &sibling_locals,
                );
            }
            aggregated.extend(diagnostics);
        }
        if !aggregated.is_empty() {
            return CompileOutput {
                ir: None,
                diagnostics: aggregated,
                warnings: Vec::new(),
            };
        }
    }

    match select_root_workflow(parsed.program, root) {
        Ok(program) => lower_program(program, workflow_inputs, shared_coordination_usage),
        Err(diagnostics) => CompileOutput {
            ir: None,
            diagnostics,
            warnings: Vec::new(),
        },
    }
}

/// One top-level declaration for an editor outline (`whip lsp`'s
/// `textDocument/documentSymbol`): its name, a coarse kind tag, and source span.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeclSymbol {
    pub name: String,
    pub kind: &'static str,
    pub span: SourceSpan,
}

/// Top-level declarations of `source` in source order, for an editor outline. On a
/// parse error it returns whatever declarations parsed (best-effort outline).
pub fn document_symbols(source: &str) -> Vec<DeclSymbol> {
    let program = parse_program(source).program;
    let mut symbols = Vec::new();
    if let Some(workflow) = &program.workflow {
        symbols.push(DeclSymbol {
            name: workflow.name.clone(),
            kind: "workflow",
            span: workflow.span,
        });
    }
    for workflow in &program.workflows {
        symbols.push(DeclSymbol {
            name: workflow.name.name.clone(),
            kind: "workflow",
            span: workflow.span,
        });
    }
    for pattern in &program.patterns {
        symbols.push(DeclSymbol {
            name: pattern.name.name.clone(),
            kind: "pattern",
            span: pattern.span,
        });
    }
    for item in &program.items {
        let symbol = match item {
            Item::Class(decl) => ("class", decl.name.name.clone(), decl.span),
            Item::Enum(decl) => ("enum", decl.name.name.clone(), decl.span),
            Item::Agent(decl) => ("agent", decl.name.name.clone(), decl.span),
            Item::Rule(decl) => ("rule", decl.name.name.clone(), decl.span),
            Item::Coerce(decl) => ("coerce", decl.name.name.clone(), decl.span),
            Item::Action(decl) => ("action", decl.name.name.clone(), decl.span),
            Item::Lease(decl) => ("lease", decl.name.name.clone(), decl.span),
            Item::Ledger(decl) => ("ledger", decl.name.name.clone(), decl.span),
            Item::Counter(decl) => ("counter", decl.name.name.clone(), decl.span),
            Item::Tracker(decl) => ("tracker", decl.name.name.clone(), decl.span),
            Item::Channel(decl) => ("channel", decl.name.name.clone(), decl.span),
            Item::Credential(decl) => ("credential", decl.name.name.clone(), decl.span),
            Item::FileStore(decl) => ("file store", decl.name.name.clone(), decl.span),
            Item::MemoryPool(decl) => ("memory pool", decl.name.name.clone(), decl.span),
            Item::Event(decl) => ("signal", decl.name.clone(), decl.span),
            Item::Table(decl) => ("table", decl.name.name.clone(), decl.span),
            Item::Gauge(decl) => ("gauge", decl.name.name.clone(), decl.span),
            Item::Campaign(decl) => ("campaign", decl.name.name.clone(), decl.span),
            Item::Mark(decl) => ("mark", decl.name.value.clone(), decl.span),
            _ => continue,
        };
        symbols.push(DeclSymbol {
            name: symbol.1,
            kind: symbol.0,
            span: symbol.2,
        });
    }
    symbols
}

/// Zero-based source line of a byte offset.
fn line_index(source: &str, offset: usize) -> usize {
    source.as_bytes()[..offset]
        .iter()
        .filter(|&&byte| byte == b'\n')
        .count()
}

/// Classify the comments inside `body` (a field-list declaration's brace region)
/// against its `members` (each member's span + already-formatted lines, in source
/// order). Returns the own-line comments to interleave between members, plus a
/// per-member optional trailing comment (appended to that member's last line).
/// Returns `None` when a comment cannot be placed safely — a comment inside a
/// *multi-line* member's own body (a deeper level this pass does not place), or a
/// trailing comment with no single-line member on its line — so the caller refuses
/// the file rather than misplace it. `comments` must be sorted by `span.start`.
fn classify_body_comments<'a>(
    source: &str,
    body: SourceSpan,
    members: &[(SourceSpan, Vec<String>)],
    comments: &'a [Comment],
) -> Option<(Vec<&'a Comment>, Vec<Option<&'a Comment>>)> {
    let mut own_line: Vec<&Comment> = Vec::new();
    let mut trailing: Vec<Option<&Comment>> = vec![None; members.len()];
    for comment in comments {
        if comment.span.start <= body.start || comment.span.start >= body.end {
            continue;
        }
        // A comment inside a multi-line member's own braces is a deeper level we do
        // not place here (e.g. a data-carrying `enum` variant's nested field).
        if members.iter().any(|(span, lines)| {
            lines.len() > 1 && span.start < comment.span.start && comment.span.start < span.end
        }) {
            return None;
        }
        let line_start = source[..comment.span.start]
            .rfind('\n')
            .map(|index| index + 1)
            .unwrap_or(0);
        if source[line_start..comment.span.start].trim().is_empty() {
            own_line.push(comment);
            continue;
        }
        // Trailing: attach to a single-line member sharing the comment's line.
        let comment_line = line_index(source, comment.span.start);
        let mut placed = false;
        for (index, (span, lines)) in members.iter().enumerate() {
            if lines.len() == 1 && line_index(source, span.start) == comment_line {
                if trailing[index].is_some() {
                    return None;
                }
                trailing[index] = Some(comment);
                placed = true;
                break;
            }
        }
        if !placed {
            return None;
        }
    }
    Some((own_line, trailing))
}

/// Emit each member's lines, interleaving `own_line` comments by source position
/// (at `indent`) and appending each member's `trailing` comment to its last line.
/// `members` and `own_line` must be in ascending `span.start` order; `trailing`
/// is parallel to `members`.
fn emit_members_with_comments(
    members: &[(SourceSpan, Vec<String>)],
    own_line: &[&Comment],
    trailing: &[Option<&Comment>],
    indent: &str,
    formatted: &mut String,
) {
    let mut next = 0;
    for (index, (span, lines)) in members.iter().enumerate() {
        while next < own_line.len() && own_line[next].span.start < span.start {
            push_line(
                formatted,
                format!("{indent}{}", format_comment(own_line[next])),
            );
            next += 1;
        }
        let last = lines.len().saturating_sub(1);
        for (offset, line) in lines.iter().enumerate() {
            match trailing[index] {
                Some(comment) if offset == last => {
                    push_line(formatted, format!("{line}  {}", format_comment(comment)));
                }
                _ => push_line(formatted, line.clone()),
            }
        }
    }
    while next < own_line.len() {
        push_line(
            formatted,
            format!("{indent}{}", format_comment(own_line[next])),
        );
        next += 1;
    }
}

/// Format a `class` body with its own-line and trailing comments preserved.
/// Returns `false` (caller refuses the file) when a body comment cannot be placed
/// safely.
fn try_format_class_with_comments(
    class_decl: &ClassDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let members: Vec<(SourceSpan, Vec<String>)> = class_decl
        .fields
        .iter()
        .map(|field| {
            let key = if field.is_key { " @key" } else { "" };
            (
                field.span,
                vec![format!(
                    "  {} {}{key}",
                    field.name.name,
                    field.ty.to_source()
                )],
            )
        })
        .collect();
    let Some((own_line, trailing)) =
        classify_body_comments(source, class_decl.span, &members, comments)
    else {
        return false;
    };
    push_line(formatted, format!("class {} {{", class_decl.name.name));
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

/// Format a `queue` body (its single `tracker` member) with own-line and trailing
/// comments preserved. Returns `false` (caller refuses the file) when a body
/// comment cannot be placed safely.
fn try_format_tracker_with_comments(
    queue: &TrackerDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let members: Vec<(SourceSpan, Vec<String>)> = vec![(
        queue.provider.span,
        vec![format!("  provider {}", queue.provider.name)],
    )];
    let Some((own_line, trailing)) = classify_body_comments(source, queue.span, &members, comments)
    else {
        return false;
    };
    push_line(formatted, format!("tracker {} {{", queue.name.name));
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

/// Format a `file store` body (its `root` and optional `allow read`/`allow write`
/// clauses) with own-line and trailing comments preserved, interleaved by the
/// clause spans captured during parsing. Returns `false` (caller refuses the file)
/// when a body comment cannot be placed safely.
fn try_format_filestore_with_comments(
    file_store: &FileStoreDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let render = |globs: &[String]| {
        globs
            .iter()
            .map(|glob| format!("{glob:?}"))
            .collect::<Vec<_>>()
            .join(", ")
    };
    let mut members: Vec<(SourceSpan, Vec<String>)> = Vec::new();
    if let Some(span) = file_store.root_span {
        members.push((span, vec![format!("  root {:?}", file_store.root)]));
    }
    if !file_store.read_globs.is_empty() {
        if let Some(span) = file_store.read_span {
            members.push((
                span,
                vec![format!("  allow read [{}]", render(&file_store.read_globs))],
            ));
        }
    }
    if !file_store.write_globs.is_empty() {
        if let Some(span) = file_store.write_span {
            members.push((
                span,
                vec![format!(
                    "  allow write [{}]",
                    render(&file_store.write_globs)
                )],
            ));
        }
    }
    if let Some(provider) = &file_store.provider {
        if let Some(span) = file_store.provider_span {
            members.push((span, vec![format!("  provider {}", provider.name)]));
        }
    }
    members.sort_by_key(|(span, _)| span.start);
    let Some((own_line, trailing)) =
        classify_body_comments(source, file_store.span, &members, comments)
    else {
        return false;
    };
    push_line(formatted, format!("file store {} {{", file_store.name.name));
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

/// Format a `signal` body (a typed payload schema of `ClassField`s, like a class)
/// with its own-line and trailing comments preserved. Returns `false` (caller
/// refuses the file) when a body comment cannot be placed safely.
fn try_format_event_with_comments(
    event: &EventDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let members: Vec<(SourceSpan, Vec<String>)> = event
        .fields
        .iter()
        .map(|field| {
            (
                field.span,
                vec![format!("  {} {}", field.name.name, field.ty.to_source())],
            )
        })
        .collect();
    let Some((own_line, trailing)) = classify_body_comments(source, event.span, &members, comments)
    else {
        return false;
    };
    push_line(formatted, format!("signal {} {{", event.name));
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

fn agent_field_span(field: &AgentField) -> SourceSpan {
    match field {
        AgentField::Provider(ident) => ident.span,
        AgentField::Profile(profile) => profile.span,
        AgentField::Capacity(_, span)
        | AgentField::Skills(_, span)
        | AgentField::Capabilities(_, span)
        | AgentField::Requires(_, span)
        | AgentField::Tools(_, span) => *span,
        AgentField::Compaction(strategy) => strategy.span,
        AgentField::Thread(mode) => mode.span,
        AgentField::Settings(sources) => sources.span,
        AgentField::Unknown { span, .. } => *span,
    }
}

fn agent_field_line(field: &AgentField) -> String {
    match field {
        AgentField::Provider(provider) => format!("  provider {}", provider.name),
        AgentField::Profile(profile) => format!("  profile {:?}", profile.value),
        AgentField::Capacity(capacity, _) => format!("  capacity {capacity}"),
        AgentField::Skills(skills, _) => {
            let skills = skills
                .iter()
                .map(|skill| format!("{:?}", skill.value))
                .collect::<Vec<_>>()
                .join(", ");
            format!("  skills [{skills}]")
        }
        AgentField::Capabilities(capabilities, _) => {
            let capabilities = capabilities
                .iter()
                .map(|capability| format!("{:?}", capability.value))
                .collect::<Vec<_>>()
                .join(", ");
            format!("  capabilities [{capabilities}]")
        }
        AgentField::Requires(classes, _) => {
            let classes = classes
                .iter()
                .map(|class| class.name.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            format!("  requires [{classes}]")
        }
        AgentField::Tools(tools, _) => {
            let tools = tools
                .iter()
                .map(|tool| tool.name.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            format!("  tools [{tools}]")
        }
        AgentField::Compaction(strategy) => format!("  compaction {}", strategy.name),
        AgentField::Thread(mode) => format!("  thread {}", mode.name),
        AgentField::Settings(sources) => format!("  settings {}", sources.name),
        AgentField::Unknown { name, .. } => format!("  {}", name.name),
    }
}

/// Format an `agent` body with its own-line and trailing comments preserved.
/// Returns `false` (caller refuses the file) when a body comment cannot be placed
/// safely.
fn try_format_agent_with_comments(
    agent: &AgentDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let members: Vec<(SourceSpan, Vec<String>)> = agent
        .fields
        .iter()
        .map(|field| (agent_field_span(field), vec![agent_field_line(field)]))
        .collect();
    let Some((own_line, trailing)) = classify_body_comments(source, agent.span, &members, comments)
    else {
        return false;
    };
    let harness = agent
        .harness
        .as_ref()
        .map(|harness| format!(" using {}", harness.name))
        .or_else(|| {
            agent
                .delegated_to
                .as_ref()
                .map(|delegate| format!(" delegated to {}", delegate.name))
        })
        .unwrap_or_default();
    push_line(
        formatted,
        format!("agent {}{} {{", agent.name.name, harness),
    );
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

/// Lines for one enum variant, with comments inside a data-carrying variant's
/// nested field block preserved (own-line interleaved, trailing appended) — the
/// block is a field list in braces, so it reuses the same classify/emit one level
/// deeper. Returns `None` when a nested comment cannot be placed safely.
fn enum_variant_lines_with_comments(
    variant: &EnumVariantDecl,
    source: &str,
    comments: &[Comment],
) -> Option<Vec<String>> {
    if variant.fields.is_empty() {
        return Some(vec![format!("  {}", variant.name.name)]);
    }
    let members: Vec<(SourceSpan, Vec<String>)> = variant
        .fields
        .iter()
        .map(|field| {
            (
                field.span,
                vec![format!("    {} {}", field.name.name, field.ty.to_source())],
            )
        })
        .collect();
    // `comments` is filtered to this variant's span by classify (via variant.span).
    let (own_line, trailing) = classify_body_comments(source, variant.span, &members, comments)?;
    let mut block = String::new();
    emit_members_with_comments(&members, &own_line, &trailing, "    ", &mut block);
    let mut lines = vec![format!("  {} {{", variant.name.name)];
    lines.extend(block.lines().map(str::to_owned));
    lines.push("  }".to_owned());
    Some(lines)
}

/// Format an `enum` body with its comments preserved at both levels: between
/// variants (own-line interleaved, trailing appended to a bare variant's line) and
/// inside a data-carrying variant's nested field block. Each brace-body filters
/// comments by its own span, so the two levels never double-count. Returns `false`
/// (caller refuses the file) when a comment cannot be placed safely.
fn try_format_enum_with_comments(
    enum_decl: &EnumDecl,
    source: &str,
    comments: &[Comment],
    formatted: &mut String,
) -> bool {
    let mut members: Vec<(SourceSpan, Vec<String>)> = Vec::with_capacity(enum_decl.variants.len());
    for variant in &enum_decl.variants {
        let Some(lines) = enum_variant_lines_with_comments(variant, source, comments) else {
            return false;
        };
        members.push((variant.span, lines));
    }
    // Enum-body-level comments are those NOT inside a data variant's nested block
    // (those are placed by `enum_variant_lines_with_comments`); pass only those to
    // the body-level classify so the nested ones are not counted twice.
    let body_level: Vec<Comment> = comments
        .iter()
        .filter(|comment| {
            !enum_decl.variants.iter().any(|variant| {
                !variant.fields.is_empty()
                    && variant.span.start < comment.span.start
                    && comment.span.start < variant.span.end
            })
        })
        .cloned()
        .collect();
    let Some((own_line, trailing)) =
        classify_body_comments(source, enum_decl.span, &members, &body_level)
    else {
        return false;
    };
    push_line(formatted, format!("enum {} {{", enum_decl.name.name));
    emit_members_with_comments(&members, &own_line, &trailing, "  ", formatted);
    push_line(formatted, "}");
    true
}

/// The name a top-level named declaration introduces, paired with its span, when
/// it is a kind that another workflow can reference by name (schemas, agents,
/// coordination resources, signals). Rules/tests/asserts/apply/contracts/patterns
/// introduce no such cross-referenced name here. Mirrors `document_symbols`'
/// named-decl set. Used to attach a "declared in workflow B" note when a
/// workflow references a name that is really private to a sibling.
fn referenced_decl_name(item: &Item) -> Option<(String, SourceSpan)> {
    match item {
        Item::Class(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Enum(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Agent(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Coerce(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Lease(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Ledger(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Counter(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Tracker(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Channel(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::FileStore(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::MemoryPool(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Event(decl) => Some((decl.name.clone(), decl.span)),
        Item::Table(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Gauge(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Campaign(decl) => Some((decl.name.name.clone(), decl.span)),
        Item::Mark(decl) => Some((decl.name.value.clone(), decl.span)),
        _ => None,
    }
}

/// If `diagnostic` (produced while validating workflow `current`) reports an
/// unknown name that is actually declared *private to a sibling workflow*, attach
/// a related note pointing at that sibling's declaration. This turns a bare
/// "unknown class `X`" into an actionable "…and `X` lives in workflow `B`; move
/// it to the top level to share it." A name that is global or one of `current`'s
/// own locals is legitimately in scope and never annotated.
fn annotate_cross_workflow_leak(
    diagnostic: &mut Diagnostic,
    current: &str,
    own_locals: &BTreeSet<String>,
    global_names: &BTreeSet<String>,
    sibling_locals: &BTreeMap<String, Vec<(String, SourceSpan)>>,
) {
    for (name, owners) in sibling_locals {
        if global_names.contains(name) || own_locals.contains(name) {
            continue;
        }
        // Only names actually referenced (as `` `name` ``) in this diagnostic, and
        // owned by some workflow other than the one being validated.
        if !diagnostic.message.contains(&format!("`{name}`")) {
            continue;
        }
        let Some((owner, span)) = owners.iter().find(|(owner, _)| owner != current) else {
            continue;
        };
        diagnostic.related.push(RelatedInfo {
            span: *span,
            message: format!(
                "`{name}` is declared inside workflow `{owner}`, which makes it \
                 private to that workflow; move it to a top-level declaration to \
                 share it across workflows"
            ),
        });
        return;
    }
}

fn select_root_workflow(
    mut program: Program,
    root: Option<&str>,
) -> Result<Program, Vec<Diagnostic>> {
    // A runnable program requires at least one explicit `workflow`. The implicit
    // compatibility root is removed (RESOLVED 2026-07-01): a source that declares
    // no `workflow` at all (neither the header form nor a `workflow Name { ... }`
    // block) is a library fragment, not a program, and is rejected here rather
    // than silently compiled as an anonymous root.
    if program.workflow.is_none() && program.workflows.is_empty() {
        return Err(vec![Diagnostic {
            related: Vec::new(),
            span: SourceSpan { start: 0, end: 0 },
            message: "program declares no `workflow`".to_owned(),
            suggestion: Some(
                "add an explicit `workflow Name { ... }` declaration; a runnable \
                 program requires at least one workflow (files that only declare \
                 shared types or patterns are libraries, meant to be `include`d)"
                    .to_owned(),
            ),
        }]);
    }

    if program.workflows.is_empty() {
        if let Some(root) = root {
            match program.workflow.as_ref() {
                Some(workflow) if workflow.name == root => {}
                Some(workflow) => {
                    return Err(vec![Diagnostic {
                        related: Vec::new(),
                        span: workflow.span,
                        message: format!("root workflow `{root}` was not found"),
                        suggestion: Some(format!("available workflow: `{}`", workflow.name)),
                    }]);
                }
                None => {
                    return Err(vec![Diagnostic {
                        related: Vec::new(),
                        span: SourceSpan { start: 0, end: 0 },
                        message: format!("root workflow `{root}` was not found"),
                        suggestion: Some(
                            "add an explicit `workflow Name { ... }` declaration".to_owned(),
                        ),
                    }]);
                }
            }
        }
        return Ok(program);
    }

    let selected_index = match root {
        Some(root) => match program
            .workflows
            .iter()
            .position(|workflow| workflow.name.name == root)
        {
            Some(index) => index,
            None => {
                let names = program
                    .workflows
                    .iter()
                    .map(|workflow| format!("`{}`", workflow.name.name))
                    .collect::<Vec<_>>()
                    .join(", ");
                return Err(vec![Diagnostic {
                    related: Vec::new(),
                    span: SourceSpan { start: 0, end: 0 },
                    message: format!("root workflow `{root}` was not found"),
                    suggestion: Some(format!("available workflows: {names}")),
                }]);
            }
        },
        None if program.workflows.len() == 1 => 0,
        None => {
            let names = program
                .workflows
                .iter()
                .map(|workflow| format!("`{}`", workflow.name.name))
                .collect::<Vec<_>>()
                .join(", ");
            return Err(vec![Diagnostic {
                related: Vec::new(),
                span: SourceSpan { start: 0, end: 0 },
                message: "multiple workflow declarations require an explicit root".to_owned(),
                suggestion: Some(format!(
                    "pass `--root <name>`; available workflows: {names}"
                )),
            }]);
        }
    };

    let selected = program.workflows.remove(selected_index);
    let mut items = program.items;
    let workflow_tags = selected.tags;
    let workflow_description = selected.description;
    items.extend(selected.items);
    Ok(Program {
        workflow: Some(selected.name),
        workflow_tags,
        workflow_description,
        explicit_workflow_body: true,
        workflows: Vec::new(),
        patterns: program.patterns,
        items,
    })
}

impl IrProgram {
    pub fn construct_uses(&self) -> Vec<&IrConstructUse> {
        self.rules
            .iter()
            .flat_map(|rule| rule.metadata.effects.iter())
            .filter_map(|effect| effect.construct_use.as_ref())
            .collect()
    }

    pub fn contract_registry(&self) -> ContractRegistry {
        let mut libraries = BTreeMap::<String, LibraryRegistration>::new();
        let mut contracts = BTreeMap::<(String, String), EffectContract>::new();

        for use_decl in &self.uses {
            libraries
                .entry(use_decl.name.clone())
                .or_insert_with(|| LibraryRegistration {
                    id: use_decl.name.clone(),
                    version: "unlocked".to_owned(),
                    standard: false,
                });
        }

        if !self.harnesses.is_empty() || !self.agents.is_empty() {
            register_standard_library(&mut libraries, "std.agent");
        }
        if !self.trackers.is_empty() {
            register_standard_library(&mut libraries, "std.tracker");
        }
        if !self.events.is_empty() {
            register_standard_library(&mut libraries, "std.ingress");
        }
        if !self.leases.is_empty() || !self.ledgers.is_empty() || !self.counters.is_empty() {
            register_standard_library(&mut libraries, "std.coord");
        }
        if !self.channels.is_empty() {
            register_standard_library(&mut libraries, "std.messaging");
        }
        if !self.credentials.is_empty() {
            register_standard_library(&mut libraries, "std.custody");
        }
        // A bare `file store` declaration registers the owning library even
        // before any rule uses a file effect (spec/std-files.md "Manifest":
        // the declaration alone previously registered nothing).
        if !self.file_stores.is_empty() {
            register_standard_library(&mut libraries, "std.files");
        }
        if self.sources.iter().any(|source| source.is_clock) {
            register_standard_library(&mut libraries, "std.time");
        }
        if !self.coerces.is_empty() {
            register_standard_library(&mut libraries, "std.coercion");
            register_effect_contract(
                &mut libraries,
                &mut contracts,
                IrEffectKind::SchemaCoerce,
                Vec::new(),
            );
        }

        for rule in &self.rules {
            for effect in &rule.metadata.effects {
                register_effect_contract(
                    &mut libraries,
                    &mut contracts,
                    effect.kind.clone(),
                    effect.required_capabilities.clone(),
                );
            }
        }

        // Package-owned construct registrations (e.g. `send`, `recall`) are NOT
        // registered here: they come from a package manifest — embedded std
        // manifests included — merged in by the CLI when the owning package is
        // imported (`use std.messaging`). Modeled in
        // `models/maude/std-construct-authorization.maude`.
        ContractRegistry {
            libraries: libraries.into_values().collect(),
            constructs: Vec::new(),
            effect_contracts: contracts.into_values().collect(),
        }
    }

    pub fn to_snapshot(&self) -> String {
        let mut snapshot = String::new();
        push_line(&mut snapshot, format!("workflow {}", self.workflow));

        if !self.source_tags.is_empty() {
            push_line(&mut snapshot, "source_tags");
            for tag in &self.source_tags {
                push_line(
                    &mut snapshot,
                    format!("@{} {} {}", tag.name, tag.target_kind, tag.target),
                );
            }
        }

        if !self.source_descriptions.is_empty() {
            push_line(&mut snapshot, "source_descriptions");
            for description in &self.source_descriptions {
                push_line(
                    &mut snapshot,
                    format!(
                        "{:?} {} {}",
                        description.value, description.target_kind, description.target
                    ),
                );
            }
        }

        if !self.shared_coordination_usage.is_empty() {
            push_line(&mut snapshot, "shared_coordination_usage");
            for usage in &self.shared_coordination_usage {
                push_line(
                    &mut snapshot,
                    format!(
                        "{} <- {}",
                        usage.resource,
                        usage.workflow_principals.join(",")
                    ),
                );
            }
        }

        if !self.includes.is_empty() {
            push_line(&mut snapshot, "includes");
            for include in &self.includes {
                match &include.source_hash {
                    Some(source_hash) => {
                        push_line(
                            &mut snapshot,
                            format!("  {} hash {}", include.path, source_hash),
                        );
                    }
                    None => push_line(&mut snapshot, format!("  {}", include.path)),
                }
            }
        }

        if !self.pattern_applications.is_empty() {
            push_line(&mut snapshot, "pattern_applications");
            for application in &self.pattern_applications {
                let type_args = application
                    .type_args
                    .iter()
                    .map(IrType::to_snapshot)
                    .collect::<Vec<_>>()
                    .join(", ");
                push_line(
                    &mut snapshot,
                    format!(
                        "  {} as {}<{}>",
                        application.pattern, application.alias, type_args
                    ),
                );
                push_line(
                    &mut snapshot,
                    format!(
                        "    defined-at {}..{}",
                        application.definition_span.start, application.definition_span.end
                    ),
                );
                push_line(
                    &mut snapshot,
                    format!(
                        "    applied-at {}..{}",
                        application.application_span.start, application.application_span.end
                    ),
                );
                for argument in &application.value_args {
                    push_line(
                        &mut snapshot,
                        format!("    arg {} {}", argument.name, argument.value),
                    );
                }
                for generated in &application.generated {
                    push_line(&mut snapshot, format!("    generated {generated}"));
                }
            }
        }

        if !self.workflow_contracts.is_empty() {
            push_line(&mut snapshot, "workflow_contracts");
            for contract in &self.workflow_contracts {
                push_line(
                    &mut snapshot,
                    format!(
                        "  {} {} {}",
                        contract.kind.as_str(),
                        contract.name,
                        contract.ty.to_snapshot()
                    ),
                );
            }
        }

        if !self.uses.is_empty() {
            push_line(&mut snapshot, "uses");
            for use_decl in &self.uses {
                push_line(
                    &mut snapshot,
                    format!("  {} {}", use_decl.kind.as_str(), use_decl.name),
                );
            }
        }

        if !self.schemas.is_empty() {
            push_line(&mut snapshot, "schemas");
            for schema in &self.schemas {
                match schema {
                    IrSchema::Enum(enum_decl) => {
                        push_line(
                            &mut snapshot,
                            format!(
                                "  enum {} {{ {} }}",
                                enum_decl.name,
                                enum_decl.variants.join(", ")
                            ),
                        );
                    }
                    IrSchema::Class(class_decl) => {
                        push_line(&mut snapshot, format!("  class {}", class_decl.name));
                        for field in &class_decl.fields {
                            // `@key` is serialized only when set, so non-keyed
                            // classes keep their prior snapshot (no ripple).
                            let key = if field.is_key { " @key" } else { "" };
                            push_line(
                                &mut snapshot,
                                format!("    {} {}{key}", field.name, field.ty.to_snapshot()),
                            );
                        }
                    }
                }
            }
        }

        if !self.harnesses.is_empty() {
            push_line(&mut snapshot, "harnesses");
            for harness in &self.harnesses {
                push_line(
                    &mut snapshot,
                    format!("  harness {} kind={}", harness.name, harness.kind),
                );
            }
        }
        if !self.trackers.is_empty() {
            push_line(&mut snapshot, "trackers");
            for queue in &self.trackers {
                push_line(
                    &mut snapshot,
                    format!("  tracker {} provider={}", queue.name, queue.provider),
                );
            }
        }
        if !self.streams.is_empty() {
            push_line(&mut snapshot, "streams");
            for stream in &self.streams {
                push_line(
                    &mut snapshot,
                    format!(
                        "  stream {} members=[{}]{}",
                        stream.name,
                        stream.members.join(","),
                        stream
                            .staleness_seconds
                            .map(|seconds| format!(" staleness={seconds}s"))
                            .unwrap_or_default()
                    ),
                );
            }
        }

        if !self.channels.is_empty() {
            push_line(&mut snapshot, "channels");
            for channel in &self.channels {
                let mut line = format!("  channel {} provider={}", channel.name, channel.provider);
                if let Some(workspace) = &channel.workspace {
                    line.push_str(&format!(" workspace={workspace}"));
                }
                if let Some(destination) = &channel.destination {
                    line.push_str(&format!(" destination={destination:?}"));
                }
                push_line(&mut snapshot, line);
            }
        }

        if !self.credentials.is_empty() {
            push_line(&mut snapshot, "credentials");
            for credential in &self.credentials {
                push_line(
                    &mut snapshot,
                    format!("  credential {} kind={}", credential.name, credential.kind),
                );
            }
        }

        if !self.gauges.is_empty() {
            push_line(&mut snapshot, "gauges");
            for gauge in &self.gauges {
                let mut line = format!(
                    "  gauge {} judge={}:{}",
                    gauge.name, gauge.judge_kind, gauge.judge_target
                );
                if !gauge.judge_args.is_empty() {
                    line.push_str(&format!(" args=({})", gauge.judge_args.join(",")));
                }
                if let Some(site) = &gauge.site {
                    line.push_str(&format!(" site={site}"));
                }
                if let Some(bar) = &gauge.expect {
                    line.push_str(&format!(
                        " expect={}:{}{}{}",
                        bar.form, bar.subject, bar.op, bar.threshold
                    ));
                }
                if !gauge.inputs.is_empty() {
                    line.push_str(&format!(" inputs={}", gauge.inputs.join(",")));
                }
                push_line(&mut snapshot, line);
            }
        }

        if !self.marks.is_empty() {
            push_line(&mut snapshot, "marks");
            for mark in &self.marks {
                push_line(
                    &mut snapshot,
                    format!("  mark {:?} after {}", mark.name, mark.site),
                );
            }
        }

        if !self.campaigns.is_empty() {
            push_line(&mut snapshot, "campaigns");
            for campaign in &self.campaigns {
                let mut line = format!("  campaign {}", campaign.name);
                if !campaign.ascend.is_empty() {
                    line.push_str(&format!(" ascend={}", campaign.ascend.join(",")));
                }
                for reach in &campaign.reach {
                    line.push_str(&format!(
                        " reach={}{}{}{}",
                        reach.gauge,
                        reach.op,
                        reach.threshold,
                        reach.unit.as_deref().unwrap_or("")
                    ));
                }
                for guard in &campaign.guard {
                    line.push_str(&format!(
                        " guard={}:within:{}%",
                        guard.gauge, guard.band_percent
                    ));
                }
                if !campaign.sacrifice.is_empty() {
                    line.push_str(&format!(" sacrifice={}", campaign.sacrifice.join(",")));
                }
                if campaign.proposer_redacted {
                    line.push_str(" proposer=redacted");
                }
                push_line(&mut snapshot, line);
            }
        }

        if !self.file_stores.is_empty() {
            push_line(&mut snapshot, "file_stores");
            for file_store in &self.file_stores {
                push_line(
                    &mut snapshot,
                    format!(
                        "  file store {} root={:?}",
                        file_store.name, file_store.root
                    ),
                );
                // Globs are serialized only when present, so stores without an
                // `allow` clause keep their prior snapshot (no ripple).
                if !file_store.read_globs.is_empty() {
                    push_line(
                        &mut snapshot,
                        format!("    allow read {:?}", file_store.read_globs),
                    );
                }
                if !file_store.write_globs.is_empty() {
                    push_line(
                        &mut snapshot,
                        format!("    allow write {:?}", file_store.write_globs),
                    );
                }
                // The provider likewise serializes only when declared (unset =
                // the `local` default), so provider-less stores keep their
                // prior `.ir` byte-identically (slice F5 zero-churn gate).
                if let Some(provider) = &file_store.provider {
                    push_line(&mut snapshot, format!("    provider {provider}"));
                }
            }
        }

        if !self.memory_pools.is_empty() {
            push_line(&mut snapshot, "memory_pools");
            for pool in &self.memory_pools {
                push_line(&mut snapshot, format!("  memory pool {}", pool.name));
                // The context limit is serialized only when present, so pools
                // without it keep a minimal snapshot (no ripple).
                if let Some(limit) = pool.context_limit {
                    push_line(&mut snapshot, format!("    context limit {limit}"));
                }
            }
        }

        if !self.agents.is_empty() {
            push_line(&mut snapshot, "agents");
            for agent in &self.agents {
                let profile = agent.profile.as_deref().unwrap_or("<missing>");
                let harness = agent.harness.as_deref().unwrap_or("<fallback>");
                let provider = agent.provider.as_deref().unwrap_or("<fallback>");
                let capacity = agent
                    .capacity
                    .map(|capacity| capacity.to_string())
                    .unwrap_or_else(|| "<missing>".to_owned());
                let skills = if agent.skills.is_empty() {
                    "[]".to_owned()
                } else {
                    format!("[{}]", agent.skills.join(", "))
                };
                let capabilities = if agent.capabilities.is_empty() {
                    "[]".to_owned()
                } else {
                    format!("[{}]", agent.capabilities.join(", "))
                };
                let tools = if agent.tools.is_empty() {
                    "[]".to_owned()
                } else {
                    format!("[{}]", agent.tools.join(", "))
                };
                // Feature requirements append only when declared, so agents
                // without `requires` keep an unchanged .ir snapshot (no ripple).
                let requires = if agent.requires.is_empty() {
                    String::new()
                } else {
                    format!(" requires=[{}]", agent.requires.join(", "))
                };
                // Compaction strategy appends only when set, so agents that take the
                // harness default keep an unchanged .ir snapshot (no ripple).
                let compaction = agent
                    .compaction
                    .as_deref()
                    .map(|strategy| format!(" compaction={strategy}"))
                    .unwrap_or_default();
                // Settings likewise appends only when set (unset = provider default).
                let settings = agent
                    .settings
                    .as_deref()
                    .map(|sources| format!(" settings={sources}"))
                    .unwrap_or_default();
                // Thread mode likewise appends only when set (unset = fresh).
                let thread = agent
                    .thread
                    .as_deref()
                    .map(|mode| format!(" thread={mode}"))
                    .unwrap_or_default();
                // Harness class (DR-0034): Managed is the default/substrate, so only
                // Delegated agents emit a class token — Managed agents' .ir is unchanged.
                let class = match agent.harness_class {
                    HarnessClass::Delegated => " class=delegated",
                    HarnessClass::Managed => "",
                };
                push_line(
                    &mut snapshot,
                    format!(
                        "  agent {} harness={} provider={} profile={} capacity={} skills={} capabilities={} tools={}{}{}{}{}{}",
                        agent.name, harness, provider, profile, capacity, skills, capabilities, tools, requires, compaction, settings, thread, class
                    ),
                );
            }
        }

        if !self.coerces.is_empty() {
            push_line(&mut snapshot, "coerces");
            for coerce in &self.coerces {
                let params = coerce
                    .params
                    .iter()
                    .map(|param| format!("{} {}", param.name, param.ty.to_snapshot()))
                    .collect::<Vec<_>>()
                    .join(", ");
                push_line(
                    &mut snapshot,
                    format!(
                        "  coerce {}({}) -> {}",
                        coerce.name,
                        params,
                        coerce.output.to_snapshot()
                    ),
                );
            }
        }

        if !self.assertions.is_empty() {
            push_line(&mut snapshot, "assertions");
            for assertion in &self.assertions {
                push_line(
                    &mut snapshot,
                    format!("  assert {}", assertion.expr.expr.to_snapshot()),
                );
                if !assertion.projection_reads.is_empty() {
                    push_line(&mut snapshot, "    reads");
                    for read in &assertion.projection_reads {
                        push_line(&mut snapshot, format!("      {}", read.to_snapshot()));
                    }
                }
            }
        }

        if !self.rules.is_empty() {
            push_line(&mut snapshot, "rules");
            for rule in &self.rules {
                push_line(&mut snapshot, format!("  rule {}", rule.name));
                for when in &rule.whens {
                    match &when.guard {
                        Some(guard) => push_line(
                            &mut snapshot,
                            format!(
                                "    when {} where {}",
                                when.pattern,
                                guard.expr.to_snapshot()
                            ),
                        ),
                        None => push_line(&mut snapshot, format!("    when {}", when.pattern)),
                    }
                }
                if !rule.metadata.fact_reads.is_empty() {
                    push_line(&mut snapshot, "    reads");
                    for read in &rule.metadata.fact_reads {
                        push_line(&mut snapshot, format!("      {}", read));
                    }
                }
                if !rule.metadata.projection_reads.is_empty() {
                    push_line(&mut snapshot, "    projection_reads");
                    for read in &rule.metadata.projection_reads {
                        push_line(&mut snapshot, format!("      {}", read.to_snapshot()));
                    }
                }
                if !rule.metadata.fact_writes.is_empty() {
                    push_line(&mut snapshot, "    writes");
                    for write in &rule.metadata.fact_writes {
                        push_line(&mut snapshot, format!("      {}", write));
                    }
                }
                if !rule.metadata.record_sources.is_empty() {
                    push_line(&mut snapshot, "    record_sources");
                    for source in &rule.metadata.record_sources {
                        push_line(
                            &mut snapshot,
                            format!(
                                "      schema:{} construct={} span={}..{}",
                                source.schema, source.construct, source.span.start, source.span.end
                            ),
                        );
                    }
                }
                if !rule.metadata.fact_consumes.is_empty() {
                    push_line(&mut snapshot, "    consumes");
                    for consumed in &rule.metadata.fact_consumes {
                        push_line(&mut snapshot, format!("      {}", consumed));
                    }
                }
                if !rule.metadata.effects.is_empty() {
                    push_line(&mut snapshot, "    effects");
                    for effect in &rule.metadata.effects {
                        let binding = effect.binding.as_deref().unwrap_or("-");
                        let construct = effect
                            .construct_use
                            .as_ref()
                            .map(|form| {
                                format!(" construct={}->{}", form.keyword, form.target_capability)
                            })
                            .unwrap_or_default();
                        // Turn-access grants are appended only when present, so
                        // grant-free effects keep their existing snapshot shape.
                        let grants = if effect.access_grants.is_empty() {
                            String::new()
                        } else {
                            let rendered = effect
                                .access_grants
                                .iter()
                                .map(|grant| {
                                    let ops = grant
                                        .operations
                                        .iter()
                                        .map(|op| op.operation.as_str())
                                        .collect::<Vec<_>>()
                                        .join(",");
                                    format!("{}[{ops}]", grant.resource)
                                })
                                .collect::<Vec<_>>()
                                .join(";");
                            format!(" grants={rendered}")
                        };
                        // Turn-scoped skill pins (Phase 7) append only when present,
                        // so pin-free effects keep their existing snapshot shape.
                        let homing = effect
                            .on_stream
                            .as_ref()
                            .map(|stream| format!(" on_stream={stream}"))
                            .unwrap_or_default();
                        let skills = if effect.turn_skills.is_empty() {
                            String::new()
                        } else {
                            format!(" skills={}", effect.turn_skills.join(","))
                        };
                        push_line(
                            &mut snapshot,
                            format!(
                                "      {} kind={} binding={}{} key={}{}{}{}",
                                effect.id,
                                effect.kind.as_str(),
                                binding,
                                construct,
                                effect.idempotency_key,
                                grants,
                                skills,
                                homing
                            ),
                        );
                    }
                }
                if !rule.metadata.dependencies.is_empty() {
                    push_line(&mut snapshot, "    dependencies");
                    for dependency in &rule.metadata.dependencies {
                        push_line(
                            &mut snapshot,
                            format!(
                                "      {} --{}--> {}",
                                dependency.upstream,
                                dependency.predicate.as_str(),
                                dependency.downstream
                            ),
                        );
                    }
                }
                if !rule.metadata.case_branches.is_empty() {
                    push_line(&mut snapshot, "    case_branches");
                    for branch in &rule.metadata.case_branches {
                        let guard = branch
                            .guard
                            .as_ref()
                            .map(|guard| guard.expr.to_snapshot())
                            .unwrap_or_else(|| "-".to_owned());
                        push_line(
                            &mut snapshot,
                            format!(
                                "      case {} type={} pattern={} guard={} body_hash={} span={}..{}",
                                branch.scrutinee,
                                branch.scrutinee_type.to_snapshot(),
                                branch.pattern.to_snapshot(),
                                guard,
                                branch.body_hash,
                                branch.pattern_span.start,
                                branch.pattern_span.end
                            ),
                        );
                    }
                }
                if !rule.metadata.terminal_outputs.is_empty() {
                    push_line(&mut snapshot, "    terminal_outputs");
                    for output in &rule.metadata.terminal_outputs {
                        push_line(
                            &mut snapshot,
                            format!(
                                "      {} span={}..{}",
                                output.binding, output.span.start, output.span.end
                            ),
                        );
                        for alternative in &output.alternatives {
                            push_line(
                                &mut snapshot,
                                format!(
                                    "        {} payload={} span={}..{}",
                                    alternative.tag,
                                    alternative.payload_type.to_snapshot(),
                                    alternative.source_span.start,
                                    alternative.source_span.end
                                ),
                            );
                        }
                    }
                }
                if !rule.metadata.terminal_branches.is_empty() {
                    push_line(&mut snapshot, "    terminal_branches");
                    for branch in &rule.metadata.terminal_branches {
                        let tag = branch.tag.as_deref().unwrap_or("_");
                        let binding = branch.binding.as_deref().unwrap_or("-");
                        let guard = branch
                            .guard
                            .as_ref()
                            .map(|guard| guard.expr.to_snapshot())
                            .unwrap_or_else(|| "-".to_owned());
                        push_line(
                            &mut snapshot,
                            format!(
                                "      case {} {} binding={} guard={} body_hash={} span={}..{}",
                                branch.scrutinee,
                                tag,
                                binding,
                                guard,
                                branch.body_hash,
                                branch.pattern_span.start,
                                branch.pattern_span.end
                            ),
                        );
                    }
                }
                push_line(
                    &mut snapshot,
                    format!("    body_hash {}", stable_hash(&rule.body)),
                );
            }
        }

        if !self.rule_dependencies.is_empty() {
            push_line(&mut snapshot, "rule_dependencies");
            for dependency in &self.rule_dependencies {
                push_line(
                    &mut snapshot,
                    format!(
                        "  {} --{}--> {}",
                        dependency.producer, dependency.fact, dependency.consumer
                    ),
                );
            }
        }

        snapshot
    }
}

fn register_standard_library(libraries: &mut BTreeMap<String, LibraryRegistration>, id: &str) {
    libraries
        .entry(id.to_owned())
        .or_insert_with(|| LibraryRegistration {
            id: id.to_owned(),
            version: "0.1.0".to_owned(),
            standard: true,
        });
}

fn register_effect_contract(
    libraries: &mut BTreeMap<String, LibraryRegistration>,
    contracts: &mut BTreeMap<(String, String), EffectContract>,
    kind: IrEffectKind,
    required_capabilities: Vec<String>,
) {
    let contract = effect_contract_for_kind(kind, required_capabilities);
    register_standard_library(libraries, contract.library_id.as_str());
    contracts
        .entry((contract.id.clone(), contract.version.clone()))
        .and_modify(|existing| {
            merge_unique(
                &mut existing.required_capabilities,
                &contract.required_capabilities,
            );
            merge_unique(&mut existing.provider_kinds, &contract.provider_kinds);
            merge_unique(&mut existing.source_forms, &contract.source_forms);
            merge_unique(&mut existing.projected_facts, &contract.projected_facts);
        })
        .or_insert(contract);
}

fn merge_unique(target: &mut Vec<String>, values: &[String]) {
    for value in values {
        if !target.contains(value) {
            target.push(value.clone());
        }
    }
    target.sort();
}

fn strings(values: &[&str]) -> Vec<String> {
    values.iter().map(|value| (*value).to_owned()).collect()
}

fn effect_contract_for_kind(
    kind: IrEffectKind,
    required_capabilities: Vec<String>,
) -> EffectContract {
    let mut required_capabilities = required_capabilities;
    required_capabilities.sort();
    required_capabilities.dedup();
    let effect_kind = kind.as_str().to_owned();

    let (
        library_id,
        source_forms,
        input_schema,
        output_schema,
        default_capabilities,
        provider_kinds,
        projected_facts,
        validation,
    ) = match kind {
        IrEffectKind::AgentTell => (
            "std.agent",
            strings(&["tell"]),
            Some("agent.turn.request"),
            Some("AgentTurn"),
            strings(&["agent.turn"]),
            strings(&["agent"]),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::SchemaCoerce => (
            "std.coercion",
            strings(&["coerce", "decide", "prompt"]),
            Some("schema.coerce.input"),
            Some("typed-provider-output"),
            // Capability id == effect kind (spec/std-coercion.md "Static
            // checks" 1: the never-enforced `model.invoke` died with the S2
            // rename), and the provider kind is the kernel's
            // `provider::PROVIDER_SCHEMA_COERCE` ("schema_coercer") string — a
            // schema coercer, not a generic model row.
            strings(&["schema.coerce"]),
            strings(&["schema_coercer"]),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::CapabilityCall => (
            "std.script",
            strings(&["call"]),
            Some("capability.call.input"),
            Some("capability.call.output"),
            Vec::new(),
            strings(&["capability"]),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::EventEmit => (
            "std.ingress",
            strings(&["emit"]),
            Some("event.emit.input"),
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::WorkflowInvoke => (
            "std.workflow",
            strings(&["invoke"]),
            Some("workflow.invoke.input"),
            Some("workflow.terminal"),
            Vec::new(),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::TimerWait => (
            "std.time",
            strings(&["timer"]),
            Some("timer.wait.input"),
            Some("TimerElapsed"),
            Vec::new(),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::None,
        ),
        IrEffectKind::ExecCommand => (
            "std.script",
            strings(&["exec"]),
            Some("exec.command.input"),
            Some("exec.command.output"),
            strings(&["exec.run"]),
            strings(&["script", "command"]),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::TrackerFile => (
            "std.tracker",
            strings(&["file"]),
            Some("tracker.file.input"),
            None,
            strings(&["tracker.file"]),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::TrackerClaim => (
            "std.tracker",
            strings(&["claim"]),
            Some("tracker.claim.input"),
            Some("TrackerClaim"),
            strings(&["tracker.claim"]),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::None,
        ),
        // T3: holder-only renew of a claimed issue. No typed output schema (the
        // renewed/not_held outcome is a completed/failed terminal, mirroring
        // tracker.release), so the manifest contract row folds cleanly against
        // this compiled one.
        IrEffectKind::TrackerRenew => (
            "std.tracker",
            strings(&["renew"]),
            Some("tracker.renew.input"),
            None,
            strings(&["tracker.renew"]),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::TrackerRelease => (
            "std.tracker",
            strings(&["release"]),
            Some("tracker.release.input"),
            None,
            strings(&["tracker.release"]),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::TrackerFinish => (
            "std.tracker",
            strings(&["finish"]),
            Some("tracker.finish.input"),
            None,
            strings(&["tracker.finish"]),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::LeaseAcquire => (
            "std.coord",
            strings(&["acquire"]),
            Some("lease.acquire.input"),
            Some("LeaseAcquireOutcome"),
            Vec::new(),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::None,
        ),
        IrEffectKind::LeaseRenew => (
            "std.coord",
            strings(&["renew"]),
            Some("lease.renew.input"),
            Some("LeaseRenewOutcome"),
            Vec::new(),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::None,
        ),
        IrEffectKind::LedgerAppend => (
            "std.coord",
            strings(&["append"]),
            Some("ledger.append.input"),
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        IrEffectKind::CounterConsume => (
            "std.coord",
            strings(&["consume"]),
            Some("counter.consume.input"),
            Some("CounterConsumeOutcome"),
            Vec::new(),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::None,
        ),
        IrEffectKind::SignalEmit => (
            "std.ingress",
            strings(&["emit", "signal"]),
            Some("signal.emit.input"),
            None,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            TypedOutputValidation::None,
        ),
        // std.files capability ids EQUAL effect kinds (spec/std-files.md, M3
        // id==kind): each contract requires exactly its own kind string, which
        // the store's default-required-capability rule already derives for an
        // empty list — declaring it here makes the registry honest about it.
        IrEffectKind::FileRead => (
            "std.files",
            strings(&["read"]),
            Some("file.read.input"),
            Some("FileReadResult"),
            strings(&["file.read"]),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::FileWrite => (
            "std.files",
            strings(&["write"]),
            Some("file.write.input"),
            Some("FileWriteResult"),
            strings(&["file.write"]),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::FileImport => (
            "std.files",
            strings(&["import"]),
            Some("file.import.input"),
            Some("FileImportResult"),
            strings(&["file.import"]),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
        IrEffectKind::FileExport => (
            "std.files",
            strings(&["export"]),
            Some("file.export.input"),
            Some("FileExportResult"),
            strings(&["file.export"]),
            Vec::new(),
            strings(&["effect.output"]),
            TypedOutputValidation::RuntimeBoundary,
        ),
    };

    merge_unique(&mut required_capabilities, &default_capabilities);

    EffectContract {
        id: effect_kind.clone(),
        library_id: library_id.to_owned(),
        version: "0.1.0".to_owned(),
        effect_kind,
        source_forms,
        input_schema: input_schema.map(str::to_owned),
        output_schema: output_schema.map(str::to_owned),
        required_capabilities,
        provider_kinds,
        projected_facts,
        validation,
    }
}

impl IrEffectKind {
    /// The single canonical `IrEffectKind` → effect-kind string map. Kernel and
    /// CLI delegate here (S0 dedup) so a rename touches exactly one match.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AgentTell => "agent.tell",
            Self::SchemaCoerce => "schema.coerce",
            Self::CapabilityCall => "capability.call",
            Self::EventEmit => "event.emit",
            Self::WorkflowInvoke => "workflow.invoke",
            Self::TimerWait => "timer.wait",
            Self::ExecCommand => "exec.command",
            Self::TrackerFile => "tracker.file",
            Self::TrackerClaim => "tracker.claim",
            Self::TrackerRenew => "tracker.renew",
            Self::TrackerRelease => "tracker.release",
            Self::TrackerFinish => "tracker.finish",
            Self::LeaseAcquire => "lease.acquire",
            Self::LeaseRenew => "lease.renew",
            Self::LedgerAppend => "ledger.append",
            Self::CounterConsume => "counter.consume",
            Self::SignalEmit => "signal.emit",
            Self::FileRead => "file.read",
            Self::FileWrite => "file.write",
            Self::FileImport => "file.import",
            Self::FileExport => "file.export",
        }
    }
}

impl DependencyPredicate {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Succeeds => "succeeds",
            Self::Fails => "fails",
            Self::TimedOut => "timed_out",
            Self::Cancelled => "cancelled",
            Self::Completes => "completes",
        }
    }
}

impl IrUseKind {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Package => "package",
        }
    }
}

impl IrType {
    /// A human-readable label for this type (e.g. `ref<TicketRequest>`), for use in
    /// diagnostics such as workflow-input errors.
    pub fn display_label(&self) -> String {
        self.to_snapshot()
    }

    fn to_snapshot(&self) -> String {
        match self {
            Self::Primitive(primitive) => primitive.as_str().to_owned(),
            Self::LiteralString(value) => format!("literal<{value:?}>"),
            Self::Ref(name) => format!("ref<{name}>"),
            Self::AgentRef(agents) => format!("agentref<{}>", agents.join(" | ")),
            Self::Object(fields) => {
                let fields = fields
                    .iter()
                    .map(|field| format!("{} {}", field.name, field.ty.to_snapshot()))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("object<{{{fields}}}>")
            }
            Self::Optional(inner) => format!("optional<{}>", inner.to_snapshot()),
            Self::Array(inner) => format!("array<{}>", inner.to_snapshot()),
            Self::Map(inner) => format!("map<{}>", inner.to_snapshot()),
            Self::Union(variants) => {
                let variants = variants
                    .iter()
                    .map(Self::to_snapshot)
                    .collect::<Vec<_>>()
                    .join(" | ");
                format!("union<{variants}>")
            }
        }
    }
}

impl IrPrimitiveType {
    fn as_str(&self) -> &'static str {
        match self {
            Self::String => "string",
            Self::Int => "int",
            Self::Float => "float",
            Self::Bool => "bool",
            Self::Null => "null",
            Self::Duration => "duration",
            Self::Time => "time",
            Self::Image => "image",
            Self::Audio => "audio",
            Self::Pdf => "pdf",
            Self::Video => "video",
            Self::Secret => "secret",
        }
    }
}

/// Post-lowering check: a turn-access grant whose resource is a declared `file store`
/// may only grant file operations (`read`/`write`/`import`/`export`). Runs after the
/// whole program is lowered so every file-store declaration is visible regardless of
/// source order. Grants whose resource is NOT a declared file store are left alone —
/// they may be package-provided resources whose operation vocabulary lives in the
/// capability registry (validated at the construct-graph layer), so this stays
/// zero-false-positive.
fn validate_turn_access_grant_file_operations(ir: &IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    const FILE_OPERATIONS: [&str; 4] = ["read", "write", "import", "export"];
    let file_stores: BTreeSet<&str> = ir
        .file_stores
        .iter()
        .map(|store| store.name.as_str())
        .collect();
    for rule in &ir.rules {
        for effect in &rule.metadata.effects {
            for grant in &effect.access_grants {
                if !file_stores.contains(grant.resource.as_str()) {
                    continue;
                }
                for op in &grant.operations {
                    if !FILE_OPERATIONS.contains(&op.operation.as_str()) {
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` grants `{}` on file store `{}`, which is not a file operation",
                                rule.name, op.operation, grant.resource
                            ),
                            suggestion: Some(
                                "file-store grants allow `read`, `write`, `import`, or `export`"
                                    .to_owned(),
                            ),
                        });
                    }
                }
            }
        }
    }
}

/// Post-lowering check: a turn-access grant whose resource is a declared `memory
/// pool` (std.memory, MEM-1) may only grant memory operations
/// (`recall`/`learn`/`curate`). Runs after the whole program is lowered so every
/// pool declaration is visible regardless of source order. Grants whose resource
/// is NOT a declared memory pool are left alone — they may be file stores or
/// package-provided resources whose operation vocabulary lives elsewhere, so this
/// stays zero-false-positive. This closes the deliberate memory-grant-validation
/// deferral (there was no declared-pool list to key it off before MEM-1).
fn validate_turn_access_grant_memory_operations(ir: &IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    const MEMORY_OPERATIONS: [&str; 3] = ["recall", "learn", "curate"];
    let memory_pools: BTreeSet<&str> = ir
        .memory_pools
        .iter()
        .map(|pool| pool.name.as_str())
        .collect();
    for rule in &ir.rules {
        for effect in &rule.metadata.effects {
            for grant in &effect.access_grants {
                if !memory_pools.contains(grant.resource.as_str()) {
                    continue;
                }
                for op in &grant.operations {
                    if !MEMORY_OPERATIONS.contains(&op.operation.as_str()) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` grants `{}` on memory pool `{}`, which is not a memory operation",
                                rule.name, op.operation, grant.resource
                            ),
                            suggestion: Some(
                                "memory-pool grants allow `recall`, `learn`, or `curate`".to_owned(),
                            ),
                        });
                    }
                }
            }
        }
    }
}

/// std.coord slice 3: a counter without a declared `timezone` anchors its
/// reset-period boundary to UTC — legal, but a daily/weekly/monthly quota
/// silently rolling over at an operator-surprising hour is worth a warning.
/// S4 (file-store default posture): a store is READ-ONLY by default — a
/// `write`/`export` against a store with no `allow write [...]` policy will
/// fail closed at runtime, so surface it as a check error here ("catch before
/// deployment"). Reads/imports need no clause (mounting the root is the read
/// consent); `allow read [...]` narrows them.
fn validate_file_store_write_policy(ir: &IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    let read_only: BTreeSet<&str> = ir
        .file_stores
        .iter()
        .filter(|store| store.write_globs.is_empty())
        .map(|store| store.name.as_str())
        .collect();
    if read_only.is_empty() {
        return;
    }
    fn walk(
        statements: &[body::BodyStmt],
        rule_name: &str,
        read_only: &BTreeSet<&str>,
        diagnostics: &mut Vec<Diagnostic>,
    ) {
        for statement in statements {
            match statement {
                body::BodyStmt::Effect(effect) => {
                    let store = match &effect.kind {
                        body::BodyEffectKind::FileWrite { store, .. }
                        | body::BodyEffectKind::FileExport { store, .. } => Some(store),
                        _ => None,
                    };
                    if let Some(store) = store {
                        if read_only.contains(store.as_str()) {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: effect.span,
                                message: format!(
                                    "rule `{rule_name}` writes to store `{store}`, which permits \
                                     no writes — stores are read-only by default"
                                ),
                                suggestion: Some(format!(
                                    "declare `allow write [\"<glob>\", …]` on `file store {store}` \
                                     to permit (and bound) writes"
                                )),
                            });
                        }
                    }
                }
                body::BodyStmt::After(after) => {
                    walk(&after.body, rule_name, read_only, diagnostics)
                }
                body::BodyStmt::Case(case) => {
                    for branch in &case.branches {
                        walk(&branch.body, rule_name, read_only, diagnostics);
                    }
                }
                _ => {}
            }
        }
    }
    for rule in &ir.rules {
        let (ast, _) = body::parse_rule_body(&rule.body, 0);
        walk(&ast.statements, &rule.name, &read_only, diagnostics);
    }
}

/// S6 `emit <signal> from <binding>` (source declarations): expand the
/// projection into concrete emit fields once every declaration has lowered
/// (the signal may be declared after the source). Each of the signal's
/// declared fields not overridden by the block becomes a copy off the `from`
/// binding — the `record … from` semantics. The `from` binding must be the
/// source's `observe` binding: it is the only binding in scope.
fn expand_source_emit_from(ir: &mut IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    let events: BTreeMap<String, Vec<String>> = ir
        .events
        .iter()
        .map(|event| {
            (
                event.name.clone(),
                event
                    .fields
                    .iter()
                    .map(|field| field.name.clone())
                    .collect(),
            )
        })
        .collect();
    for source in &mut ir.sources {
        let Some(from) = source.emit_from.clone() else {
            continue;
        };
        if from != source.observe_binding {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: source.span,
                message: format!(
                    "source `{}` emits `from {from}`, but the only binding in scope is the observe binding `{}`",
                    source.name, source.observe_binding
                ),
                suggestion: Some(format!("write `emit {} from {}`", source.emit_signal, source.observe_binding)),
            });
            continue;
        }
        let Some(signal_fields) = events.get(&source.emit_signal) else {
            // The undeclared-signal diagnostic is reported by the emit checks.
            continue;
        };
        for field in signal_fields {
            if source
                .emit_fields
                .iter()
                .any(|existing| &existing.name == field)
            {
                continue;
            }
            source.emit_fields.push(IrSourceEmitField {
                name: field.clone(),
                value: SourceValue::Path {
                    binding: Ident {
                        name: from.clone(),
                        span: source.span,
                    },
                    segments: vec![Ident {
                        name: field.clone(),
                        span: source.span,
                    }],
                    span: source.span,
                },
                span: source.span,
            });
        }
    }
}

/// Auto-fail R1a — partiality made visible: an effect whose failure has no
/// observing `after` block in its rule will auto-fail the instance at runtime
/// (the rule-level net). That is SAFE, but the "handles only `succeeds`" signal
/// is load-bearing enough to surface prominently at check time — a warning, not
/// a buried lint advisory. `@service` workflows are exempt (they record a
/// durable diagnostic and keep running, so the auto-fail framing would be
/// wrong), timers are exempt (they cannot fail), and the compile-time observer
/// set is deliberately WIDER than the runtime net's: coordination outcome
/// predicates (`held`/`contended`/`ok`/`over`) count as observers here so
/// ordinary coordination code stays quiet, while the runtime net still catches
/// a genuine op failure underneath them.
fn warn_unhandled_effect_failures(ir: &IrProgram, warnings: &mut Vec<Diagnostic>) {
    let service = ir
        .source_tags
        .iter()
        .any(|tag| tag.target_kind == "workflow" && tag.name == "service");
    if service {
        return;
    }
    for rule in &ir.rules {
        for effect in &rule.metadata.effects {
            let Some(binding) = effect.binding.as_deref() else {
                continue;
            };
            if effect.kind == IrEffectKind::TimerWait {
                continue;
            }
            // A `then`-chained effect (synthetic `__then_*` handle) is an
            // explicit opt-in to auto-fail on failure (R2) — never a warning.
            if binding.starts_with(then_expand::THEN_BINDING_PREFIX) {
                continue;
            }
            let observed = rule.body.lines().any(|line| {
                let Some(rest) = line.trim().strip_prefix("after ") else {
                    return false;
                };
                let mut parts = rest.split_whitespace();
                if parts.next() != Some(binding) {
                    return false;
                }
                // `times` only occurs as the two-token predicate `times out`.
                matches!(
                    parts.next().map(|token| token.trim_end_matches('{')),
                    Some(
                        "fails"
                            | "times"
                            | "completes"
                            | "held"
                            | "contended"
                            | "ok"
                            | "over"
                            | "promoted"
                            | "conflicted"
                    )
                )
            });
            if observed {
                continue;
            }
            warnings.push(Diagnostic {
                related: Vec::new(),
                span: effect.span,
                message: format!(
                    "effect `{binding}`'s failure is unhandled in rule `{}`; if it fails or \
                     times out, the instance will auto-fail with a generic reason",
                    rule.name
                ),
                suggestion: Some(format!(
                    "handle it with `after {binding} fails {{}}` (typed failure or recovery) \
                     or observe every outcome with `after {binding} completes`"
                )),
            });
        }
    }
}

fn warn_counter_without_timezone(ir: &IrProgram, warnings: &mut Vec<Diagnostic>) {
    for counter in &ir.counters {
        if counter.timezone.is_none() {
            warnings.push(Diagnostic {
                related: Vec::new(),
                span: counter.span,
                message: format!(
                    "counter `{}` declares no `timezone`; its `{}` reset boundary anchors to UTC",
                    counter.name, counter.reset
                ),
                suggestion: Some(
                    "declare `timezone \"<IANA zone>\"` (e.g. `timezone \"America/New_York\"`) to anchor the period locally"
                        .to_owned(),
                ),
            });
        }
    }
}

/// MEM-5 static check 4: a memory-pool grant on a `tell` whose agent runs a
/// NATIVE adapter (codex/claude/command) is inert — only the owned harness
/// exposes the granted memory tools. Warn instead of silently dropping the
/// author's intent (the inert-grant honesty the design eliminates).
fn warn_inert_memory_grant_on_native_adapter(ir: &IrProgram, warnings: &mut Vec<Diagnostic>) {
    let memory_pools: BTreeSet<&str> = ir
        .memory_pools
        .iter()
        .map(|pool| pool.name.as_str())
        .collect();
    if memory_pools.is_empty() {
        return;
    }
    let harness_kind_of: BTreeMap<&str, &str> = ir
        .harnesses
        .iter()
        .map(|harness| (harness.name.as_str(), harness.kind.as_str()))
        .collect();
    let agent_harness_kind: BTreeMap<&str, &str> = ir
        .agents
        .iter()
        .filter_map(|agent| {
            let harness = agent.harness.as_deref()?;
            Some((agent.name.as_str(), *harness_kind_of.get(harness)?))
        })
        .collect();
    for rule in &ir.rules {
        for effect in &rule.metadata.effects {
            let Some(agent) = effect.agent.as_deref() else {
                continue;
            };
            let Some(kind) = agent_harness_kind.get(agent) else {
                continue;
            };
            if !matches!(*kind, "codex" | "claude" | "command") {
                continue;
            }
            for grant in &effect.access_grants {
                if memory_pools.contains(grant.resource.as_str()) {
                    warnings.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: format!(
                            "rule `{}` grants memory pool `{}` on a tell to `{agent}`, whose \
                             harness kind `{kind}` is a native adapter — memory grants only \
                             take effect on the owned harness, so this grant is inert",
                            rule.name, grant.resource
                        ),
                        suggestion: Some(
                            "target an owned-harness agent, or drop the memory grant".to_owned(),
                        ),
                    });
                }
            }
        }
    }
}

/// Detect recursive pattern application over the pattern-declaration graph and
/// emit `graph.unbounded_pattern_recursion` (severity error) for each expansion
/// cycle, naming the cycle. Returns the set of patterns that participate in a
/// cycle so the caller can suppress the generic "nested apply" message for them.
///
/// A pattern's body that `apply`s another pattern is an edge; a pattern that can
/// reach itself (directly via a self-apply, or transitively) cannot elaborate into
/// a finite first-order program, so v0 rejects it (spec/static-analysis.md). The
/// reachability closure mirrors `models/maude/pattern-recursion.maude`.
fn detect_pattern_recursion(
    patterns: &BTreeMap<String, PatternDecl>,
    diagnostics: &mut Vec<Diagnostic>,
) -> BTreeSet<String> {
    // Application edges: pattern name -> the patterns its body applies, with spans.
    let mut edges: BTreeMap<&str, Vec<(&str, SourceSpan)>> = BTreeMap::new();
    for pattern in patterns.values() {
        let mut applied = Vec::new();
        for item in &pattern.items {
            if let Item::Apply(apply) = item {
                applied.push((apply.pattern.name.as_str(), apply.span));
            }
        }
        edges.insert(pattern.name.name.as_str(), applied);
    }

    // A pattern is recursive iff it can reach itself. Find a shortest cycle path
    // back to `start` via breadth-first search, tracking each node's predecessor.
    let find_cycle = |start: &str| -> Option<(Vec<String>, SourceSpan)> {
        let mut queue: VecDeque<&str> = VecDeque::new();
        // predecessor[node] = (came_from, span_of_edge) used to first reach `node`.
        let mut predecessor: BTreeMap<&str, (&str, SourceSpan)> = BTreeMap::new();
        for &(target, span) in edges.get(start).into_iter().flatten() {
            if target == start {
                // Direct self-application.
                return Some((vec![start.to_owned(), start.to_owned()], span));
            }
            if predecessor.insert(target, (start, span)).is_none() {
                queue.push_back(target);
            }
        }
        while let Some(node) = queue.pop_front() {
            for &(target, span) in edges.get(node).into_iter().flatten() {
                if target == start {
                    // Reconstruct start -> ... -> node, then close back to start.
                    let mut path = vec![node.to_owned()];
                    let mut cursor = node;
                    while cursor != start {
                        let (from, _) = predecessor[cursor];
                        path.push(from.to_owned());
                        cursor = from;
                    }
                    path.reverse();
                    path.push(start.to_owned());
                    // Report at the first apply edge of `start` that enters the cycle.
                    let first = &path[1];
                    let entry_span = edges
                        .get(start)
                        .into_iter()
                        .flatten()
                        .find(|(target, _)| target == first)
                        .map(|(_, span)| *span)
                        .unwrap_or(span);
                    return Some((path, entry_span));
                }
                if predecessor.insert(target, (node, span)).is_none() {
                    queue.push_back(target);
                }
            }
        }
        None
    };

    let mut recursive = BTreeSet::new();
    // Iterate patterns in declaration-name order for deterministic diagnostics, and
    // report each cycle once by skipping members already covered by a prior cycle.
    for name in patterns.keys() {
        if recursive.contains(name) {
            continue;
        }
        if let Some((cycle, span)) = find_cycle(name) {
            for member in &cycle {
                recursive.insert(member.clone());
            }
            diagnostics.push(Diagnostic { related: Vec::new(),
                span,
                message: format!(
                    "recursive pattern application is not allowed (graph.unbounded_pattern_recursion): expansion cycle {}",
                    cycle.join(" -> ")
                ),
                suggestion: Some(
                    "break the cycle: pattern expansion must elaborate into a finite program"
                        .to_owned(),
                ),
            });
        }
    }
    recursive
}

/// Reject a *transitive* runtime workflow-invocation cycle (A invokes B invokes A,
/// or longer). RESOLVED 2026-07-01: the invoke-recursion policy is "as permissive
/// as provable convergence at compile time allows"; whipplescript has no
/// convergence proof for runtime `invoke` recursion (termination is data-dependent
/// and there is no decreasing-measure mechanism yet), so — exactly parallel to
/// `detect_pattern_recursion` — any cycle is rejected as
/// `graph.unbounded_workflow_invocation_recursion`. Direct self-invocation (a cycle
/// of length 1) is already rejected per-rule in `validate_workflow_invocations`, so
/// self-edges are excluded here and this catches only length >= 2 cycles. Modeled
/// as invoke-graph non-convergence in `models/maude/subworkflow-convergence.maude`.
fn detect_workflow_invoke_recursion(program: &Program, diagnostics: &mut Vec<Diagnostic>) {
    // Invoke edges: workflow name -> the workflows its rules invoke, with the span
    // of the invoking rule body. Built over the raw AST (all workflows), so it is
    // independent of root selection. Self-edges are excluded (owned by the direct
    // per-rule recursion check).
    let mut edges: BTreeMap<String, Vec<(String, SourceSpan)>> = BTreeMap::new();
    let record_invokes =
        |name: &str, items: &[Item], edges: &mut BTreeMap<String, Vec<(String, SourceSpan)>>| {
            let entry = edges.entry(name.to_owned()).or_default();
            for item in items {
                let Item::Rule(rule) = item else {
                    continue;
                };
                for statement in workflow_invoke_statements(&rule.body.text) {
                    if let Some((target, _)) = invoke_statement_parts(&statement) {
                        if target != name {
                            entry.push((target.to_owned(), rule.body.span));
                        }
                    }
                }
            }
        };
    if let Some(root) = &program.workflow {
        record_invokes(&root.name, &program.items, &mut edges);
    }
    for workflow in &program.workflows {
        record_invokes(&workflow.name.name, &workflow.items, &mut edges);
    }

    // A workflow is in a cycle iff it can reach itself over invoke edges. BFS for a
    // shortest path back to `start` (mirrors `detect_pattern_recursion`).
    let find_cycle = |start: &str| -> Option<(Vec<String>, SourceSpan)> {
        let mut queue: VecDeque<&str> = VecDeque::new();
        let mut predecessor: BTreeMap<&str, (&str, SourceSpan)> = BTreeMap::new();
        for (target, span) in edges.get(start).into_iter().flatten() {
            if predecessor
                .insert(target.as_str(), (start, *span))
                .is_none()
            {
                queue.push_back(target.as_str());
            }
        }
        while let Some(node) = queue.pop_front() {
            for (target, span) in edges.get(node).into_iter().flatten() {
                if target == start {
                    let mut path = vec![node.to_owned()];
                    let mut cursor = node;
                    while cursor != start {
                        let (from, _) = predecessor[cursor];
                        path.push(from.to_owned());
                        cursor = from;
                    }
                    path.reverse();
                    path.push(start.to_owned());
                    let first = &path[1];
                    let entry_span = edges
                        .get(start)
                        .into_iter()
                        .flatten()
                        .find(|(target, _)| target == first)
                        .map(|(_, span)| *span)
                        .unwrap_or(*span);
                    return Some((path, entry_span));
                }
                if predecessor.insert(target.as_str(), (node, *span)).is_none() {
                    queue.push_back(target.as_str());
                }
            }
        }
        None
    };

    let mut flagged: BTreeSet<String> = BTreeSet::new();
    for name in edges.keys() {
        if flagged.contains(name) {
            continue;
        }
        if let Some((cycle, span)) = find_cycle(name) {
            for member in &cycle {
                flagged.insert(member.clone());
            }
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span,
                message: format!(
                    "recursive workflow invocation is not allowed (graph.unbounded_workflow_invocation_recursion): invocation cycle {}",
                    cycle.join(" -> ")
                ),
                suggestion: Some(
                    "break the cycle: a runtime `invoke` cycle has no compile-time convergence proof; route the recurrence through an external event, clock, or durable boundary instead"
                        .to_owned(),
                ),
            });
        }
    }
}

fn detect_private_workflow_invocations(program: &Program, diagnostics: &mut Vec<Diagnostic>) {
    let private_workflows = program
        .workflows
        .iter()
        .filter(|workflow| workflow.tags.iter().any(|tag| tag.name == "private"))
        .map(|workflow| workflow.name.name.as_str())
        .collect::<BTreeSet<_>>();
    if private_workflows.is_empty() {
        return;
    }

    let mut record_private_invokes = |caller: &str, items: &[Item]| {
        for item in items {
            let Item::Rule(rule) = item else {
                continue;
            };
            for statement in workflow_invoke_statements(&rule.body.text) {
                let Some((target, _)) = invoke_statement_parts(&statement) else {
                    continue;
                };
                if caller == target || !private_workflows.contains(target) {
                    continue;
                }
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` invokes private workflow `{target}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "remove `@private` from the target workflow or expose a public wrapper workflow"
                            .to_owned(),
                    ),
                });
            }
        }
    };

    if let Some(root) = &program.workflow {
        record_private_invokes(&root.name, &program.items);
    }
    for workflow in &program.workflows {
        record_private_invokes(&workflow.name.name, &workflow.items);
    }
}

fn expand_pattern_applications(
    mut program: Program,
    diagnostics: &mut Vec<Diagnostic>,
) -> (Program, Vec<IrPatternApplication>) {
    let mut patterns = BTreeMap::new();
    for pattern in &program.patterns {
        if patterns
            .insert(pattern.name.name.clone(), pattern.clone())
            .is_some()
        {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: pattern.name.span,
                message: format!("pattern `{}` is declared more than once", pattern.name.name),
                suggestion: Some("rename one pattern declaration".to_owned()),
            });
        }
    }

    // v0 forbids recursive pattern application (spec/static-analysis.md,
    // graph.unbounded_pattern_recursion): an `apply` that reaches, directly or
    // transitively, a pattern already on the active expansion stack can never
    // elaborate into a finite first-order program. Detect cycles up front so the
    // precise diagnostic is emitted and the generic "nested apply not supported
    // yet" message is suppressed for the recursive case.
    let recursive_patterns = detect_pattern_recursion(&patterns, diagnostics);

    let mut expanded_items = Vec::new();
    let mut applications = Vec::new();
    for item in program.items {
        let Item::Apply(apply) = item else {
            expanded_items.push(item);
            continue;
        };
        let Some(pattern) = patterns.get(&apply.pattern.name) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: apply.pattern.span,
                message: format!("pattern `{}` was not found", apply.pattern.name),
                suggestion: Some("declare the pattern before applying it".to_owned()),
            });
            continue;
        };
        if pattern.type_params.len() != apply.type_args.len() {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: apply.span,
                message: format!(
                    "pattern `{}` expects {} type arguments but got {}",
                    pattern.name.name,
                    pattern.type_params.len(),
                    apply.type_args.len()
                ),
                suggestion: Some("match the pattern type parameter list".to_owned()),
            });
            continue;
        }
        let type_substitutions = pattern
            .type_params
            .iter()
            .map(|param| param.name.clone())
            .zip(apply.type_args.iter().cloned())
            .collect::<BTreeMap<_, _>>();
        let value_substitutions = parse_pattern_value_arguments(&apply, diagnostics);
        let local_names = pattern_local_names(pattern, &apply.alias.name);
        let definition_span = pattern.span;
        let application_span = apply.span;
        let mut generated = Vec::new();
        for pattern_item in pattern.items.iter().cloned() {
            // Enforce the pattern-body allow-list before expanding: a pattern
            // is a compile-time reuse fragment, not a workflow, so forbidden
            // constructs are rejected with a clear diagnostic and dropped.
            if let Some(diagnostic) = pattern_body_admission(&pattern_item, &recursive_patterns) {
                diagnostics.push(diagnostic);
                continue;
            }
            if let Some((generated_name, item)) = expand_pattern_item(
                pattern_item,
                &apply.alias.name,
                &type_substitutions,
                &value_substitutions,
                &local_names,
            ) {
                generated.push(generated_name);
                expanded_items.push(item);
            }
        }
        applications.push(IrPatternApplication {
            pattern: pattern.name.name.clone(),
            alias: apply.alias.name,
            type_args: apply.type_args.into_iter().map(lower_type).collect(),
            value_args: value_substitutions
                .into_iter()
                .map(|(name, value)| IrPatternArgument { name, value })
                .collect(),
            generated,
            definition_span,
            application_span,
        });
    }
    program.items = expanded_items;
    (program, applications)
}

fn pattern_local_names(pattern: &PatternDecl, alias: &str) -> BTreeMap<String, String> {
    let mut names = BTreeMap::new();
    for item in &pattern.items {
        match item {
            Item::Harness(harness) => {
                names.insert(
                    harness.name.name.clone(),
                    generated_pattern_name(alias, &harness.name.name),
                );
            }
            Item::Agent(agent) => {
                names.insert(
                    agent.name.name.clone(),
                    generated_pattern_name(alias, &agent.name.name),
                );
            }
            Item::Enum(enum_decl) => {
                names.insert(
                    enum_decl.name.name.clone(),
                    generated_pattern_name(alias, &enum_decl.name.name),
                );
            }
            Item::Class(class_decl) => {
                names.insert(
                    class_decl.name.name.clone(),
                    generated_pattern_name(alias, &class_decl.name.name),
                );
            }
            Item::Coerce(coerce) => {
                names.insert(
                    coerce.name.name.clone(),
                    generated_pattern_name(alias, &coerce.name.name),
                );
            }
            Item::Rule(rule) => {
                names.insert(
                    rule.name.name.clone(),
                    generated_pattern_name(alias, &rule.name.name),
                );
            }
            _ => {}
        }
    }
    names
}

fn generated_pattern_name(alias: &str, name: &str) -> String {
    format!("{alias}_{name}")
}

fn parse_pattern_value_arguments(
    apply: &ApplyDecl,
    diagnostics: &mut Vec<Diagnostic>,
) -> BTreeMap<String, String> {
    let mut args = BTreeMap::new();
    for line in apply
        .body
        .text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        let mut parts = line.splitn(2, char::is_whitespace);
        let Some(name) = parts.next().filter(|name| is_identifier(name)) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: apply.body.span,
                message: format!(
                    "pattern application `{}` has malformed argument `{line}`",
                    apply.alias.name
                ),
                suggestion: Some("write pattern arguments as `name value`".to_owned()),
            });
            continue;
        };
        let Some(value) = parts
            .next()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: apply.body.span,
                message: format!(
                    "pattern application `{}` argument `{name}` is missing a value",
                    apply.alias.name
                ),
                suggestion: Some("write pattern arguments as `name value`".to_owned()),
            });
            continue;
        };
        if args.insert(name.to_owned(), value.to_owned()).is_some() {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: apply.body.span,
                message: format!(
                    "pattern application `{}` passes argument `{name}` more than once",
                    apply.alias.name
                ),
                suggestion: Some("remove the duplicate pattern argument".to_owned()),
            });
        }
    }
    args
}

/// The explicit allow-list gate for a `pattern { ... }` body.
///
/// A pattern is a compile-time reuse fragment, not a workflow. Its body MAY
/// declare the building blocks of a workflow -- rules, effects (`coerce`),
/// records (via a rule's `record`), local schemas (`class`/`enum`), tables,
/// agents/harnesses, and coordination resources -- but it MUST NOT contain:
///   * workflow contracts (`input`/`output`/`failure`) -- workflow-level shape,
///   * nested `pattern` declarations,
///   * nested `apply` (pattern applications inside pattern bodies), or
///   * rules that reach a workflow terminal (`complete`/`fail`): a reusable
///     fragment must not hard-code the enclosing workflow's terminal outcome.
///
/// Returns `Some(diagnostic)` for a forbidden construct; `None` when the item is
/// on the allow-list.
fn pattern_body_admission(
    item: &Item,
    recursive_patterns: &BTreeSet<String>,
) -> Option<Diagnostic> {
    match item {
        Item::WorkflowContract(contract) => Some(Diagnostic {
            related: Vec::new(),
            span: contract.span,
            message: "workflow contracts are not allowed in pattern bodies".to_owned(),
            suggestion: Some(
                "declare workflow inputs, outputs, and failures on the workflow".to_owned(),
            ),
        }),
        Item::Pattern(pattern) => Some(Diagnostic {
            related: Vec::new(),
            span: pattern.span,
            message: "nested pattern declarations are not supported in pattern bodies".to_owned(),
            suggestion: Some("declare reusable patterns at source top level".to_owned()),
        }),
        // A recursive nested apply was already rejected with the precise
        // graph.unbounded_pattern_recursion diagnostic by detect_pattern_recursion;
        // don't also emit the generic "not supported yet" message for it.
        Item::Apply(apply) if !recursive_patterns.contains(&apply.pattern.name) => Some(Diagnostic {
            related: Vec::new(),
            span: apply.span,
            message: "pattern applications inside pattern bodies are not supported yet".to_owned(),
            suggestion: Some(
                "apply patterns from workflow bodies only in this implementation slice".to_owned(),
            ),
        }),
        // Objective intent is top-level: a gauge binds a judge to this
        // program's sites and a campaign partitions this program's gauge
        // vector — neither is a reusable template fragment.
        Item::Gauge(gauge) => Some(Diagnostic {
            related: Vec::new(),
            span: gauge.span,
            message: "gauge declarations are not allowed in pattern bodies".to_owned(),
            suggestion: Some("declare gauges at source top level".to_owned()),
        }),
        Item::Campaign(campaign) => Some(Diagnostic {
            related: Vec::new(),
            span: campaign.span,
            message: "campaign declarations are not allowed in pattern bodies".to_owned(),
            suggestion: Some("declare campaigns at source top level".to_owned()),
        }),
        Item::Mark(mark) => Some(Diagnostic {
            related: Vec::new(),
            span: mark.span,
            message: "mark declarations are not allowed in pattern bodies".to_owned(),
            suggestion: Some("declare marks at source top level".to_owned()),
        }),
        Item::Rule(rule) => pattern_rule_terminal_span(rule).map(|span| Diagnostic {
            related: Vec::new(),
            span,
            message: format!(
                "rule `{}` in a pattern body cannot reach a workflow terminal (`complete`/`fail`)",
                rule.name.name
            ),
            suggestion: Some(
                "record a fact in the pattern rule and let a workflow rule decide the terminal outcome"
                    .to_owned(),
            ),
        }),
        _ => None,
    }
}

/// Locate the first workflow-terminal statement (`complete`/`fail`) in a
/// pattern rule body, returning its source span for diagnostics.
fn pattern_rule_terminal_span(rule: &RuleDecl) -> Option<SourceSpan> {
    let mut offset = 0usize;
    for line in rule.body.text.split_inclusive('\n') {
        let trimmed_start = line.trim_start();
        let leading = line.len() - trimmed_start.len();
        let statement = trimmed_start.trim_end();
        if is_pattern_terminal_statement(statement) {
            let start = rule.body.span.start + offset + leading;
            return Some(SourceSpan {
                start,
                end: start + statement.len(),
            });
        }
        offset += line.len();
    }
    None
}

/// A trimmed body line begins a workflow terminal iff it starts with the
/// `complete` or `fail` keyword followed by whitespace, `{`, or end of line.
fn is_pattern_terminal_statement(line: &str) -> bool {
    for keyword in ["complete", "fail"] {
        if let Some(rest) = line.strip_prefix(keyword) {
            if rest.is_empty() || rest.starts_with('{') || rest.starts_with(char::is_whitespace) {
                return true;
            }
        }
    }
    false
}

fn expand_pattern_item(
    item: Item,
    alias: &str,
    type_substitutions: &BTreeMap<String, TypeSyntax>,
    value_substitutions: &BTreeMap<String, String>,
    local_names: &BTreeMap<String, String>,
) -> Option<(String, Item)> {
    match item {
        Item::Include(include) => Some((
            format!("include:{}", include.path.value),
            Item::Include(include),
        )),
        Item::Use(use_decl) => Some((format!("use:{}", use_decl.name.value), Item::Use(use_decl))),
        Item::Tracker(queue) => {
            Some((format!("tracker:{}", queue.name.name), Item::Tracker(queue)))
        }
        Item::Stream(stream) => {
            Some((format!("stream:{}", stream.name.name), Item::Stream(stream)))
        }
        Item::Channel(channel) => Some((
            format!("channel:{}", channel.name.name),
            Item::Channel(channel),
        )),
        Item::Credential(credential) => Some((
            format!("credential:{}", credential.name.name),
            Item::Credential(credential),
        )),
        // Gauges, campaigns, and marks are rejected from pattern bodies by
        // `pattern_body_admission` (objective intent and cut points are
        // top-level); there is deliberately no expansion path for them.
        Item::Gauge(_) | Item::Campaign(_) | Item::Mark(_) => None,
        Item::FileStore(file_store) => Some((
            format!("file-store:{}", file_store.name.name),
            Item::FileStore(file_store),
        )),
        Item::MemoryPool(pool) => Some((
            format!("memory-pool:{}", pool.name.name),
            Item::MemoryPool(pool),
        )),
        Item::Event(event) => Some((format!("event:{}", event.name), Item::Event(event))),
        Item::Source(source) => {
            Some((format!("source:{}", source.name.name), Item::Source(source)))
        }
        Item::Test(test) => Some((format!("test:{}", test.name.value), Item::Test(test))),
        Item::Lease(lease) => Some((format!("lease:{}", lease.name.name), Item::Lease(lease))),
        Item::Ledger(ledger) => {
            Some((format!("ledger:{}", ledger.name.name), Item::Ledger(ledger)))
        }
        Item::Counter(counter) => Some((
            format!("counter:{}", counter.name.name),
            Item::Counter(counter),
        )),
        Item::Action(action) => {
            Some((format!("action:{}", action.name.name), Item::Action(action)))
        }
        Item::Harness(mut harness) => {
            let name = rename_ident(harness.name, alias, local_names);
            let generated = format!("harness:{}", name.name);
            harness.name = name;
            Some((generated, Item::Harness(harness)))
        }
        // Forbidden constructs are rejected up front by `pattern_body_admission`
        // (the explicit allow-list gate), so these arms are unreachable in
        // practice; they stay defensive and simply drop the item.
        Item::WorkflowContract(_) | Item::Pattern(_) | Item::Apply(_) => None,
        Item::Agent(mut agent) => {
            let name = rename_ident(agent.name, alias, local_names);
            let generated = format!("agent:{}", name.name);
            agent.name = name;
            if let Some(harness) = agent.harness {
                agent.harness = Some(Ident {
                    name: local_names
                        .get(&harness.name)
                        .cloned()
                        .unwrap_or(harness.name),
                    span: harness.span,
                });
            }
            Some((generated, Item::Agent(agent)))
        }
        Item::Enum(mut enum_decl) => {
            let name = rename_ident(enum_decl.name, alias, local_names);
            let generated = format!("enum:{}", name.name);
            enum_decl.name = name;
            Some((generated, Item::Enum(enum_decl)))
        }
        Item::Class(mut class_decl) => {
            let name = rename_ident(class_decl.name, alias, local_names);
            let generated = format!("class:{}", name.name);
            class_decl.name = name;
            for field in &mut class_decl.fields {
                field.ty =
                    substitute_pattern_type(field.ty.clone(), type_substitutions, local_names);
            }
            Some((generated, Item::Class(class_decl)))
        }
        Item::Table(mut table) => {
            let name = rename_ident(table.name, alias, local_names);
            let generated = format!("table:{}", name.name);
            table.name = name;
            for row in &mut table.rows {
                row.body.text = substitute_pattern_text(
                    &row.body.text,
                    type_substitutions,
                    value_substitutions,
                    local_names,
                );
            }
            Some((generated, Item::Table(table)))
        }
        Item::Coerce(mut coerce) => {
            let name = rename_ident(coerce.name, alias, local_names);
            let generated = format!("coerce:{}", name.name);
            coerce.name = name;
            for param in &mut coerce.params {
                param.ty =
                    substitute_pattern_type(param.ty.clone(), type_substitutions, local_names);
            }
            coerce.output =
                substitute_pattern_type(coerce.output.clone(), type_substitutions, local_names);
            coerce.body.text = substitute_pattern_text(
                &coerce.body.text,
                type_substitutions,
                value_substitutions,
                local_names,
            );
            Some((generated, Item::Coerce(coerce)))
        }
        Item::Assert(mut assertion) => {
            assertion.expr = substitute_pattern_text(
                &assertion.expr,
                type_substitutions,
                value_substitutions,
                local_names,
            );
            Some((format!("assert:{alias}"), Item::Assert(assertion)))
        }
        Item::Rule(mut rule) => {
            let name = rename_ident(rule.name, alias, local_names);
            let generated = format!("rule:{}", name.name);
            rule.name = name;
            for when in &mut rule.whens {
                when.text = substitute_pattern_text(
                    &when.text,
                    type_substitutions,
                    value_substitutions,
                    local_names,
                );
            }
            rule.body.text = substitute_pattern_text(
                &rule.body.text,
                type_substitutions,
                value_substitutions,
                local_names,
            );
            Some((generated, Item::Rule(rule)))
        }
    }
}

fn rename_ident(ident: Ident, alias: &str, local_names: &BTreeMap<String, String>) -> Ident {
    Ident {
        name: local_names
            .get(&ident.name)
            .cloned()
            .unwrap_or_else(|| generated_pattern_name(alias, &ident.name)),
        span: ident.span,
    }
}

fn substitute_pattern_type(
    ty: TypeSyntax,
    type_substitutions: &BTreeMap<String, TypeSyntax>,
    local_names: &BTreeMap<String, String>,
) -> TypeSyntax {
    match ty {
        TypeSyntax::Ref { name } => {
            if let Some(replacement) = type_substitutions.get(&name.name) {
                return replacement.clone();
            }
            TypeSyntax::Ref {
                name: Ident {
                    name: local_names.get(&name.name).cloned().unwrap_or(name.name),
                    span: name.span,
                },
            }
        }
        TypeSyntax::AgentRef { agents, span } => TypeSyntax::AgentRef {
            agents: agents
                .into_iter()
                .map(|agent| Ident {
                    name: local_names.get(&agent.name).cloned().unwrap_or(agent.name),
                    span: agent.span,
                })
                .collect(),
            span,
        },
        TypeSyntax::Optional { inner, span } => TypeSyntax::Optional {
            inner: Box::new(substitute_pattern_type(
                *inner,
                type_substitutions,
                local_names,
            )),
            span,
        },
        TypeSyntax::Array { inner, span } => TypeSyntax::Array {
            inner: Box::new(substitute_pattern_type(
                *inner,
                type_substitutions,
                local_names,
            )),
            span,
        },
        TypeSyntax::Map { inner, span } => TypeSyntax::Map {
            inner: Box::new(substitute_pattern_type(
                *inner,
                type_substitutions,
                local_names,
            )),
            span,
        },
        TypeSyntax::Union { variants, span } => TypeSyntax::Union {
            variants: variants
                .into_iter()
                .map(|variant| substitute_pattern_type(variant, type_substitutions, local_names))
                .collect(),
            span,
        },
        other => other,
    }
}

/// Substitute a pattern's type parameters, hygienic local names, and value
/// arguments through an item's source text in ONE pass.
///
/// Single-pass is what makes the substitution hygienic. Running one
/// whole-string replacement per map over a shared accumulator — as this did —
/// let each pass rescan text the previous passes had inserted. A type argument
/// was therefore capturable by a pattern-local declaration: `apply Review<Task>`
/// against a pattern declaring its own `Task` had the argument rewritten to the
/// pattern's gensym, so the rule matched the pattern's local class instead of
/// the caller's type. Value-argument keys are unvalidated identifiers taken
/// from the apply body and ran last, so they could rewrite whatever the type
/// pass had just produced. Both failed closed on downstream name resolution,
/// but only after handing the author a diagnostic naming an identifier they
/// never wrote.
///
/// Each identifier token is now resolved exactly once, against the maps in the
/// priority order the multi-pass form implied, and its replacement is emitted
/// without being re-examined. Token boundaries are unchanged: a maximal run of
/// identifier characters is precisely what the old boundary test accepted.
fn substitute_pattern_text(
    text: &str,
    type_substitutions: &BTreeMap<String, TypeSyntax>,
    value_substitutions: &BTreeMap<String, String>,
    local_names: &BTreeMap<String, String>,
) -> String {
    let mut output = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find(is_identifier_char) {
        output.push_str(&rest[..start]);
        let after = &rest[start..];
        let end = after
            .find(|ch| !is_identifier_char(ch))
            .unwrap_or(after.len());
        let token = &after[..end];
        match resolve_pattern_token(token, type_substitutions, value_substitutions, local_names) {
            Some(replacement) => output.push_str(&replacement),
            None => output.push_str(token),
        }
        rest = &after[end..];
    }
    output.push_str(rest);
    output
}

/// Resolve one identifier token against the substitution maps, in the priority
/// order the multi-pass form implied: a type parameter first, then a
/// pattern-local declaration, then a value argument. A token naming none of
/// them is not substituted.
fn resolve_pattern_token(
    token: &str,
    type_substitutions: &BTreeMap<String, TypeSyntax>,
    value_substitutions: &BTreeMap<String, String>,
    local_names: &BTreeMap<String, String>,
) -> Option<String> {
    if let Some(ty) = type_substitutions.get(token) {
        return Some(ty.to_source());
    }
    if let Some(local) = local_names.get(token) {
        return Some(local.clone());
    }
    value_substitutions.get(token).cloned()
}

fn is_identifier_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'
}

fn collect_projection_reads(expr: &Expr) -> Vec<IrProjectionRead> {
    let mut reads = Vec::new();
    collect_projection_reads_into(expr, &mut reads);
    reads
}

fn collect_projection_reads_into(expr: &Expr, reads: &mut Vec<IrProjectionRead>) {
    match expr {
        Expr::Literal(_) | Expr::Path(_) => {}
        Expr::Index { target, key } => {
            collect_projection_reads_into(target, reads);
            collect_projection_reads_into(key, reads);
        }
        Expr::Array(items) => {
            for item in items {
                collect_projection_reads_into(item, reads);
            }
        }
        Expr::Object(fields) => {
            for field in fields {
                collect_projection_reads_into(&field.value, reads);
            }
        }
        Expr::Unary { expr, .. } => collect_projection_reads_into(expr, reads),
        Expr::Binary { left, right, .. } => {
            collect_projection_reads_into(left, reads);
            collect_projection_reads_into(right, reads);
        }
        Expr::Call { args, .. } => {
            for arg in args {
                collect_projection_reads_into(arg, reads);
            }
        }
        Expr::Query { kind, head, guard } => {
            reads.push(IrProjectionRead {
                kind: *kind,
                head: head.clone(),
                guard: guard.as_ref().map(|guard| guard.to_snapshot()),
            });
            if let Some(guard) = guard {
                collect_projection_reads_into(guard, reads);
            }
        }
    }
}

fn sort_projection_reads(reads: &mut Vec<IrProjectionRead>) {
    reads.sort_by_key(IrProjectionRead::to_snapshot);
    reads.dedup();
}

fn collect_schema_names(program: &Program, diagnostics: &mut Vec<Diagnostic>) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    // Track the first declaration span per name so a duplicate can point back to
    // it as related information ("first declared here").
    let mut first_spans: BTreeMap<String, SourceSpan> = BTreeMap::new();
    for item in &program.items {
        let name = match item {
            Item::Enum(enum_decl) => &enum_decl.name,
            Item::Class(class_decl) => &class_decl.name,
            _ => continue,
        };

        if !names.insert(name.name.clone()) {
            let mut diagnostic = Diagnostic {
                related: Vec::new(),
                span: name.span,
                message: format!("schema `{}` is declared more than once", name.name),
                suggestion: Some("rename one declaration or merge the schemas".to_owned()),
            };
            if let Some(first) = first_spans.get(&name.name) {
                diagnostic = diagnostic.with_related(*first, "first declared here");
            }
            diagnostics.push(diagnostic);
        } else {
            first_spans.insert(name.name.clone(), name.span);
        }
    }

    names
}

fn collect_harness_kinds(
    program: &Program,
    diagnostics: &mut Vec<Diagnostic>,
) -> BTreeMap<String, String> {
    let mut kinds: BTreeMap<String, String> = BTreeMap::new();
    for item in &program.items {
        let Item::Harness(harness) = item else {
            continue;
        };
        if kinds
            .insert(harness.name.name.clone(), harness.kind.name.clone())
            .is_some()
        {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: harness.name.span,
                message: format!("harness `{}` is declared more than once", harness.name.name),
                suggestion: Some(
                    "rename one harness declaration or merge the harness settings".to_owned(),
                ),
            });
        }
    }
    kinds
}

fn collect_agent_names(program: &Program, diagnostics: &mut Vec<Diagnostic>) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    for item in &program.items {
        let Item::Agent(agent) = item else {
            continue;
        };
        if !names.insert(agent.name.name.clone()) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: agent.name.span,
                message: format!("agent `{}` is declared more than once", agent.name.name),
                suggestion: Some("rename one agent declaration or merge the settings".to_owned()),
            });
        }
    }
    names
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct WorkflowContractNames {
    inputs: BTreeMap<String, TypeSyntax>,
    outputs: BTreeMap<String, TypeSyntax>,
    failures: BTreeMap<String, TypeSyntax>,
}

fn collect_workflow_contract_names(
    program: &Program,
    diagnostics: &mut Vec<Diagnostic>,
) -> WorkflowContractNames {
    let mut names = WorkflowContractNames::default();
    for item in &program.items {
        let Item::WorkflowContract(contract) = item else {
            continue;
        };
        let set = match contract.kind {
            WorkflowContractKind::Input => &mut names.inputs,
            WorkflowContractKind::Output => &mut names.outputs,
            WorkflowContractKind::Failure => &mut names.failures,
        };
        if set
            .insert(contract.name.name.clone(), contract.ty.clone())
            .is_some()
        {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: contract.name.span,
                message: format!(
                    "workflow declares {} `{}` more than once",
                    contract.kind.as_str(),
                    contract.name.name
                ),
                suggestion: Some("remove the duplicate workflow contract".to_owned()),
            });
        }
    }
    names
}

impl SemanticContext {
    fn from_program(
        program: &Program,
        workflow_inputs: BTreeMap<String, WorkflowInputSurface>,
    ) -> Self {
        let mut schemas = SchemaIndex::with_builtins();
        let mut agents = BTreeSet::new();
        let mut agent_capabilities = BTreeMap::new();
        let mut coerce_outputs = BTreeMap::new();
        let mut coerce_params = BTreeMap::new();
        let mut leases = BTreeSet::new();
        let mut ledgers = BTreeSet::new();
        let mut counters = BTreeSet::new();
        let mut channels = BTreeSet::new();
        let mut channel_providers = BTreeMap::new();
        let mut credentials = BTreeMap::new();
        let mut memory_pools = BTreeSet::new();

        for item in &program.items {
            schemas.insert_item(item);
            match item {
                Item::Agent(agent) => {
                    agents.insert(agent.name.name.clone());
                    let capabilities = agent
                        .fields
                        .iter()
                        .find_map(|field| match field {
                            AgentField::Capabilities(capabilities, _) => Some(
                                capabilities
                                    .iter()
                                    .map(|capability| capability.value.clone())
                                    .collect::<BTreeSet<_>>(),
                            ),
                            _ => None,
                        })
                        .unwrap_or_default();
                    agent_capabilities.insert(agent.name.name.clone(), capabilities);
                }
                Item::Coerce(coerce) => {
                    coerce_outputs.insert(coerce.name.name.clone(), coerce.output.clone());
                    coerce_params.insert(coerce.name.name.clone(), coerce.params.clone());
                }
                Item::Lease(lease) => {
                    leases.insert(lease.name.name.clone());
                }
                Item::Ledger(ledger) => {
                    ledgers.insert(ledger.name.name.clone());
                }
                Item::Counter(counter) => {
                    counters.insert(counter.name.name.clone());
                }
                Item::Channel(channel) => {
                    channels.insert(channel.name.name.clone());
                    channel_providers
                        .insert(channel.name.name.clone(), channel.provider.name.clone());
                }
                Item::Credential(credential) => {
                    credentials.insert(
                        credential.name.name.clone(),
                        credential.kind.name.replace('_', "-"),
                    );
                }
                Item::MemoryPool(pool) => {
                    memory_pools.insert(pool.name.name.clone());
                }
                _ => {}
            }
        }

        Self {
            workflow: program
                .workflow
                .as_ref()
                .map(|workflow| workflow.name.clone()),
            schemas,
            agents,
            agent_capabilities,
            coerce_outputs,
            coerce_params,
            workflow_inputs,
            leases,
            ledgers,
            counters,
            channels,
            channel_providers,
            credentials,
            memory_pools,
            regions: BTreeMap::new(),
        }
    }
}

fn collect_workflow_input_surfaces(program: &Program) -> BTreeMap<String, WorkflowInputSurface> {
    let mut surfaces = BTreeMap::new();
    let top_level_schemas = schema_index_for_items(&program.items);

    if let Some(workflow) = &program.workflow {
        let inputs = workflow_inputs_for_items(&program.items);
        surfaces.insert(
            workflow.name.clone(),
            WorkflowInputSurface {
                inputs,
                outputs: workflow_outputs_for_items(&program.items),
                failures: workflow_failures_for_items(&program.items),
                schemas: top_level_schemas.clone(),
                milestones: collect_milestone_declarations(&program.items),
            },
        );
    }

    for workflow in &program.workflows {
        let mut schemas = top_level_schemas.clone();
        schemas.merge(schema_index_for_items(&workflow.items));
        surfaces.insert(
            workflow.name.name.clone(),
            WorkflowInputSurface {
                inputs: workflow_inputs_for_items(&workflow.items),
                outputs: workflow_outputs_for_items(&workflow.items),
                failures: workflow_failures_for_items(&workflow.items),
                schemas,
                milestones: collect_milestone_declarations(&workflow.items),
            },
        );
    }

    surfaces
}

fn collect_shared_coordination_usage(program: &Program) -> Vec<IrSharedCoordinationUsage> {
    let global_shared = shared_coordination_declarations(&program.items);
    let mut usage: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();

    let mut record_workflow = |workflow_name: &str, local_items: &[Item]| {
        let mut shared = global_shared.clone();
        shared.extend(shared_coordination_declarations(local_items));
        if shared.is_empty() {
            return;
        }
        let principal = format!("workflow:local/{workflow_name}");
        for resource in coordination_resources_used_by_items(&program.items)
            .into_iter()
            .chain(coordination_resources_used_by_items(local_items))
        {
            if shared.contains(&resource) {
                usage.entry(resource).or_default().insert(principal.clone());
            }
        }
    };

    if let Some(workflow) = &program.workflow {
        record_workflow(&workflow.name, &[]);
    }
    for workflow in &program.workflows {
        record_workflow(&workflow.name.name, &workflow.items);
    }

    usage
        .into_iter()
        .map(|(resource, principals)| IrSharedCoordinationUsage {
            resource: format!("resource:{resource}"),
            workflow_principals: principals.into_iter().collect(),
        })
        .collect()
}

fn shared_coordination_declarations(items: &[Item]) -> BTreeSet<String> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Lease(lease) if lease.shared => Some(lease.name.name.clone()),
            Item::Ledger(ledger) if ledger.shared => Some(ledger.name.name.clone()),
            Item::Counter(counter) if counter.shared => Some(counter.name.name.clone()),
            _ => None,
        })
        .collect()
}

fn coordination_resources_used_by_items(items: &[Item]) -> BTreeSet<String> {
    let mut resources = BTreeSet::new();
    for item in items {
        let Item::Rule(rule) = item else {
            continue;
        };
        let (body, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
        collect_coordination_resources_from_statements(&body.statements, &mut resources);
    }
    resources
}

fn collect_coordination_resources_from_statements(
    statements: &[body::BodyStmt],
    resources: &mut BTreeSet<String>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => match &effect.kind {
                body::BodyEffectKind::LeaseAcquire { resource, .. } => {
                    resources.insert(resource.clone());
                }
                body::BodyEffectKind::LedgerAppend { ledger, .. } => {
                    resources.insert(ledger.clone());
                }
                body::BodyEffectKind::CounterConsume { counter, .. } => {
                    resources.insert(counter.clone());
                }
                _ => {}
            },
            body::BodyStmt::After(after) => {
                collect_coordination_resources_from_statements(&after.body, resources);
            }
            body::BodyStmt::Region(region) => {
                collect_coordination_resources_from_statements(&region.body, resources);
                collect_coordination_resources_from_statements(&region.lapse_body, resources);
            }
            body::BodyStmt::Case(case_stmt) => {
                for branch in &case_stmt.branches {
                    collect_coordination_resources_from_statements(&branch.body, resources);
                }
            }
            body::BodyStmt::Record(_)
            | body::BodyStmt::Done { .. }
            | body::BodyStmt::Terminal(_)
            | body::BodyStmt::Cancel { .. }
            | body::BodyStmt::Milestone { .. }
            | body::BodyStmt::Redact { .. } => {}
        }
    }
}

/// Scans a workflow's rule bodies for `emit milestone "<name>" [of <Class>]`
/// projections (Family C) and returns the name -> payload-class map (empty class
/// string for a bare milestone). The emit statement IS the declaration — the
/// declared milestone set is exactly what the workflow's rules can project, which
/// is what a parent's `after p reaches "<name>"` is validated against.
fn collect_milestone_declarations(items: &[Item]) -> BTreeMap<String, String> {
    let mut milestones = BTreeMap::new();
    for item in items {
        let Item::Rule(rule) = item else {
            continue;
        };
        for (name, class) in milestone_emissions_in_body(&rule.body.text) {
            milestones.entry(name).or_insert(class);
        }
    }
    milestones
}

/// Validates Family C milestone statements in a rule (spec/decision-records/
/// discriminated-families-design.md sections 6.4 / 7.3):
///   - child `emit milestone "<name>" of <Class>` — `<Class>` must be a declared
///     class (the payload the observing parent narrows into scope);
///   - parent `after <p> reaches "<name>"` — `<p>` must be a workflow-invoke
///     binding in this rule, and `<name>` must be a milestone that the invoked
///     child workflow actually declares (the reject-undeclared / terminal-only
///     observation invariant: a parent cannot observe a state the child never
///     projects).
fn validate_milestone_statements(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    // Child side: every `emit milestone "<name>" of <Class>` payload class must
    // exist.
    for (name, class) in milestone_emissions_in_body(&rule.body.text) {
        if !class.is_empty() && !semantic.schemas.class_exists(&class) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` emits milestone `{name}` with unknown payload class `{class}`",
                    rule.name.name
                ),
                suggestion: Some(format!("declare `class {class}` before projecting it")),
            });
        }
    }

    // Parent side: every `after <p> reaches "<name>"` must name a milestone the
    // invoked child declares.
    for (binding, milestone) in milestone_reaches_in_body(&rule.body.text) {
        let Some(workflow) = invoke_binding_workflow(rule, &binding) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` has `after {binding} reaches \"{milestone}\"` for `{binding}`, which is not a workflow-invoke binding in this rule",
                    rule.name.name
                ),
                suggestion: Some(
                    "`reaches` observes a child workflow milestone; bind the child with `invoke W { ... } as <binding>` first"
                        .to_owned(),
                ),
            });
            continue;
        };
        let declared = semantic
            .workflow_inputs
            .get(&workflow)
            .map(|surface| surface.milestones.contains_key(&milestone))
            .unwrap_or(false);
        if !declared {
            let available = semantic
                .workflow_inputs
                .get(&workflow)
                .map(|surface| {
                    surface
                        .milestones
                        .keys()
                        .map(|name| format!("\"{name}\""))
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default();
            let suggestion = if available.is_empty() {
                format!("workflow `{workflow}` declares no milestones; add `emit milestone \"{milestone}\" ...` to it")
            } else {
                format!("workflow `{workflow}` declares: {available}")
            };
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` reaches milestone `{milestone}` that workflow `{workflow}` does not declare",
                    rule.name.name
                ),
                suggestion: Some(suggestion),
            });
        }
    }
}

/// Parses `after <binding> reaches "<name>"` headers out of a rule body's text,
/// returning (binding, milestone-name) pairs. Mirrors `milestone_emissions_in_body`.
fn milestone_reaches_in_body(body: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for raw in body.lines() {
        let trimmed = raw.trim();
        let Some(rest) = trimmed.strip_prefix("after ") else {
            continue;
        };
        let mut words = rest.split_whitespace();
        let Some(binding) = words.next() else {
            continue;
        };
        if words.next() != Some("reaches") {
            continue;
        }
        let Some(quoted) = words.next() else {
            continue;
        };
        if !(quoted.starts_with('"') && quoted.ends_with('"') && quoted.len() >= 2) {
            continue;
        }
        out.push((binding.to_owned(), quoted.trim_matches('"').to_owned()));
    }
    out
}

/// Maps an `invoke <Workflow> { ... } as <binding>` binding to the invoked
/// workflow name within a single rule, so a sibling `after <binding> reaches`
/// can find the child workflow whose milestones it observes.
fn invoke_binding_workflow(rule: &RuleDecl, binding: &str) -> Option<String> {
    for statement in workflow_invoke_statements(&rule.body.text) {
        let (target, _) = invoke_statement_parts(&statement)?;
        if let Some(as_binding) = binding_after_as(&statement) {
            if as_binding == binding {
                return Some(target.to_owned());
            }
        }
    }
    None
}

/// Resolves the payload class of a child milestone for `after <binding> reaches
/// "<milestone>"`: follow `binding` to its invoked workflow, then look up the
/// milestone in that workflow's declared set. Returns the owning workflow with
/// the class, because the class may be declared inside that child and so
/// resolves in the child's index, not this workflow's (`SchemaScopes`).
/// `Some((_, ""))` means the milestone is declared but payload-less; `None`
/// means undeclared (reject) or unresolvable.
fn milestone_payload_class(
    rule: &RuleDecl,
    binding: &str,
    milestone: &str,
    semantic: &SemanticContext,
) -> Option<(String, String)> {
    let workflow = invoke_binding_workflow(rule, binding)?;
    let surface = semantic.workflow_inputs.get(&workflow)?;
    let class = surface.milestones.get(milestone).cloned()?;
    Some((workflow, class))
}

/// Resolves the OUTPUT-contract class of the child workflow a `succeeds`/`completes`
/// invoke binding observes, so `after <binding> succeeds as r` can type `r` and
/// check `r.<field>`. `None` (leave the binding opaque, unchanged) when: the binding
/// is not an invoke; the child declares zero or several outputs (which output the
/// child completes is not statically known); or the sole output is a scalar (no
/// fields).
///
/// The class is resolved in the CHILD's index and returned with its owning
/// workflow. A child that declares its output class workflow-locally — the
/// ordinary, encapsulated spelling — used to fall through this function and leave
/// `r.<field>` unchecked; the class still never becomes nameable in the parent,
/// only resolvable for reads off this binding (`SchemaScopes`).
fn invoke_output_class(
    rule: &RuleDecl,
    binding: &str,
    semantic: &SemanticContext,
) -> Option<(String, String)> {
    let workflow = invoke_binding_workflow(rule, binding)?;
    let surface = semantic.workflow_inputs.get(&workflow)?;
    if surface.outputs.len() != 1 {
        return None;
    }
    match surface.outputs.values().next()? {
        TypeSyntax::Ref { name } if surface.schemas.class_exists(&name.name) => {
            Some((workflow, name.name.clone()))
        }
        _ => None,
    }
}

/// Resolves the FAILURE-contract class of the child workflow a `fails` invoke
/// binding observes, so `after <binding> fails as f` can type `f` to the child's
/// declared failure shape (and check `f.<field>`) instead of the generic DR-0032
/// `TerminalFailed` base. `None` (fall back to the base) when: the binding is not
/// an invoke; the child declares zero or several failures (which failure the child
/// raised is not statically known); or the sole failure is a scalar (no fields).
/// Anything else keeps the base, which every failure structurally satisfies.
///
/// As with `invoke_output_class`, the class is resolved in the CHILD's index and
/// returned with its owning workflow, so a child that declares its failure class
/// workflow-locally is typed rather than silently left on the base.
fn invoke_failure_class(
    rule: &RuleDecl,
    binding: &str,
    semantic: &SemanticContext,
) -> Option<(String, String)> {
    let workflow = invoke_binding_workflow(rule, binding)?;
    let surface = semantic.workflow_inputs.get(&workflow)?;
    if surface.failures.len() != 1 {
        return None;
    }
    match surface.failures.values().next()? {
        TypeSyntax::Ref { name } if surface.schemas.class_exists(&name.name) => {
            Some((workflow, name.name.clone()))
        }
        _ => None,
    }
}

/// Parses `emit milestone "<name>" [of <Class>]` headers out of a rule body's
/// text, returning (name, class) pairs (class is empty for a bare milestone).
/// Text-based to mirror the other body scanners (`workflow_invoke_statements`)
/// and stay independent of flow-vs-rule body provenance.
fn milestone_emissions_in_body(body: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for raw in body.lines() {
        let trimmed = raw.trim();
        let Some(rest) = trimmed.strip_prefix("emit milestone ") else {
            continue;
        };
        // The name is a quoted string literal; take the text between the first
        // pair of quotes.
        let rest = rest.trim_start();
        if !rest.starts_with('"') {
            continue;
        }
        let Some(close) = rest[1..].find('"') else {
            continue;
        };
        let name = rest[1..=close].to_owned();
        let after_name = rest[close + 2..].trim_start();
        let class = after_name
            .strip_prefix("of ")
            .map(|tail| {
                tail.trim_start()
                    .split(|c: char| c.is_whitespace() || c == '{')
                    .next()
                    .unwrap_or("")
                    .to_owned()
            })
            .unwrap_or_default();
        out.push((name, class));
    }
    out
}

fn schema_index_for_items(items: &[Item]) -> SchemaIndex {
    let mut schemas = SchemaIndex::with_builtins();
    for item in items {
        schemas.insert_item(item);
    }
    schemas
}

fn workflow_inputs_for_items(items: &[Item]) -> BTreeMap<String, TypeSyntax> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::WorkflowContract(contract) if contract.kind == WorkflowContractKind::Input => {
                Some((contract.name.name.clone(), contract.ty.clone()))
            }
            _ => None,
        })
        .collect()
}

fn workflow_outputs_for_items(items: &[Item]) -> BTreeMap<String, TypeSyntax> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::WorkflowContract(contract) if contract.kind == WorkflowContractKind::Output => {
                Some((contract.name.name.clone(), contract.ty.clone()))
            }
            _ => None,
        })
        .collect()
}

fn workflow_failures_for_items(items: &[Item]) -> BTreeMap<String, TypeSyntax> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::WorkflowContract(contract) if contract.kind == WorkflowContractKind::Failure => {
                Some((contract.name.name.clone(), contract.ty.clone()))
            }
            _ => None,
        })
        .collect()
}

impl SchemaIndex {
    fn with_builtins() -> Self {
        let mut index = Self::default();
        index.insert_class(
            "AgentTurn",
            [
                ("id", string_ty()),
                ("summary", string_ty()),
                ("agent", string_ty()),
                ("provider", string_ty()),
                ("status", string_ty()),
                ("run_id", string_ty()),
                ("effect_id", string_ty()),
            ],
        );
        index.insert_class(
            "WorkItem",
            [
                ("id", string_ty()),
                ("title", string_ty()),
                ("body", string_ty()),
                ("queue", string_ty()),
                ("status", string_ty()),
                ("labels", array_ty(string_ty())),
            ],
        );
        // std.vcs observer schemas (DR-0052 grammar pass): the readiness
        // sugar's typed bindings. Observer-origin — the mediator emits
        // them; user rules eliminate, never construct.
        index.insert_class(
            "VcsChange",
            [
                ("branch", string_ty()),
                ("cut", string_ty()),
                ("path", string_ty()),
                ("origin", string_ty()),
                ("by", string_ty()),
                ("intent", string_ty()),
                ("at", string_ty()),
            ],
        );
        index.insert_class(
            "VcsContention",
            [
                ("branch", string_ty()),
                ("with", string_ty()),
                ("stream", string_ty()),
                ("slice", array_ty(string_ty())),
                ("at", string_ty()),
            ],
        );
        index.insert_class(
            "VcsPromotion",
            [
                ("branch", string_ty()),
                ("stream", string_ty()),
                ("cut", string_ty()),
                ("at", string_ty()),
            ],
        );
        index.insert_class(
            "VcsStall",
            [
                ("branch", string_ty()),
                ("stream", string_ty()),
                ("boundary", string_ty()),
                ("paths", array_ty(string_ty())),
                ("at", string_ty()),
            ],
        );
        index.insert_class(
            "Evidence",
            [
                ("title", string_ty()),
                ("path", string_ty()),
                ("summary", string_ty()),
            ],
        );
        index.insert_class(
            "TerminalFailed",
            [
                ("reason", string_ty()),
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
                // DR-0032: `kind` names the failing effect — the `EffectError` base
                // field that lets a future runtime union dispatch and that
                // telemetry reads. Static narrowing does not require it.
                ("kind", string_ty()),
            ],
        );
        // DR-0032 P3 (per-kind failure extras, DQ-2 static narrowing): each
        // kind's failure schema extends the base with the ruled v1 extras —
        // exec `exit_code`; schema.coerce `error_class` + optional
        // `http_status`; agent.tell `error_class`. The extras are reachable
        // ONLY when the binding's effect kind matches (the `fails`-arm
        // narrowing below), so each addition is additive by construction.
        index.insert_class(
            "TerminalFailedExec",
            [
                ("reason", string_ty()),
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
                ("kind", string_ty()),
                // Absent when the process could not be spawned (the emitters
                // only set it for a run that actually started) — the docs
                // said so; the type now agrees.
                ("exit_code", optional_ty(int_ty())),
            ],
        );
        index.insert_class(
            "TerminalFailedCoerce",
            [
                ("reason", string_ty()),
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
                ("kind", string_ty()),
                ("error_class", string_ty()),
                ("http_status", optional_ty(int_ty())),
            ],
        );
        index.insert_class(
            "TerminalFailedTell",
            [
                ("reason", string_ty()),
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
                ("kind", string_ty()),
                ("error_class", string_ty()),
            ],
        );
        index.insert_class(
            "TerminalTimedOut",
            [
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
            ],
        );
        index.insert_class(
            "TerminalCancelled",
            [
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
            ],
        );
        // The `after x completes as o` envelope: the runtime delivers the
        // terminal UNION {tag, status, summary, effect_id, run_id} (plus the
        // dynamically-shaped value/error read via `case o { Completed as v =>
        // … }`). Typing the alias as the effect's SUCCESS schema — the old
        // behavior — approved field reads that were null at runtime on every
        // non-success terminal.
        index.insert_class(
            "TerminalOutcome",
            [
                ("tag", string_ty()),
                ("status", string_ty()),
                ("summary", string_ty()),
                ("effect_id", string_ty()),
                ("run_id", string_ty()),
            ],
        );
        // The generic inbound messaging envelope (spec/messaging.md): a
        // `when message from <channel> as msg` binding sees a `Message`, never a
        // domain type. Structured sub-payloads (sender_claims, interaction,
        // correlation) are JSON-serialized strings here; provider-specific
        // payloads live in bounded evidence / `raw_ref`, not as untyped facts.
        index.insert_class(
            "Message",
            [
                ("message_id", string_ty()),
                ("channel", string_ty()),
                ("provider", string_ty()),
                ("received_at", string_ty()),
                ("sender", string_ty()),
                ("sender_claims", string_ty()),
                ("thread_id", string_ty()),
                ("text", string_ty()),
                ("markdown", string_ty()),
                ("attachments", array_ty(string_ty())),
                ("interaction", string_ty()),
                ("raw_ref", string_ty()),
                ("correlation", string_ty()),
            ],
        );
        // The typed receipt a `send via <channel> { ... } as r` binding sees
        // (std.messaging; the `messaging.send` contract's output schema —
        // spec/std-messaging.md "MessageSendReceipt"). Every provider returns
        // the full shape; correlation fields the provider cannot report
        // (`provider_message_id`, `thread_id`, `destination`) are empty
        // strings, and `accepted_at` is the provider-acknowledged instant.
        // Failure is NOT a receipt: it settles `capability.call.failed` with
        // the DR-0032 EffectError base and routes to `fails as`. `status` is
        // `accepted` in v1 (`delivered` is reserved for providers whose report
        // includes it; none exists yet).
        index.insert_class(
            "MessageSendReceipt",
            [
                ("message_id", string_ty()),
                ("channel", string_ty()),
                ("provider", string_ty()),
                ("status", string_ty()),
                ("provider_message_id", string_ty()),
                ("thread_id", string_ty()),
                ("destination", string_ty()),
                ("accepted_at", string_ty()),
            ],
        );
        index
    }

    fn insert_class<const N: usize>(&mut self, name: &str, fields: [(&str, TypeSyntax); N]) {
        self.classes.insert(
            name.to_owned(),
            fields
                .into_iter()
                .map(|(field, ty)| (field.to_owned(), ty))
                .collect(),
        );
    }

    fn insert_item(&mut self, item: &Item) {
        match item {
            Item::Enum(enum_decl) => {
                self.enums.insert(
                    enum_decl.name.name.clone(),
                    enum_decl
                        .variants
                        .iter()
                        .map(|variant| variant.name.name.clone())
                        .collect(),
                );
                // Data-carrying variants are visible as generated
                // `<Enum>.<Variant>` classes (spec/sum-types.md), so case
                // bindings type-check field access against them.
                for variant in &enum_decl.variants {
                    if variant.fields.is_empty() {
                        continue;
                    }
                    let mut fields = BTreeMap::new();
                    fields.insert(
                        "variant".to_owned(),
                        TypeSyntax::LiteralString {
                            value: variant.name.name.clone(),
                            span: variant.name.span,
                        },
                    );
                    for field in &variant.fields {
                        fields.insert(field.name.name.clone(), field.ty.clone());
                    }
                    self.classes.insert(
                        format!("{}.{}", enum_decl.name.name, variant.name.name),
                        fields,
                    );
                }
            }
            Item::Class(class_decl) => {
                self.classes.insert(
                    class_decl.name.name.clone(),
                    class_decl
                        .fields
                        .iter()
                        .map(|field| (field.name.name.clone(), field.ty.clone()))
                        .collect(),
                );
                self.insert_presence(&class_decl.name.name, &class_decl.fields);
            }
            Item::Event(event) => {
                self.events.insert(event.name.clone());
                // The payload schema is indexed under the dotted signal name,
                // unreachable from user class declarations, so bare `when
                // <signal> as x` bindings type-check field access.
                self.classes.insert(
                    event.name.clone(),
                    event
                        .fields
                        .iter()
                        .map(|field| (field.name.name.clone(), field.ty.clone()))
                        .collect(),
                );
                self.insert_presence(&event.name, &event.fields);
            }
            _ => {}
        }
    }

    /// Record Family B presence conditions for a schema's fields (if any).
    fn insert_presence(&mut self, schema: &str, fields: &[ClassField]) {
        let conditions: BTreeMap<String, (String, String)> = fields
            .iter()
            .filter_map(|field| {
                field
                    .presence_condition
                    .clone()
                    .map(|condition| (field.name.name.clone(), condition))
            })
            .collect();
        if !conditions.is_empty() {
            self.presence.insert(schema.to_owned(), conditions);
        }
    }

    /// The presence condition `(discriminant, literal)` for a schema field, if any.
    fn field_presence(&self, schema: &str, field: &str) -> Option<&(String, String)> {
        self.presence
            .get(schema)
            .and_then(|fields| fields.get(field))
    }

    fn merge(&mut self, other: SchemaIndex) {
        self.classes.extend(other.classes);
        self.enums.extend(other.enums);
        self.presence.extend(other.presence);
    }

    fn class_exists(&self, name: &str) -> bool {
        self.classes.contains_key(name)
    }

    fn resolve_field_path(&self, root_schema: &str, path: &[String]) -> Result<TypeSyntax, String> {
        // Dotted runtime fact names (general `when fact <name>` matches) are
        // untyped — unless a declared `event` (or generated `<Enum>.<Variant>`
        // class) indexes a payload schema under the dotted name, in which
        // case field paths are statically validated against it.
        if root_schema.contains('.') && !self.classes.contains_key(root_schema) {
            return Ok(TypeSyntax::Ref {
                name: Ident {
                    name: root_schema.to_owned(),
                    span: zero_span(),
                },
            });
        }
        let mut schema = root_schema.to_owned();
        let mut current = TypeSyntax::Ref {
            name: Ident {
                name: schema.clone(),
                span: zero_span(),
            },
        };

        for field in path {
            let Some(fields) = self.classes.get(&schema) else {
                return Err(format!("schema `{schema}` has no declared fields"));
            };
            let Some(field_ty) = fields.get(field) else {
                return Err(format!("schema `{schema}` has no field `{field}`"));
            };

            current = field_ty.clone();
            match schema_name_for_path(&current) {
                Some(next_schema) => schema = next_schema,
                None if field != path.last().expect("path is non-empty") => {
                    return Err(format!("field `{field}` is not a schema value"));
                }
                None => {}
            }
        }

        Ok(current)
    }
}

fn zero_span() -> SourceSpan {
    SourceSpan { start: 0, end: 0 }
}

fn string_ty() -> TypeSyntax {
    TypeSyntax::Primitive {
        name: "string".to_owned(),
        span: zero_span(),
    }
}

fn int_ty() -> TypeSyntax {
    TypeSyntax::Primitive {
        name: "int".to_owned(),
        span: zero_span(),
    }
}

fn optional_ty(inner: TypeSyntax) -> TypeSyntax {
    TypeSyntax::Optional {
        inner: Box::new(inner),
        span: zero_span(),
    }
}

fn array_ty(inner: TypeSyntax) -> TypeSyntax {
    TypeSyntax::Array {
        inner: Box::new(inner),
        span: zero_span(),
    }
}

fn schema_name_for_path(ty: &TypeSyntax) -> Option<String> {
    match ty {
        TypeSyntax::Ref { name } => Some(name.name.clone()),
        TypeSyntax::Optional { inner, .. } => schema_name_for_path(inner),
        _ => None,
    }
}

/// The complete standard-package universe (the 13 std packages of the
/// standard-package campaign). `use std.<name>` outside this list is a check
/// error: std resolution is a built-in registry, so an unknown name can never
/// resolve later — a typo'd `use std.coercon` would otherwise silently import
/// nothing (and downstream missing-import bite is advisory only).
pub const STD_PACKAGE_IDS: &[&str] = &[
    "std.agent",
    "std.vcs",
    "std.coercion",
    "std.coord",
    "std.files",
    "std.human",
    "std.ingress",
    "std.memory",
    "std.messaging",
    "std.script",
    "std.telemetry",
    "std.time",
    "std.tracker",
    "std.workflow",
];

/// Cross-declaration stream checks (DR-0052 Decision 5, run after all
/// items lower so agent order does not matter): every member names a
/// declared agent, and membership is single-valued — one stream per
/// agent, so the sync topology stays a tree.
fn validate_streams(ir: &IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    let mut memberships: Vec<(&str, &str)> = Vec::new(); // (agent, stream)
    for stream in &ir.streams {
        for (member, span) in stream.members.iter().zip(&stream.member_spans) {
            if !ir.agents.iter().any(|agent| agent.name == *member) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: *span,
                    message: format!(
                        "stream `{}` member `{}` is not a declared agent",
                        stream.name, member
                    ),
                    suggestion: Some(
                        "stream members are agent declarations; declare the agent \
                         or remove it from the stream"
                            .to_owned(),
                    ),
                });
                continue;
            }
            if let Some((_, holder)) = memberships.iter().find(|(agent, _)| agent == member) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: *span,
                    message: format!("agent `{member}` is already a member of stream `{holder}`",),
                    suggestion: Some(
                        "membership is single-valued (the sync topology stays a \
                         tree): an agent homes to exactly one stream"
                            .to_owned(),
                    ),
                });
                continue;
            }
            memberships.push((member, &stream.name));
        }
    }
    // `on stream <name>` on a tell must name a declared stream — the
    // per-turn exception cannot invent topology.
    for rule in &ir.rules {
        for effect in &rule.metadata.effects {
            if let Some(target) = &effect.on_stream {
                if !ir.streams.iter().any(|stream| stream.name == *target) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: format!("`on stream {target}` names an undeclared stream"),
                        suggestion: Some(
                            "declare the stream at top level: `stream <name> { members [...] }`"
                                .to_owned(),
                        ),
                    });
                }
            }
            // A literal selection validates against the ONE selection
            // grammar at check time (DR-0052 R4.2 — the grammar lives in
            // whipplescript-core, the same parser the runtime uses;
            // dynamic expressions validate at execution instead).
            if let Some(source) = &effect.selection_source {
                let trimmed = source.trim();
                if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
                    let literal = &trimmed[1..trimmed.len() - 1];
                    if let Err(error) = whipplescript_core::selection::parse(literal) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!("the selection does not parse: {error}"),
                            suggestion: Some(
                                "selections compose atoms like `path(<glob>)`, `by(<prefix>)`, \
                                 `intent(<prefix>)`, `cut(<id>)` with `|`, `&`, `~`, and \
                                 `dependents-of(...)`"
                                    .to_owned(),
                            ),
                        });
                    }
                }
            }
            // `with access to vcs { repair for <binding> }` (DR-0052
            // R3): the vcs resource grants exactly one operation, on an
            // invoke only (a tell would hand a MODEL repair authority),
            // and its target must be a fact this rule bound — the grant's
            // extent IS the bound incident fact.
            for grant in &effect.access_grants {
                if grant.resource != "vcs" {
                    continue;
                }
                if effect.kind != IrEffectKind::WorkflowInvoke {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: "a `vcs` access grant rides an `invoke` only".to_owned(),
                        suggestion: Some(
                            "repair authority is orchestration: grant it to a repair \
                             workflow via `invoke ... with access to vcs { repair for \
                             <binding> }`; agents never receive it"
                                .to_owned(),
                        ),
                    });
                    continue;
                }
                for op in &grant.operations {
                    if op.operation != "repair" {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!("unknown `vcs` grant operation `{}`", op.operation),
                            suggestion: Some(
                                "the vcs resource grants `repair for <binding>`".to_owned(),
                            ),
                        });
                        continue;
                    }
                    let Some(target) = &op.target else {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: "`repair` names no binding".to_owned(),
                            suggestion: Some(
                                "write `repair for <binding>` where the binding is a \
                                 vcs arming fact this rule matched (e.g. `when reconcile \
                                 stalled as r`)"
                                    .to_owned(),
                            ),
                        });
                        continue;
                    };
                    let bound = rule.whens.iter().any(|when| {
                        binding_after_as(when.pattern.as_str()).as_deref() == Some(target)
                    });
                    if !bound {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!("`repair for {target}` names no binding of this rule"),
                            suggestion: Some(
                                "bind the arming fact first: `when reconcile stalled as \
                                 <binding>` (or the dotted `when fact vcs.* as <binding>` \
                                 form)"
                                    .to_owned(),
                            ),
                        });
                    }
                }
            }
            // `transport ... onto <target>`: the target is a nameable
            // tier — `mainline`, or a declared stream (its line).
            if let Some(target) = &effect.transport_onto {
                if target != "mainline" && !ir.streams.iter().any(|stream| stream.name == *target) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: format!(
                            "`onto {target}` names neither `mainline` nor a declared stream"
                        ),
                        suggestion: Some(
                            "transport targets are the nameable tiers: `onto mainline`, or \
                             `onto <stream>` for a declared stream's line"
                                .to_owned(),
                        ),
                    });
                }
            }
        }
    }
}

/// std.messaging v1 provider capability report (spec/std-messaging.md
/// "Capability reports + conditioned checks"). Reports are DATA, never code
/// (M8): these compiled constants are mirrored by the embedded std.messaging
/// manifest's `bindings[].config.report` rows, and the conditioned static
/// checks below admit syntax only when the selected provider's report
/// supports it. Report axes are messaging.md "Provider Capability Report"
/// narrowed for v1: `delivery_receipts` ⊆ {accepted, failed}; `identity` ⊆
/// {anonymous, claimed_actor} (no verified_actor provider exists, so any
/// check demanding verified identity fails closed); `content` ⊆
/// {text, markdown}.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ChannelProviderReport {
    /// The short channel-declaration identifier (`provider <short_name>`).
    pub short_name: &'static str,
    /// The binding-row provider id the short name resolves to.
    pub provider_id: &'static str,
    /// `outbound_only` | `inbound_only` | `bidirectional`.
    pub direction: &'static str,
    /// `anonymous` | `claimed_actor`.
    pub identity: &'static str,
    /// Interaction families the provider can deliver callbacks for.
    pub interactions: &'static [&'static str],
    /// Payload content kinds the provider accepts.
    pub content: &'static [&'static str],
    /// Receipt statuses the provider can report.
    pub delivery_receipts: &'static [&'static str],
}

/// The four v1 std.messaging providers (spec/std-messaging.md "Providers").
pub const CHANNEL_PROVIDER_REPORTS: &[ChannelProviderReport] = &[
    ChannelProviderReport {
        short_name: "fixture",
        provider_id: "fixture",
        direction: "bidirectional",
        identity: "claimed_actor",
        interactions: &["buttons", "reactions"],
        content: &["text", "markdown"],
        delivery_receipts: &["accepted", "failed"],
    },
    ChannelProviderReport {
        short_name: "local",
        provider_id: "std.messaging.local",
        direction: "bidirectional",
        identity: "claimed_actor",
        interactions: &["buttons", "reactions"],
        content: &["text", "markdown"],
        delivery_receipts: &["accepted", "failed"],
    },
    ChannelProviderReport {
        short_name: "desktop",
        provider_id: "std.messaging.desktop",
        direction: "outbound_only",
        identity: "anonymous",
        interactions: &[],
        content: &["text"],
        delivery_receipts: &["accepted", "failed"],
    },
    ChannelProviderReport {
        short_name: "stdio",
        provider_id: "std.messaging.stdio",
        direction: "bidirectional",
        identity: "claimed_actor",
        interactions: &["buttons"],
        content: &["text", "markdown"],
        delivery_receipts: &["accepted", "failed"],
    },
];

/// Resolve a channel's declared `provider <p>` identifier against the v1
/// provider reports: the short name (`local`) or the full binding provider id
/// (`std.messaging.local`) both resolve. `None` = unknown identifier, a check
/// error (spec/std-messaging.md open question 2 resolved: short names resolved
/// against contributed provider kinds, unknown = check error).
pub fn channel_provider_report(provider: &str) -> Option<&'static ChannelProviderReport> {
    CHANNEL_PROVIDER_REPORTS
        .iter()
        .find(|report| report.short_name == provider || report.provider_id == provider)
}

/// The built-in resource gauges: deterministic observables already in the
/// effect ledger, present without declaration (improve design note §3).
/// `std.cache_hit` is the provider prompt-cache hit rate (cache-read tokens /
/// total input-side tokens) — present only when the provider reports cache
/// usage (spec/inference-cache-note.md G2).
pub const BUILTIN_GAUGES: &[&str] = &["std.spend", "std.latency", "std.tokens", "std.cache_hit"];

/// The v1 std.files store providers (spec/std-files.md "Providers"): `local`
/// is the FileStore host-projection seam (native + DO) and the default when a
/// `file store` declares no `provider` clause. Non-filesystem providers
/// (S3/GitHub/Drive) are deferred with cause; an unknown identifier is a
/// check error at the declaration.
pub const FILE_STORE_PROVIDERS: &[&str] = &["local"];

/// Cross-reference validation for the improve surface, run after the item
/// loop so declaration order never matters: judge `coerce` targets must
/// resolve, derived-gauge inputs and campaign gauge references must name a
/// declared gauge or a built-in resource gauge, and a campaign's partition
/// must be disjoint (a gauge cannot be both ascended and sacrificed).
fn validate_improve_declarations(ir: &IrProgram, diagnostics: &mut Vec<Diagnostic>) {
    // A mark rides a committing site: its `after` target must be a rule
    // (flow segments have lowered to `flow.<name>.segN` rules by now).
    for mark in &ir.marks {
        if !ir.rules.iter().any(|rule| rule.name == mark.site) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: mark.span,
                message: format!("mark `{}` rides unknown site `{}`", mark.name, mark.site),
                suggestion: Some(format!(
                    "declared rules: {}",
                    ir.rules
                        .iter()
                        .map(|rule| rule.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )),
            });
        }
    }
    let gauge_names: BTreeSet<&str> = ir.gauges.iter().map(|gauge| gauge.name.as_str()).collect();
    let resolves = |name: &str| gauge_names.contains(name) || BUILTIN_GAUGES.contains(&name);
    let unknown = |name: &str, span: SourceSpan, diagnostics: &mut Vec<Diagnostic>| {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("unknown gauge `{name}`"),
            suggestion: Some(format!(
                "declare `gauge {name} {{ ... }}` or use a built-in gauge ({})",
                BUILTIN_GAUGES.join(", ")
            )),
        });
    };
    for gauge in &ir.gauges {
        if gauge.judge_kind == "coerce" {
            match ir
                .coerces
                .iter()
                .find(|coerce| coerce.name == gauge.judge_target)
            {
                None => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: gauge.span,
                        message: format!(
                            "gauge `{}` judges via undeclared coerce `{}`",
                            gauge.name, gauge.judge_target
                        ),
                        suggestion: Some("declare the coerce this gauge judges with".to_owned()),
                    });
                }
                // Explicit-argument binding (settled 2026-07-14): the
                // judge's data diet is written down, never inferred. The
                // single reserved `record` passes the whole judge-input
                // record to a one-parameter coerce; otherwise each path
                // (`input.…` / `facts.<Class>.<field>`) feeds the
                // parameter at its position, arity-checked here so a
                // drifted signature is a check error, not a silently
                // rebound judge.
                Some(coerce) if !gauge.judge_args.is_empty() => {
                    if gauge.judge_args.len() == 1 && gauge.judge_args[0] == "record" {
                        if coerce.params.len() != 1 {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: gauge.span,
                                message: format!(
                                    "gauge `{}`: the reserved `(record)` form needs a \
                                     single-parameter coerce; `{}` takes {}",
                                    gauge.name,
                                    gauge.judge_target,
                                    coerce.params.len()
                                ),
                                suggestion: Some(
                                    "give the coerce one record-shaped parameter, or bind each \
                                     parameter to an explicit path"
                                        .to_owned(),
                                ),
                            });
                        }
                    } else {
                        for arg in &gauge.judge_args {
                            let head = arg.split('.').next().unwrap_or_default();
                            let valid = match head {
                                "record" => false, // reserved: only alone
                                "input" => true,
                                "facts" => arg.splitn(3, '.').count() == 3,
                                _ => false,
                            };
                            if !valid {
                                diagnostics.push(Diagnostic {
                                    related: Vec::new(),
                                    span: gauge.span,
                                    message: format!(
                                        "gauge `{}`: judge argument `{arg}` is not a record \
                                         path",
                                        gauge.name
                                    ),
                                    suggestion: Some(
                                        "arguments are `input.<path>`, \
                                         `facts.<Class>.<field...>`, or the single reserved \
                                         `record`"
                                            .to_owned(),
                                    ),
                                });
                            }
                        }
                        if gauge.judge_args.len() != coerce.params.len() {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: gauge.span,
                                message: format!(
                                    "gauge `{}`: judge passes {} argument{} but coerce `{}` \
                                     takes {}",
                                    gauge.name,
                                    gauge.judge_args.len(),
                                    if gauge.judge_args.len() == 1 { "" } else { "s" },
                                    gauge.judge_target,
                                    coerce.params.len()
                                ),
                                suggestion: Some(
                                    "bind one path per coerce parameter, in order".to_owned(),
                                ),
                            });
                        }
                    }
                }
                Some(_) => {}
            }
        }
        if !gauge.inputs.is_empty() && gauge.judge_kind != "exec" {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: gauge.span,
                message: format!(
                    "derived gauge `{}` must judge via exec (its judge receives the input score vector)",
                    gauge.name
                ),
                suggestion: Some("use `judge via exec \"<validator>\"`".to_owned()),
            });
        }
        for input in &gauge.inputs {
            if input == &gauge.name {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: gauge.span,
                    message: format!("derived gauge `{}` cannot input itself", gauge.name),
                    suggestion: None,
                });
            } else if !resolves(input) {
                unknown(input, gauge.span, diagnostics);
            }
        }
    }
    for campaign in &ir.campaigns {
        let mut named: Vec<(&str, &'static str)> = Vec::new();
        for name in &campaign.ascend {
            named.push((name, "ascend"));
        }
        for reach in &campaign.reach {
            named.push((&reach.gauge, "reach"));
        }
        for guard in &campaign.guard {
            named.push((&guard.gauge, "guard"));
        }
        for name in &campaign.sacrifice {
            named.push((name, "sacrifice"));
        }
        let mut seen: BTreeMap<&str, &'static str> = BTreeMap::new();
        for (name, role) in named {
            if !resolves(name) {
                unknown(name, campaign.span, diagnostics);
            }
            if let Some(previous) = seen.insert(name, role) {
                let message = if previous == role {
                    format!(
                        "campaign `{}` names gauge `{name}` twice in {role}",
                        campaign.name
                    )
                } else {
                    format!(
                        "campaign `{}` names gauge `{name}` as both {previous} and {role}",
                        campaign.name
                    )
                };
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: campaign.span,
                    message,
                    suggestion: Some("name each gauge once, in at most one clause".to_owned()),
                });
            }
        }
    }
}

/// The harness class (DR-0034). `Managed` = WhippleScript is the agent runtime
/// (owned; hermetic context, full provenance, reproducible). `Delegated` = a foreign
/// runtime WhippleScript invokes, which assembles its own context. The guarantee is
/// two-valued, so the class is too.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HarnessClass {
    Managed,
    Delegated,
}

impl HarnessClass {
    pub fn as_str(self) -> &'static str {
        match self {
            HarnessClass::Managed => "managed",
            HarnessClass::Delegated => "delegated",
        }
    }
}

/// Classify a harness kind (DR-0034 Decision 6). Total over the supported kinds:
/// `owned` and the credential-free `fixture` model client are Managed; every other
/// kind (codex/claude sidecars, the `native-fixture` delegated adapter, `command`)
/// is Delegated. An unrecognized kind — validated registry-side by the CLI
/// (spec/std-agent.md "Open provider registry") — defaults to Delegated, never
/// granting the Managed guarantee to something unknown.
pub fn harness_class(kind: &str) -> HarnessClass {
    match kind {
        "owned" | "fixture" => HarnessClass::Managed,
        _ => HarnessClass::Delegated,
    }
}

fn validate_test_expr_source(
    label: &str,
    source: &str,
    span: SourceSpan,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if source.trim().is_empty() {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("{label} is empty"),
            suggestion: Some("provide an expression".to_owned()),
        });
        return;
    }
    if let Err(error) = parse_expression(source) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("{label} is not a valid expression: {error}"),
            suggestion: None,
        });
    }
}

/// The string-literal values of a literal-union (or single-literal) type, or `None`
/// if the type is not a pure string-literal union. Used to validate Family B
/// discriminants.
fn literal_union_values(ty: &TypeSyntax) -> Option<Vec<String>> {
    match ty {
        TypeSyntax::LiteralString { value, .. } => Some(vec![value.clone()]),
        TypeSyntax::Union { variants, .. } => {
            let values = variants
                .iter()
                .filter_map(|variant| match variant {
                    TypeSyntax::LiteralString { value, .. } => Some(value.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>();
            (!values.is_empty() && values.len() == variants.len()).then_some(values)
        }
        _ => None,
    }
}

/// Family B validation (spec/decision-records/discriminated-families-design.md §6.3):
/// every `<field> <T> when <disc> is "<lit>"` must name a same-schema discriminant
/// that is a string-literal union, and `<lit>` must be one of its values.
fn validate_presence_conditions(
    container: &str,
    fields: &[ClassField],
    diagnostics: &mut Vec<Diagnostic>,
) {
    for field in fields {
        let Some((disc, literal)) = &field.presence_condition else {
            continue;
        };
        let Some(disc_field) = fields.iter().find(|candidate| &candidate.name.name == disc) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: field.span,
                message: format!(
                    "`{container}` field `{}` is conditioned on unknown discriminant `{disc}`",
                    field.name.name
                ),
                suggestion: Some(
                    "`when <field> is \"...\"` must name a literal-union field of the same schema"
                        .to_owned(),
                ),
            });
            continue;
        };
        match literal_union_values(&disc_field.ty) {
            Some(values) if values.iter().any(|value| value == literal) => {}
            Some(values) => diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: field.span,
                message: format!(
                    "`{container}` field `{}` is conditioned on `{disc} is \"{literal}\"`, which is not a value of `{disc}`",
                    field.name.name
                ),
                suggestion: Some(format!("use one of: {}", values.join(", "))),
            }),
            None => diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: field.span,
                message: format!(
                    "`{container}` field `{}` is conditioned on `{disc}`, which is not a string-literal discriminant",
                    field.name.name
                ),
                suggestion: Some(
                    "the discriminant must be a string-literal union, e.g. `kind \"a\" | \"b\"`"
                        .to_owned(),
                ),
            }),
        }
    }
}

/// The coerce body is a clause list — `prompt` (single or multi-line) and
/// `provider <name>` — not free text. Reject anything else so a typo'd
/// `promt` (which would otherwise silently produce a coercion with NO prompt)
/// or a stray field fails at `check`, matching the agent-block posture.
/// The backend named by a coerce declaration's `provider <name>` clause.
///
/// Mirrors `validate_coerce_body_fields`'s prompt tracking exactly: a `provider`
/// line inside a `"""` prompt is prose the model reads, not a clause, and
/// reading it as one would let a prompt rename the endpoint its own egress is
/// judged against.
fn coerce_declared_provider(body: &str) -> Option<String> {
    let mut in_prompt = false;
    let mut awaiting_opener = false;
    for line in body.lines() {
        let trimmed = line.trim();
        if in_prompt {
            if trimmed.matches('"').count() >= 3 && trimmed.matches("\"\"\"").count() % 2 == 1 {
                in_prompt = false;
            }
            continue;
        }
        if awaiting_opener {
            if trimmed.is_empty() {
                continue;
            }
            awaiting_opener = false;
            if let Some(after_opener) = trimmed.strip_prefix("\"\"\"") {
                if after_opener.matches("\"\"\"").count() % 2 == 0 {
                    in_prompt = true;
                }
                continue;
            }
        }
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if trimmed == "prompt" {
            awaiting_opener = true;
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("prompt ") {
            if let Some(after_opener) = rest.strip_prefix("\"\"\"") {
                if after_opener.matches("\"\"\"").count() % 2 == 0 {
                    in_prompt = true;
                }
            }
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("provider ") {
            let mut tokens = rest.split_whitespace();
            if let (Some(name), None) = (tokens.next(), tokens.next()) {
                return Some(name.to_owned());
            }
        }
    }
    None
}

#[cfg(test)]
#[path = "lib_tests/coerce_provider.rs"]
mod coerce_provider_tests;

fn validate_coerce_body_fields(coerce: &CoerceDecl, diagnostics: &mut Vec<Diagnostic>) {
    let mut in_prompt = false;
    let mut awaiting_opener = false;
    for line in coerce.body.text.lines() {
        let trimmed = line.trim();
        if in_prompt {
            // A line with an odd number of `"""` markers closes the prompt.
            if trimmed.matches("\"\"\"").count() % 2 == 1 {
                in_prompt = false;
            }
            continue;
        }
        if awaiting_opener {
            // Bare `prompt` on its own line: the opener is the next
            // non-empty line.
            if trimmed.is_empty() {
                continue;
            }
            awaiting_opener = false;
            if let Some(after_opener) = trimmed.strip_prefix("\"\"\"") {
                if after_opener.matches("\"\"\"").count() % 2 == 0 {
                    in_prompt = true;
                }
                continue;
            }
            // fall through: not an opener — validate as a clause line
        }
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if trimmed == "prompt" {
            awaiting_opener = true;
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("prompt ") {
            let rest = rest.trim_start();
            if let Some(after_opener) = rest.strip_prefix("\"\"\"") {
                // `prompt """…` (optionally annotated): multi-line unless the
                // triple quote closes on the same line.
                if after_opener.matches("\"\"\"").count() % 2 == 0 {
                    in_prompt = true;
                }
            }
            // Single-quoted one-line prompts close on their own line.
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("provider ") {
            if rest.split_whitespace().count() != 1 {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: coerce.name.span,
                    message: format!(
                        "coerce `{}` has a malformed `provider` clause: `{trimmed}`",
                        coerce.name.name
                    ),
                    suggestion: Some("write `provider <name>`".to_owned()),
                });
            }
            continue;
        }
        let field = trimmed.split_whitespace().next().unwrap_or(trimmed);
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: coerce.name.span,
            message: format!(
                "unknown coerce field `{field}` on coerce `{}`",
                coerce.name.name
            ),
            suggestion: Some("supported coerce fields are `prompt` and `provider`".to_owned()),
        });
    }
}

fn validate_type_refs(
    ty: &TypeSyntax,
    schema_names: &BTreeSet<String>,
    agent_names: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match ty {
        TypeSyntax::Primitive { .. } | TypeSyntax::LiteralString { .. } => {}
        TypeSyntax::Ref { name } => {
            if !schema_names.contains(&name.name) && !is_builtin_schema_ref(&name.name) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: name.span,
                    message: format!("unknown schema reference `{}`", name.name),
                    suggestion: Some(format!(
                        "declare `class {}` or `enum {}` before using it",
                        name.name, name.name
                    )),
                });
            }
        }
        TypeSyntax::AgentRef { agents, .. } => {
            let mut seen = BTreeSet::new();
            for agent in agents {
                if !seen.insert(agent.name.clone()) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: agent.span,
                        message: format!("AgentRef lists agent `{}` more than once", agent.name),
                        suggestion: Some(
                            "remove the duplicate agent from the AgentRef domain".to_owned(),
                        ),
                    });
                }
                if !agent_names.contains(&agent.name) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: agent.span,
                        message: format!("AgentRef references unknown agent `{}`", agent.name),
                        suggestion: Some(format!(
                            "declare `agent {}` before using it in AgentRef",
                            agent.name
                        )),
                    });
                }
            }
        }
        TypeSyntax::Optional { inner, .. }
        | TypeSyntax::Array { inner, .. }
        | TypeSyntax::Map { inner, .. } => {
            validate_type_refs(inner, schema_names, agent_names, diagnostics)
        }
        TypeSyntax::Union { variants, .. } => {
            for variant in variants {
                validate_type_refs(variant, schema_names, agent_names, diagnostics);
            }
        }
    }
}

fn is_builtin_schema_ref(name: &str) -> bool {
    matches!(
        name,
        "AgentTurn"
            | "WorkItem"
            | "Evidence"
            | "VcsChange"
            | "VcsContention"
            | "VcsPromotion"
            | "VcsStall"
            | "TerminalFailed"
            | "TerminalTimedOut"
            | "TerminalCancelled"
            | "TerminalOutcome"
    )
}

/// The terminal-family schemas are `origin = observer` (discriminated-families
/// design §5.4): the kernel projects them when it observes an effect or child
/// terminal, and user rules may only *eliminate* them (`after … fails/times
/// out/cancels as f`), never *construct* them. A rule that `record`s one would
/// forge a terminal outcome the kernel never produced, misleading the
/// `after`/terminal-case reaction machinery. Rejected at check time.
fn is_observer_only_schema(name: &str) -> bool {
    matches!(
        name,
        "TerminalFailed"
            | "TerminalTimedOut"
            | "TerminalCancelled"
            | "TerminalOutcome"
            // std.vcs observer schemas: the mediator emits them; a rule
            // that `record`s one forges a workspace observation.
            | "VcsChange"
            | "VcsContention"
            | "VcsPromotion"
            | "VcsStall"
    )
}

fn validate_canonical_rule_body_syntax(rule: &RuleDecl, diagnostics: &mut Vec<Diagnostic>) {
    for line in rule.body.text.lines().map(str::trim) {
        if line.starts_with("then ") {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` uses unsupported `then` sequencing",
                    rule.name.name
                ),
                suggestion: Some(
                    "use `after <effect> succeeds { ... }` blocks for effect sequencing".to_owned(),
                ),
            });
        }
        if line.starts_with("after ") && line.contains("=>") {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` uses unsupported `after ... =>` sequencing",
                    rule.name.name
                ),
                suggestion: Some("write `after <effect> succeeds { ... }`".to_owned()),
            });
        }
    }
}

fn build_rule_dependencies(rules: &[IrRule]) -> Vec<IrRuleDependency> {
    let mut dependencies = Vec::new();
    for producer in rules {
        for produced_fact in &producer.metadata.fact_writes {
            for consumer in rules {
                if consumer.metadata.fact_reads.contains(produced_fact) {
                    dependencies.push(IrRuleDependency {
                        producer: producer.name.clone(),
                        consumer: consumer.name.clone(),
                        fact: produced_fact.clone(),
                    });
                }
            }
        }
    }
    dependencies.sort_by(|left, right| {
        (&left.producer, &left.consumer, &left.fact).cmp(&(
            &right.producer,
            &right.consumer,
            &right.fact,
        ))
    });
    dependencies
}

/// `send via <channel>` (std.messaging) must name a declared `channel`. The
/// channel name is carried as the construct's `channel` field; an unknown channel
/// would lower to a `messaging.send` effect that no provider can route, so it is
/// rejected at compile time (mirrors `acquire`/`consume` resource-existence checks).
/// `when message from <channel> as msg` (spec/messaging.md) must name a declared
/// channel, mirroring the outbound `send via <channel>` check.
fn validate_message_from_channels(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for when in &rule.whens {
        let (pattern, _) = split_when_guard(&when.text);
        let Some(rest) = pattern.trim_start().strip_prefix("message from ") else {
            continue;
        };
        let Some(channel) = rest.split_whitespace().next() else {
            continue;
        };
        if !semantic.channels.iter().any(|c| c.as_str() == channel) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: when.span,
                message: format!("`when message from {channel}` names an unknown channel"),
                suggestion: Some(
                    "declare it with `channel <name> { provider … }`, or correct the channel name"
                        .to_owned(),
                ),
            });
            continue;
        }
        // Capability-report-conditioned check (spec/std-messaging.md "Static
        // checks"): inbound observation requires the channel provider's report
        // `direction` ∈ {inbound_only, bidirectional}. Desktop channels are a
        // check error here — send/receive-capable are distinguishable (the v1
        // acceptance test). Unknown providers already errored at the channel
        // declaration, so they are not re-flagged here.
        if let Some(report) = semantic
            .channel_providers
            .get(channel)
            .and_then(|provider| channel_provider_report(provider))
        {
            if report.direction == "outbound_only" {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: when.span,
                    message: format!(
                        "`when message from {channel}` observes a channel whose provider `{}` is outbound-only (its capability report cannot deliver inbound messages)",
                        report.short_name
                    ),
                    suggestion: Some(
                        "route inbound observation through an inbound-capable provider (`local`, `stdio`, `fixture`)"
                            .to_owned(),
                    ),
                });
            }
        }
    }
}

fn validate_send_channels(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let (ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
    fn walk(
        statements: &[body::BodyStmt],
        semantic: &SemanticContext,
        diagnostics: &mut Vec<Diagnostic>,
    ) {
        for statement in statements {
            match statement {
                body::BodyStmt::Effect(effect) => {
                    if let body::BodyEffectKind::ConstructCapabilityCall {
                        keyword, fields, ..
                    } = &effect.kind
                    {
                        if keyword == "send" {
                            if let Some(channel) =
                                fields.iter().find(|field| field.name == "channel")
                            {
                                if !semantic.channels.contains(&channel.source) {
                                    diagnostics.push(Diagnostic {
                                        related: Vec::new(),
                                        span: effect.span,
                                        message: format!(
                                            "`send via {}` names an unknown channel",
                                            channel.source
                                        ),
                                        suggestion: Some(
                                            "declare it with `channel <name> { provider … }`, or correct the channel name"
                                                .to_owned(),
                                        ),
                                    });
                                } else if let Some(report) = semantic
                                    .channel_providers
                                    .get(&channel.source)
                                    .and_then(|provider| channel_provider_report(provider))
                                {
                                    // Capability-report-conditioned check
                                    // (spec/std-messaging.md "Static checks"):
                                    // outbound `send via` requires the provider
                                    // report `direction` ∈ {outbound_only,
                                    // bidirectional}. No v1 provider is
                                    // inbound-only, so this arm has no
                                    // reachable negative today; it exists so a
                                    // future inbound-only provider fails
                                    // closed at check time, not at dispatch.
                                    if report.direction == "inbound_only" {
                                        diagnostics.push(Diagnostic {
                                            related: Vec::new(),
                                            span: effect.span,
                                            message: format!(
                                                "`send via {}` targets a channel whose provider `{}` is inbound-only (its capability report cannot accept outbound sends)",
                                                channel.source, report.short_name
                                            ),
                                            suggestion: Some(
                                                "send through an outbound-capable provider (`local`, `desktop`, `stdio`, `fixture`)"
                                                    .to_owned(),
                                            ),
                                        });
                                    }
                                }
                            }
                        }
                        // MEM-1 check 1: the memory operations must name a
                        // DECLARED pool — the twin of the send-channel check.
                        if matches!(keyword.as_str(), "recall" | "learn" | "curate") {
                            if let Some(pool) = fields.iter().find(|field| field.name == "pool") {
                                if !semantic.memory_pools.contains(&pool.source) {
                                    diagnostics.push(Diagnostic {
                                        related: Vec::new(),
                                        span: effect.span,
                                        message: format!(
                                            "`{keyword}` names unknown memory pool `{}`",
                                            pool.source
                                        ),
                                        suggestion: Some(
                                            "declare it with `memory pool <name> { … }`, or correct the pool name"
                                                .to_owned(),
                                        ),
                                    });
                                }
                            }
                        }
                    }
                }
                body::BodyStmt::After(after) => walk(&after.body, semantic, diagnostics),
                body::BodyStmt::Case(case) => {
                    for branch in &case.branches {
                        walk(&branch.body, semantic, diagnostics);
                    }
                }
                _ => {}
            }
        }
    }
    walk(&ast.statements, semantic, diagnostics);
}

/// In-turn agent observations — `agent.turn.streamed` (streamed progress),
/// `agent.turn.tool_requested` (in-turn tool call), and `agent.turn.artifact_captured`
/// (captured artifact/diff) — are recorded as EVIDENCE, never as rule-matchable facts
/// (spec/agent-harness.md). The rule-matchable lifecycle facts are
/// `agent.turn.started/completed/failed/timed_out/cancelled`. A `when` that matches an
/// evidence-only fact can never fire, so it is a compile-time error.
const EVIDENCE_ONLY_TURN_FACTS: [&str; 3] = [
    "agent.turn.streamed",
    "agent.turn.tool_requested",
    "agent.turn.artifact_captured",
];

/// Structural well-formedness of access grants (`with access to <resource> { … }`):
/// a grant must grant at least one operation, and a single effect must not list the
/// same resource twice (merge them). The deeper "required
/// Resource/Operation/Capability ports" validation against the capability registry
/// is a separate construct-graph-layer concern, so this stays registry-independent
/// and zero-false-positive.
fn validate_turn_access_grants(
    rule: &RuleDecl,
    metadata: &IrRuleMetadata,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for effect in &metadata.effects {
        if effect.access_grants.is_empty() {
            continue;
        }
        let mut seen = BTreeSet::new();
        for grant in &effect.access_grants {
            if grant.operations.is_empty() {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: effect.span,
                    message: format!(
                        "rule `{}` has a `with access to {}` grant that grants no operations",
                        rule.name.name, grant.resource
                    ),
                    suggestion: Some(
                        "list at least one operation in the grant block, or drop the grant"
                            .to_owned(),
                    ),
                });
            }
            if !seen.insert(grant.resource.clone()) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: effect.span,
                    message: format!(
                        "rule `{}` lists access resource `{}` more than once on one effect",
                        rule.name.name, grant.resource
                    ),
                    suggestion: Some(
                        "merge the grant clauses for a resource into a single block".to_owned(),
                    ),
                });
            }
        }
    }
}

fn validate_evidence_fact_not_matched(rule: &RuleDecl, diagnostics: &mut Vec<Diagnostic>) {
    for when in &rule.whens {
        let (pattern, _) = split_when_guard(&when.text);
        let Some(name) = runtime_fact_name_for_pattern(pattern) else {
            continue;
        };
        if EVIDENCE_ONLY_TURN_FACTS.contains(&name.as_str()) {
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: when.span,
                message: format!(
                    "rule `{}` matches evidence-only fact `{name}`: in-turn observations are evidence, not rule-matchable facts",
                    rule.name.name
                ),
                suggestion: Some(
                    "match a lifecycle fact (`agent.turn.completed`/`failed`/`timed_out`/`cancelled`) and read in-turn detail from its evidence".to_owned(),
                ),
            });
        }
    }
}

/// DR-0043 Decision 5: extracts each rule's `during`/`until` region (at most
/// one per rule in v1), REWRITES the rule body to the condition-HOLDS variant
/// (region content spliced inline — every downstream scanner and effect-id
/// derivation sees ordinary text), and returns the pre-rendered region
/// metadata (removed / lapsed variants, region effect scopes) to attach onto
/// the lowered `IrRule`s.
fn extract_rule_regions(
    items: &mut [Item],
    diagnostics: &mut Vec<Diagnostic>,
) -> BTreeMap<String, IrRegion> {
    let mut pending = BTreeMap::new();
    for item in items.iter_mut() {
        let Item::Rule(rule) = item else {
            continue;
        };
        let (ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
        let mut regions = Vec::new();
        collect_region_blocks(&ast.statements, &[], &mut regions);
        if regions.is_empty() {
            continue;
        }
        if regions.len() > 1 {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: regions[1].0.span,
                message: format!(
                    "rule `{}` declares more than one `during`/`until` region",
                    rule.name.name
                ),
                suggestion: Some(
                    "v1 supports one region per rule (including nested regions); split the \
                     rule or merge the conditions"
                        .to_owned(),
                ),
            });
            continue;
        }
        let (region, region_case_arms) = regions[0].clone();
        if count_effect_statements(&region.body) == 0 {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: region.span,
                message: format!(
                    "the `{}` region in rule `{}` contains no progression",
                    if region.until { "until" } else { "during" },
                    rule.name.name
                ),
                suggestion: Some(
                    "a region around purely-atomic actions commits with admission and can \
                     never lapse between steps; it needs at least one effect with a \
                     continuation"
                        .to_owned(),
                ),
            });
            continue;
        }
        // Lapse-arm binding scope: the arm may run at ANY point inside the
        // region, so it may only reference bindings guaranteed at region
        // entry — never a binding the region itself introduces (the optional
        // progress view is the sanctioned window into those).
        let mut region_bindings = BTreeSet::new();
        collect_all_binding_names(&region.body, &mut region_bindings);
        if let Some(view) = &region.lapse_binding {
            region_bindings.remove(view);
        }
        let mut arm_roots = BTreeSet::new();
        collect_statement_roots(&region.lapse_body, &mut arm_roots);
        for root in &arm_roots {
            if region_bindings.contains(root) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: region.span,
                    message: format!(
                        "the `on lapse` arm of rule `{}` references `{root}`, a binding the \
                         region introduces — it may not exist when the arm runs",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "reference only bindings from before the region, or bind the \
                         progress view (`on lapse as got`) and read `got.<binding>` — its \
                         fields are present exactly if that step settled"
                            .to_owned(),
                    ),
                });
            }
        }
        // Variant surgery. All spans are absolute; rebase onto the body text.
        let base = rule.body.span.start;
        let text = rule.body.text.clone();
        let clamp = |offset: usize| offset.saturating_sub(base).min(text.len());
        let (r_start, r_end) = (clamp(region.span.start), clamp(region.span.end));
        let (b_start, b_end) = (clamp(region.body_span.start), clamp(region.body_span.end));
        let (l_start, l_end) = (clamp(region.lapse_span.start), clamp(region.lapse_span.end));
        if !(r_start <= b_start
            && b_start <= b_end
            && b_end <= l_start
            && l_start <= l_end
            && l_end <= r_end)
        {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: region.span,
                message: format!(
                    "internal: region span reconstruction failed for rule `{}`",
                    rule.name.name
                ),
                suggestion: None,
            });
            continue;
        }
        let body_content = &text[b_start..b_end];
        let arm_content = &text[l_start..l_end];
        let variant_holds = format!("{}{}{}", &text[..r_start], body_content, &text[r_end..]);
        let variant_removed = format!("{}{}", &text[..r_start], &text[r_end..]);
        let variant_lapsed = format!("{}{}{}", &text[..r_start], arm_content, &text[r_end..]);
        // Region effect scopes, computed on the HOLDS variant (the canonical
        // kernel body): each region-owned effect binding's LEVEL-1 `after`
        // ancestor is the scope the kernel keys its effect id under.
        let mut effect_bindings = BTreeSet::new();
        collect_effect_binding_names(&region.body, &mut effect_bindings);
        let (holds_ast, _) = body::parse_rule_body(&variant_holds, 0);
        let mut region_effects = Vec::new();
        assign_region_effect_scopes(
            &holds_ast.statements,
            None,
            &effect_bindings,
            &mut region_effects,
        );
        pending.insert(
            rule.name.name.clone(),
            IrRegion {
                until: region.until,
                condition: region.condition.clone(),
                lapse_binding: region.lapse_binding.clone(),
                effects: region_effects,
                body_removed: variant_removed,
                body_lapsed: variant_lapsed,
                arm_content: arm_content.to_owned(),
                arm_case_arms: region_case_arms,
            },
        );
        rule.body.text = variant_holds;
    }
    pending
}

/// Every region in the body, each paired with the `(scrutinee, pattern)` chain of
/// the `case` arms that enclose it. The chain is what lets the lapse arm be
/// read-narrowed at the position the region actually sits in: an arm inside
/// `case e.kind { "deploy" => … }` inherits that arm's Family B allowances, so
/// checking it against the rule-top (empty) allowed set would reject a legal read.
fn collect_region_blocks(
    statements: &[body::BodyStmt],
    case_arms: &[(String, String)],
    out: &mut Vec<(body::RegionBlock, Vec<(String, String)>)>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Region(region) => {
                out.push((region.clone(), case_arms.to_vec()));
                collect_region_blocks(&region.body, case_arms, out);
                collect_region_blocks(&region.lapse_body, case_arms, out);
            }
            body::BodyStmt::After(after) => collect_region_blocks(&after.body, case_arms, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    let mut nested = case_arms.to_vec();
                    nested.push((case.scrutinee.clone(), branch.pattern.clone()));
                    collect_region_blocks(&branch.body, &nested, out);
                }
            }
            _ => {}
        }
    }
}

fn count_effect_statements(statements: &[body::BodyStmt]) -> usize {
    let mut count = 0;
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(_) => count += 1,
            body::BodyStmt::After(after) => count += count_effect_statements(&after.body),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    count += count_effect_statements(&branch.body);
                }
            }
            body::BodyStmt::Region(region) => {
                count += count_effect_statements(&region.body);
            }
            _ => {}
        }
    }
    count
}

fn collect_effect_binding_names(statements: &[body::BodyStmt], out: &mut BTreeSet<String>) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let Some(binding) = &effect.binding {
                    out.insert(binding.clone());
                }
            }
            body::BodyStmt::After(after) => collect_effect_binding_names(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_effect_binding_names(&branch.body, out);
                }
            }
            body::BodyStmt::Region(region) => {
                collect_effect_binding_names(&region.body, out);
            }
            _ => {}
        }
    }
}

/// Walks the HOLDS-variant AST assigning each region-owned effect its LEVEL-1
/// `after` scope (the kernel's effect-id key component). `level1` is fixed at
/// the first `after` ancestor and inherited by everything deeper.
fn assign_region_effect_scopes(
    statements: &[body::BodyStmt],
    level1: Option<&(String, String)>,
    region_bindings: &BTreeSet<String>,
    out: &mut Vec<IrRegionEffect>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let Some(binding) = &effect.binding {
                    if region_bindings.contains(binding)
                        && !out.iter().any(|known| &known.binding == binding)
                    {
                        out.push(IrRegionEffect {
                            binding: binding.clone(),
                            scope: level1.cloned(),
                        });
                    }
                }
            }
            body::BodyStmt::After(after) => {
                let own = (
                    after.binding.clone(),
                    after.predicate.kernel_str().to_owned(),
                );
                let next = level1.cloned().unwrap_or(own);
                assign_region_effect_scopes(&after.body, Some(&next), region_bindings, out);
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    assign_region_effect_scopes(&branch.body, level1, region_bindings, out);
                }
            }
            body::BodyStmt::Region(region) => {
                assign_region_effect_scopes(&region.body, level1, region_bindings, out);
            }
            _ => {}
        }
    }
}

/// Root identifiers referenced by a statement list's value positions: record
/// fields, terminal fields, done/cancel bindings, effect arguments, and
/// `{{ … }}` prompt interpolations. Used for the lapse-arm scope check.
fn collect_statement_roots(statements: &[body::BodyStmt], out: &mut BTreeSet<String>) {
    fn roots_in_expr(source: &str, out: &mut BTreeSet<String>) {
        let bytes = source.as_bytes();
        let mut i = 0;
        let mut in_string = false;
        while i < bytes.len() {
            let c = bytes[i] as char;
            if c == '"' {
                in_string = !in_string;
                i += 1;
                continue;
            }
            if in_string {
                i += 1;
                continue;
            }
            if c.is_ascii_alphabetic() || c == '_' {
                let start = i;
                while i < bytes.len() {
                    let cj = bytes[i] as char;
                    if cj.is_ascii_alphanumeric() || cj == '_' {
                        i += 1;
                    } else {
                        break;
                    }
                }
                let preceded_by_dot = start > 0 && bytes[start - 1] as char == '.';
                if !preceded_by_dot {
                    out.insert(source[start..i].to_owned());
                }
                continue;
            }
            i += 1;
        }
    }
    fn roots_in_fields(fields: &[body::FieldAssign], out: &mut BTreeSet<String>) {
        for field in fields {
            match &field.value {
                body::FieldValue::Expr { source, .. } => roots_in_expr(source, out),
                body::FieldValue::Nested { fields, .. } => roots_in_fields(fields, out),
                body::FieldValue::Shorthand => {
                    out.insert(field.name.clone());
                }
            }
        }
    }
    fn roots_in_prompt(text: &str, out: &mut BTreeSet<String>) {
        let mut rest = text;
        while let Some(open) = rest.find("{{") {
            let tail = &rest[open + 2..];
            let Some(close) = tail.find("}}") else {
                break;
            };
            roots_in_expr(&tail[..close], out);
            rest = &tail[close + 2..];
        }
    }
    for statement in statements {
        match statement {
            body::BodyStmt::Record(record) => roots_in_fields(&record.fields, out),
            body::BodyStmt::Done {
                binding,
                replacement,
                ..
            } => {
                out.insert(binding.clone());
                if let Some(record) = replacement {
                    roots_in_fields(&record.fields, out);
                }
            }
            body::BodyStmt::Cancel { binding, .. } => {
                out.insert(binding.clone());
            }
            body::BodyStmt::Effect(effect) => {
                if let Some(prompt) = &effect.prompt {
                    roots_in_prompt(&prompt.text, out);
                }
                match &effect.kind {
                    body::BodyEffectKind::Coerce { args, .. } => {
                        for arg in args {
                            roots_in_expr(arg, out);
                        }
                    }
                    body::BodyEffectKind::TrackerFinish { item, fields } => {
                        out.insert(item.clone());
                        roots_in_fields(fields, out);
                    }
                    body::BodyEffectKind::TrackerRelease { item } => {
                        out.insert(item.clone());
                    }
                    _ => {}
                }
            }
            body::BodyStmt::Terminal(terminal) => {
                roots_in_fields(&terminal.fields, out);
                if let Some(body::FieldValue::Expr { source, .. }) = &terminal.scalar {
                    roots_in_expr(source, out);
                }
            }
            body::BodyStmt::Milestone { fields, .. } => roots_in_fields(fields, out),
            body::BodyStmt::After(after) => collect_statement_roots(&after.body, out),
            body::BodyStmt::Case(case) => {
                roots_in_expr(&case.scrutinee, out);
                for branch in &case.branches {
                    collect_statement_roots(&branch.body, out);
                }
            }
            body::BodyStmt::Region(region) => {
                collect_statement_roots(&region.body, out);
                collect_statement_roots(&region.lapse_body, out);
            }
            body::BodyStmt::Redact { source, .. } => {
                out.insert(source.clone());
            }
        }
    }
}

fn validate_effectful_self_trigger(
    rule: &RuleDecl,
    metadata: &IrRuleMetadata,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if metadata.effects.is_empty() {
        return;
    }

    for written_fact in &metadata.fact_writes {
        if metadata.fact_reads.contains(written_fact)
            && !metadata.fact_consumes.contains(written_fact)
        {
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "effectful rule `{}` preserves trigger fact `{written_fact}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "consume or advance the triggering fact, or move the next effect behind an external completion event"
                        .to_owned(),
                ),
            });
        }
    }
}

fn binding_types_for_rule(rule: &RuleDecl) -> BTreeMap<String, String> {
    let mut binding_types = BTreeMap::new();
    for when in &rule.whens {
        if let Some((binding, schema)) = binding_from_when(&when.text) {
            binding_types.insert(binding, schema);
        }
    }
    binding_types
}

fn validate_workflow_terminal_actions(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    contracts: &WorkflowContractNames,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for line in rule.body.text.lines().map(str::trim) {
        let terminal = line
            .strip_prefix("complete ")
            .map(|rest| ("complete", rest, &contracts.outputs))
            .or_else(|| {
                line.strip_prefix("fail ")
                    .map(|rest| ("fail", rest, &contracts.failures))
            });
        let Some((action, rest, declared)) = terminal else {
            continue;
        };
        // Scalar terminal form: `complete result 0.9` / `fail error "msg"` — a bare
        // value after the name, with no `{ }` block and no `from` projection.
        // Validated against a scalar (primitive) contract; class contracts still
        // require a field block (checked by the block path below).
        if !rest.contains('{') {
            let tokens: Vec<&str> = rest.split_whitespace().collect();
            let is_from = matches!(tokens.as_slice(), [_, "from", ..]) && action == "complete";
            if tokens.len() >= 2 && !is_from {
                let name = tokens[0];
                let value = rest.trim().get(name.len()..).unwrap_or("").trim();
                if !declared.contains_key(name) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` {action}s unknown workflow terminal `{name}`",
                            rule.name.name
                        ),
                        suggestion: Some(format!(
                            "declare `{kind} {name} Type` on the workflow first",
                            kind = if action == "complete" {
                                "output"
                            } else {
                                "failure"
                            }
                        )),
                    });
                    continue;
                }
                if let Some(contract_ty) = declared.get(name) {
                    validate_scalar_terminal_payload(
                        rule,
                        action,
                        name,
                        value,
                        contract_ty,
                        semantic,
                        binding_types,
                        known_roots,
                        diagnostics,
                    );
                }
                continue;
            }
        }
        // Header is `<name>` or (for `complete`) `<name> from <binding>` — the
        // bounded-type projection form (DR-0027), whose payload copies the binding.
        let Some(name) = rest.split('{').next().and_then(|header| {
            let mut parts = header.split_whitespace();
            match (parts.next(), parts.next(), parts.next()) {
                (Some(name), None, _) => Some(name),
                (Some(name), Some("from"), Some(binding))
                    if action == "complete" && is_identifier(binding) =>
                {
                    Some(name)
                }
                _ => None,
            }
        }) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!("rule `{}` has malformed `{action}` action", rule.name.name),
                suggestion: Some(format!(
                    "{action} a declared workflow terminal with a payload block"
                )),
            });
            continue;
        };
        if !declared.contains_key(name) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` {action}s unknown workflow terminal `{name}`",
                    rule.name.name
                ),
                suggestion: Some(format!(
                    "declare `{kind} {name} Type` on the workflow first",
                    kind = if action == "complete" {
                        "output"
                    } else {
                        "failure"
                    }
                )),
            });
            continue;
        }
        let Some(contract_ty) = declared.get(name) else {
            continue;
        };
        validate_workflow_terminal_payload(
            rule,
            action,
            name,
            contract_ty,
            semantic,
            binding_types,
            known_roots,
            diagnostics,
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn validate_workflow_terminal_payload(
    rule: &RuleDecl,
    action: &str,
    terminal_name: &str,
    contract_ty: &TypeSyntax,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some((_, _, body)) = workflow_terminal_blocks(&rule.body.text).into_iter().find(
        |(candidate_action, candidate_name, _)| {
            candidate_action == action && candidate_name == terminal_name
        },
    ) else {
        return;
    };
    let schema = match contract_ty {
        TypeSyntax::Ref { name } if semantic.schemas.class_exists(&name.name) => &name.name,
        TypeSyntax::Primitive { .. }
        | TypeSyntax::LiteralString { .. }
        | TypeSyntax::Union { .. } => {
            // A scalar (primitive/literal/union) contract takes a bare value, not
            // a field block.
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "workflow terminal `{terminal_name}` has a scalar payload contract but is given a field block"
                ),
                suggestion: Some(format!(
                    "write a bare scalar value: `{action} {terminal_name} <value>`"
                )),
            });
            return;
        }
        _ => {
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "workflow terminal `{terminal_name}` uses an unsupported payload contract type"
                ),
                suggestion: Some(
                    "declare the terminal payload as a class (field block) or a scalar type (number/string/bool)"
                        .to_owned(),
                ),
            });
            return;
        }
    };
    for assignment in collect_field_assignments(&body) {
        let (field, value) = match assignment {
            RecordFieldAssignment::Value { field, value } => (field, value),
            RecordFieldAssignment::Shorthand { field } => (field.clone(), field),
        };
        let line = format!("{field} {value}");
        validate_record_field(
            rule,
            &line,
            schema,
            semantic,
            binding_types,
            known_roots,
            diagnostics,
        );
    }
    validate_required_terminal_fields(rule, schema, terminal_name, &body, semantic, diagnostics);
}

/// Validates a bare-scalar terminal payload (`complete result 0.9` /
/// `fail error "reason"`) against a scalar output/failure contract. A class
/// contract is rejected (it needs a field block); a literal value is typechecked
/// against the primitive/enum/union contract, and a binding-expression value has
/// its roots and field path validated.
#[allow(clippy::too_many_arguments)]
fn validate_scalar_terminal_payload(
    rule: &RuleDecl,
    action: &str,
    terminal_name: &str,
    value: &str,
    contract_ty: &TypeSyntax,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if let TypeSyntax::Ref { name } = contract_ty {
        if semantic.schemas.class_exists(&name.name) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "workflow terminal `{terminal_name}` has a class payload contract `{}` but is given a bare scalar value",
                    name.name
                ),
                suggestion: Some(format!("write a field block: `{action} {terminal_name} {{}}`")),
            });
            return;
        }
    }
    if value.is_empty() {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("workflow terminal `{terminal_name}` is missing its scalar value"),
            suggestion: Some(format!("write `{action} {terminal_name} <value>`")),
        });
        return;
    }
    // A literal value is typechecked against the scalar contract; a binding
    // expression has its roots (and any field path) validated.
    validate_literal_assignment(
        rule,
        terminal_name,
        "value",
        contract_ty,
        value,
        semantic,
        diagnostics,
    );
    if let Some(root) = dangling_value_root(value, known_roots) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` has unknown binding `{root}` in `{action} {terminal_name}` value",
                rule.name.name
            ),
            suggestion: Some(
                "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                    .to_owned(),
            ),
        });
    } else if let Some((root, path)) = expression_path(value) {
        // Local scopes only. A terminal payload line is also walked by the
        // scoped field-path pass in `analyze_rule`, which is where an
        // invoke-derived binding resolves; making this one scope-aware too would
        // report the same read twice.
        check_field_path(
            rule,
            &root,
            &path,
            rule.body.span,
            SchemaScopes::local(&semantic.schemas),
            binding_types,
            diagnostics,
        );
    }
}

fn validate_required_terminal_fields(
    rule: &RuleDecl,
    schema: &str,
    terminal_name: &str,
    body: &str,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(schema_fields) = semantic.schemas.classes.get(schema) else {
        return;
    };
    let seen = collect_field_assignments(body)
        .into_iter()
        .map(|assignment| match assignment {
            RecordFieldAssignment::Value { field, .. }
            | RecordFieldAssignment::Shorthand { field } => field,
        })
        .collect::<BTreeSet<_>>();
    for (required, ty) in schema_fields {
        if seen.contains(required) || matches!(ty, TypeSyntax::Optional { .. }) {
            continue;
        }
        diagnostics.push(Diagnostic { related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "workflow terminal `{terminal_name}` is missing required field `{schema}.{required}`"
            ),
            suggestion: Some(format!("add `{required}` to the `{terminal_name}` payload")),
        });
    }
}

/// Maximum nesting depth of `after` blocks across `statements` (an `after` inside an
/// `after` is depth 2, …). Other nesting (`case`/`when`/handlers) is descended into so
/// an `after` buried inside them still counts, but only `after` increments the depth —
/// it is `after`-chaining specifically that `lint.deep_after_nesting` advises moving to
/// a `flow`. Computed from the body AST so prompt braces never confuse it.
fn max_after_depth(statements: &[body::BodyStmt]) -> usize {
    use body::BodyStmt;
    statements
        .iter()
        .map(|statement| match statement {
            BodyStmt::After(after) => 1 + max_after_depth(&after.body),
            BodyStmt::Case(case) => case
                .branches
                .iter()
                .map(|branch| max_after_depth(&branch.body))
                .max()
                .unwrap_or(0),
            _ => 0,
        })
        .max()
        .unwrap_or(0)
}

fn analyze_rule(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) -> IrRuleMetadata {
    // Statement-form gate: every body must parse into the body AST. Unknown
    // statements, malformed modifiers, and unclosed blocks are spanned
    // errors here rather than silent no-ops at lowering time.
    let (body_ast, body_diagnostics) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
    diagnostics.extend(body_diagnostics);
    let mut metadata = IrRuleMetadata {
        fact_reads: rule
            .whens
            .iter()
            .map(|when| fact_read_from_when(&when.text))
            .collect(),
        max_after_depth: max_after_depth(&body_ast.statements),
        ..IrRuleMetadata::default()
    };
    let mut seen_bindings = BTreeSet::new();
    let mut binding_types = BTreeMap::new();
    // Bindings whose schema is declared inside a CHILD workflow (`after <invoke>
    // succeeds/fails/reaches as x`). Their field paths resolve in that child's
    // index, not this one — see `SchemaScopes`.
    let mut foreign_schemas: BTreeMap<String, String> = BTreeMap::new();
    for when in &rule.whens {
        // A pattern that binds (`... as x`) but maps to no known readiness
        // form would otherwise be a silently-dead rule.
        let (pattern_text, _) = split_when_guard(&when.text);
        if binding_after_as(pattern_text).is_some()
            && binding_from_when(&when.text).is_none()
            && !pattern_text.ends_with(" is available")
        {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: when.span,
                message: format!(
                    "rule `{}` has unknown readiness pattern `{pattern_text}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "match a class (`when Class as x`) or a runtime fact (`when fact <name> as x`)"
                        .to_owned(),
                ),
            });
        }
        if let Some((binding, schema)) = binding_from_when(&when.text) {
            validate_binding_name(rule, &binding, when.span, diagnostics);
            if !schema.contains('.') && !semantic.schemas.class_exists(&schema) {
                let suggestion = match closest_name(&schema, semantic.schemas.classes.keys()) {
                    Some(candidate) => {
                        format!("did you mean `{candidate}`? otherwise declare `class {schema}`")
                    }
                    None => format!("declare `class {schema}` before matching it"),
                };
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: when.span,
                    message: format!("rule `{}` matches unknown class `{schema}`", rule.name.name),
                    suggestion: Some(suggestion),
                });
            }
            // The bare dotted form is the typed signal reaction
            // (spec/event-ingress.md): it requires a declared `signal`;
            // undeclared dotted facts keep the untyped `when fact` form.
            if schema.contains('.')
                && !pattern_text.trim_start().starts_with("fact ")
                && !semantic.schemas.events.contains(&schema)
            {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: when.span,
                    message: format!(
                        "rule `{}` reacts to undeclared signal `{schema}`",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "declare `signal {schema} {{ ... }}` for a typed reaction, or use `when fact {schema} as ...` for an untyped one"
                    )),
                });
            }
            binding_types.insert(binding, schema);
        }
    }
    let mut effect_payload_types = collect_effect_payload_types(rule, semantic, diagnostics);
    // `exec ... -> Schema as binding` is parsed from the AST (the command text
    // can itself contain `->`/` as `, so a text scan is unsafe), giving its
    // result the same after-binding type flow a named `coerce -> Schema` gets.
    collect_exec_payload_types(&body_ast.statements, semantic, &mut effect_payload_types);
    // Inline `decide … as <binding>` carries the synthesized
    // `decide.<rule>.<binding>` class (see `collect_inline_decide_schemas`), so
    // its result is `case`able / field-accessible like a named coerce result.
    collect_decide_payload_types(
        &body_ast.statements,
        &rule.name.name,
        &mut effect_payload_types,
    );
    collect_prompt_payload_types(&body_ast.statements, &mut effect_payload_types);
    // `redact … as <binding>` result carries the synthesized `redact.<rule>.<binding>`
    // projected class (see `collect_redact_schemas`), so access through it resolves
    // against the kept-only fields.
    collect_redact_payload_types(
        &body_ast.statements,
        &rule.name.name,
        &mut effect_payload_types,
    );
    for (binding, payload_type) in &effect_payload_types {
        if let IrType::Ref(schema) = payload_type {
            binding_types.insert(binding.clone(), schema.clone());
        }
    }
    // Effect-kind map for the `fails`-arm static narrowing (DR-0032 P3): the
    // failing effect's kind is always statically known at the read site. Scan
    // raw lines first (every single-line effect form), then the balanced
    // multi-line statements (a `coerce` whose arguments span lines carries its
    // binding on the closing line).
    // Bindings born from the std.vcs completion-valued verbs: the
    // succeeds-refusals below need the construct, not just the generic
    // CapabilityCall kind. Maps binding -> (verb, negative variant).
    let vcs_verb_bindings: BTreeMap<String, (&'static str, &'static str)> = rule
        .body
        .text
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            let (verb, negative) = if line.starts_with("promote ") {
                ("promote", "Conflicted")
            } else if line.starts_with("undo ") {
                ("undo", "Stranded")
            } else if line.starts_with("transport ") {
                ("transport", "Conflicted")
            } else {
                return None;
            };
            Some((binding_after_as(line)?, (verb, negative)))
        })
        .collect();
    let mut effect_binding_kinds: BTreeMap<String, IrEffectKind> = rule
        .body
        .text
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            // `exec` is not in parse_effect_line (whose other callers feed the
            // rule-metadata effect count); match it here for kind narrowing.
            if line.starts_with("exec ") {
                return Some((binding_after_as(line)?, IrEffectKind::ExecCommand));
            }
            let (kind, binding) = parse_effect_line(line)?;
            Some((binding?, kind))
        })
        .collect();
    for statement in effect_payload_statements(&rule.body.text) {
        if let Some((kind, Some(binding))) = parse_effect_line(statement.trim()) {
            effect_binding_kinds.insert(binding, kind);
        }
    }
    // `after <binding> <predicate> as <alias>`: the alias carries the
    // effect's completed payload type, so case dispatch and field access
    // through it type-check.
    for line in rule.body.text.lines() {
        let Some(rest) = line.trim().strip_prefix("after ") else {
            continue;
        };
        let mut words = rest.split_whitespace();
        let Some(binding) = words.next() else {
            continue;
        };
        let Some(predicate) = words.next() else {
            continue;
        };
        // Coordination ops are completion-valued: an `acquire` COMPLETES with
        // variant Held|Contended (counter `consume` with Ok|Over), so the
        // generic `succeeds` arm would fire on the negative outcome too — a
        // workflow proceeding "as if holding" on Contended. Reject `succeeds`
        // and force the variant vocabulary; `fails` (infra failures) and
        // `completes` (deliberate catch-all) stay legal.
        if predicate == "succeeds" {
            if let Some((verb, negative)) = vcs_verb_bindings.get(binding) {
                // std.vcs verbs are completion-valued: the generic
                // `succeeds` arm would fire on the refusal variant too — a
                // workflow proceeding as if the act landed. Same posture
                // as acquire; outcome-variant predicates are only ever
                // added alongside this refusal (DR-0052 Decision 0).
                let positive = if *verb == "promote" {
                    "promoted"
                } else {
                    "applied"
                };
                let negative_arm = negative.to_lowercase();
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` observes {verb} `{binding}` with `succeeds`, which also \
                         matches a {negative} outcome (the op completes either way)",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "use `after {binding} {positive}` / `after {binding} {negative_arm}` \
                         for the outcome variants, or `after {binding} completes` for any \
                         settled outcome"
                    )),
                });
            }
        }
        if predicate == "succeeds" {
            match effect_binding_kinds.get(binding) {
                Some(IrEffectKind::LeaseAcquire) => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` observes acquire `{binding}` with `succeeds`, which also \
                             matches a Contended outcome (the acquire op completes either way)",
                            rule.name.name
                        ),
                        suggestion: Some(format!(
                            "use `after {binding} held` / `after {binding} contended` for the \
                             outcome variants, or `after {binding} completes` for any settled \
                             outcome"
                        )),
                    });
                }
                Some(IrEffectKind::CounterConsume) => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` observes counter consume `{binding}` with `succeeds`, \
                             which also matches an Over outcome (the consume op completes \
                             either way)",
                            rule.name.name
                        ),
                        suggestion: Some(format!(
                            "use `after {binding} ok` / `after {binding} over` for the outcome \
                             variants, or `after {binding} completes` for any settled outcome"
                        )),
                    });
                }
                _ => {}
            }
        }
        // `after p reaches "<name>" as m` (Family C): the milestone name sits
        // between the predicate and `as`, so the alias lands one token later.
        // Type `m` to the child's declared milestone payload class.
        if predicate == "reaches" {
            let Some(quoted) = words.next() else {
                continue;
            };
            let milestone = quoted.trim_matches('"');
            let (Some("as"), Some(alias)) = (words.next(), words.next()) else {
                continue;
            };
            let alias = alias.trim_end_matches('{').trim();
            if alias.is_empty() {
                continue;
            }
            if let Some((workflow, class)) =
                milestone_payload_class(rule, binding, milestone, semantic)
            {
                if !class.is_empty() {
                    binding_types.insert(alias.to_owned(), class);
                    foreign_schemas.insert(alias.to_owned(), workflow);
                }
            }
            continue;
        }
        // `times out` is the only two-token predicate; skip its second word so
        // the `as <alias>` clause lines up.
        if predicate == "times" && words.next() != Some("out") {
            continue;
        }
        let (Some(keyword), Some(alias)) = (words.next(), words.next()) else {
            continue;
        };
        if keyword != "as" {
            continue;
        }
        let alias = alias.trim_end_matches('{').trim();
        if alias.is_empty() {
            continue;
        }
        // Bind the alias to the terminal payload schema that matches the
        // predicate, consistent with the case-tag payload schemas
        // (terminal_payload_schema_for_tag): `times out` -> `TerminalTimedOut`,
        // `cancelled` -> `TerminalCancelled`. Other predicates carry the
        // effect's completed payload schema.
        match predicate {
            "times" => {
                binding_types.insert(alias.to_owned(), "TerminalTimedOut".to_owned());
            }
            "cancelled" => {
                binding_types.insert(alias.to_owned(), "TerminalCancelled".to_owned());
            }
            // `completes` binds the terminal-union ENVELOPE, not the success
            // schema: the runtime delivers {tag, status, summary, …} for ANY
            // settled outcome, and the payload is read via `case o {
            // Completed as v => … }`. The old success-schema typing approved
            // reads that were null on every non-success terminal.
            "completes" => {
                binding_types.insert(alias.to_owned(), "TerminalOutcome".to_owned());
            }
            // DR-0032: the `fails` branch binds the EffectError family — the
            // base `{reason, summary, effect_id, run_id, kind}` plus per-kind
            // extras narrowed STATICALLY by the binding's effect kind (P3 /
            // DQ-2): exec adds `exit_code`; schema.coerce adds `error_class` +
            // optional `http_status`; agent.tell adds `error_class`. Every
            // other kind stays on the plain base.
            //
            // Exception (typed invoke failure): when this is an invoke binding
            // whose child declares a SOLE, shared top-level FAILURE contract class,
            // bind the alias to THAT class so `f.<field>` type-checks against the
            // child's declared failure shape (the runtime merges the child payload
            // under the base). Invoke bindings with a child-local/unresolvable
            // failure class keep the `TerminalFailed` base.
            "fails" => {
                if let Some((workflow, class)) = invoke_failure_class(rule, binding, semantic) {
                    binding_types.insert(alias.to_owned(), class);
                    foreign_schemas.insert(alias.to_owned(), workflow);
                } else {
                    let schema = match effect_binding_kinds.get(binding) {
                        Some(IrEffectKind::ExecCommand) => "TerminalFailedExec",
                        Some(IrEffectKind::SchemaCoerce) => "TerminalFailedCoerce",
                        Some(IrEffectKind::AgentTell) => "TerminalFailedTell",
                        _ => "TerminalFailed",
                    };
                    binding_types.insert(alias.to_owned(), schema.to_owned());
                }
            }
            _ => {
                if let Some(IrType::Ref(schema)) = effect_payload_types.get(binding) {
                    binding_types.insert(alias.to_owned(), schema.clone());
                } else if let Some((workflow, class)) = invoke_output_class(rule, binding, semantic)
                {
                    // Typed invoke result: `after <child> succeeds/completes as r`
                    // binds r to the child workflow's OUTPUT contract class, so
                    // `r.<field>` type-checks. (The runtime already carries the
                    // child's terminal payload into this binding.) The `fails` arm
                    // above keeps the DR-0032 failure base.
                    binding_types.insert(alias.to_owned(), class);
                    foreign_schemas.insert(alias.to_owned(), workflow);
                }
            }
        }
    }
    for when in &rule.whens {
        if let (_, Some(guard)) = split_when_guard(&when.text) {
            validate_expression(rule, guard, semantic, &binding_types, "guard", diagnostics);
            validate_known_field_paths(rule, guard, semantic, &binding_types, diagnostics);
            if let Some(expr) = lower_expression(guard, when.span) {
                metadata
                    .projection_reads
                    .extend(collect_projection_reads(&expr.expr));
            }
        }
        validate_availability_when(rule, &when.text, semantic, &binding_types, diagnostics);
    }
    validate_case_blocks(rule, semantic, &binding_types, diagnostics);
    metadata.case_branches =
        collect_rule_case_metadata(rule, semantic, &binding_types, diagnostics);
    let terminal_metadata = collect_terminal_case_metadata(
        rule,
        semantic,
        &binding_types,
        &effect_payload_types,
        diagnostics,
    );
    // Complete value-position root set: typed bindings plus every binding NAME
    // the body introduces (AST-collected, so multi-line-prompt `tell`/`exec`
    // results and `case` payloads are covered, which `binding_types` omits).
    let mut known_roots: BTreeSet<String> = binding_types.keys().cloned().collect();
    collect_all_binding_names(&body_ast.statements, &mut known_roots);
    validate_record_blocks(rule, semantic, &binding_types, &known_roots, diagnostics);
    validate_effect_payloads(rule, semantic, &binding_types, &known_roots, diagnostics);
    validate_effect_field_roots(rule, &body_ast.statements, &known_roots, diagnostics);
    validate_emit_signal_declarations(
        rule,
        &body_ast.statements,
        &semantic.schemas.events,
        diagnostics,
    );
    validate_workflow_invocations(rule, semantic, &binding_types, &known_roots, diagnostics);
    validate_milestone_statements(rule, semantic, diagnostics);
    let mut block_stack: Vec<BlockFrame> = Vec::new();
    let mut misplaced_effect_bindings = BTreeSet::new();
    seed_ast_only_effect_bindings(&body_ast.statements, &mut seen_bindings, &mut binding_types);
    validate_body_effect_operands(
        rule,
        &body_ast.statements,
        semantic,
        &binding_types,
        diagnostics,
    );
    validate_coordination_discipline(rule, &body_ast.statements, diagnostics);
    // `redact <source> keep [..] as <out>`: the source must resolve to a known
    // schema and every kept field must exist on it (fail-closed).
    validate_redactions(
        rule,
        &body_ast.statements,
        semantic,
        &binding_types,
        diagnostics,
    );
    // Family B read-narrowing: a presence-conditioned field is readable only inside a
    // matching `case <root>.<disc>` arm (starts with nothing allowed at the rule top).
    validate_conditioned_field_reads(
        rule,
        &body_ast.statements,
        semantic,
        &binding_types,
        &BTreeSet::new(),
        diagnostics,
    );
    let mut anonymous_effects = 0usize;
    let mut record_depth = 0i32;

    for raw_line in rule.body.text.lines() {
        let line = raw_line.trim();
        if line.is_empty() {
            continue;
        }

        if record_depth > 0 {
            record_depth += brace_delta(line);
            continue;
        }

        if let Some(binding) = binding_after_multiline_string_end(line) {
            misplaced_effect_bindings.insert(binding.clone());
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` places effect binding `{binding}` after a multiline string delimiter",
                    rule.name.name
                ),
                suggestion: Some(format!(
                    "move `as {binding}` onto the effect line, before the multiline string body"
                )),
            });
            continue;
        }
        validate_rule_prompt_content_type_annotation(rule, line, diagnostics);

        if line.starts_with('}') {
            block_stack.pop();
            continue;
        }

        if line.starts_with("case ") || (!line.starts_with("after ") && is_case_branch_start(line))
        {
            validate_known_field_paths_scoped(
                rule,
                line,
                semantic,
                &binding_types,
                &foreign_schemas,
                diagnostics,
            );
            continue;
        }

        let active_afters = after_scopes(&block_stack);
        validate_binding_uses(rule, line, &seen_bindings, &active_afters, diagnostics);
        validate_known_field_paths_scoped(
            rule,
            line,
            semantic,
            &binding_types,
            &foreign_schemas,
            diagnostics,
        );

        if let Some(binding) = parse_consume_line(line) {
            match binding_types.get(&binding) {
                Some(schema) => metadata.fact_consumes.push(format!("schema:{schema}")),
                None => diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` consumes unknown fact binding `{binding}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "consume a binding introduced by a `when Class as binding` clause"
                            .to_owned(),
                    ),
                }),
            }
            if !line.contains("->") {
                continue;
            }
        }

        if line.starts_with("after ") {
            if let Some(alias) = binding_after_as(line) {
                validate_binding_name(rule, &alias, rule.body.span, diagnostics);
            }
            match parse_after_line(line) {
                Some((binding, predicate)) => {
                    if !seen_bindings.contains(&binding) {
                        let suggestion = if misplaced_effect_bindings.contains(&binding) {
                            format!(
                                "move `as {binding}` onto the effect line before the multiline string"
                            )
                        } else {
                            format!("create an effect with `as {binding}` before the `after` block")
                        };
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: rule.body.span,
                            message: format!(
                                "rule `{}` has `after` block for unknown effect binding `{binding}`",
                                rule.name.name
                            ),
                            suggestion: Some(suggestion),
                        });
                    }
                    block_stack.push(BlockFrame::After { binding, predicate });
                }
                None => {
                    diagnostics.push(Diagnostic { related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` has unsupported `after` dependency predicate",
                            rule.name.name
                        ),
                        suggestion: Some(
                            "use `after name succeeds`, `after name fails`, `after name completes`, `after name times out`, or `after name cancelled`"
                                .to_owned(),
                        ),
                    });
                }
            }
            continue;
        }

        if let Some((schema, _)) = parse_record_start(line) {
            if is_observer_only_schema(&schema) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` cannot record kernel-owned terminal schema `{schema}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "the terminal family (`TerminalFailed`/`TerminalTimedOut`/`TerminalCancelled`) is produced only by the kernel; to fail this workflow use `fail <failure> { ... }`, and to react to an effect terminal use `after <effect> fails/times out/cancels as f`"
                            .to_owned(),
                    ),
                });
            } else if !semantic.schemas.class_exists(&schema) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!("rule `{}` records unknown class `{schema}`", rule.name.name),
                    suggestion: Some(format!("declare `class {schema}` before recording it")),
                });
            }
            metadata.fact_writes.push(format!("schema:{schema}"));
            record_depth = brace_delta(line).max(1);
            continue;
        }

        if let Some((kind, binding)) = parse_effect_line(line) {
            validate_agent_tell_target(
                rule,
                line,
                &kind,
                semantic,
                &binding_types,
                &known_roots,
                diagnostics,
            );
            anonymous_effects += 1;
            let id = binding
                .clone()
                .unwrap_or_else(|| format!("effect{anonymous_effects}"));
            if let Some(binding) = &binding {
                validate_binding_name(rule, binding, rule.body.span, diagnostics);
                seen_bindings.insert(binding.clone());
                if let Some(schema) = effect_binding_schema(line, &kind, semantic) {
                    binding_types.insert(binding.clone(), schema);
                }
            }
            for (upstream, predicate) in after_scopes(&block_stack) {
                metadata.dependencies.push(IrEffectDependency {
                    upstream,
                    predicate,
                    downstream: id.clone(),
                });
            }
            let idempotency_key = effect_idempotency_key(&rule.name.name, &id, &kind, &binding);
            metadata.effects.push(IrEffectNode {
                id,
                kind,
                binding,
                required_capabilities: parse_required_capabilities(line),
                construct_use: None,
                idempotency_key,
                span: rule.body.span,
                timeout_seconds: None,
                // The line-scanner result is overwritten by collect_effects_from_ast
                // below (which carries the real grants); empty here is fine.
                access_grants: Vec::new(),
                turn_skills: Vec::new(),
                on_stream: None,
                selection_source: None,
                transport_onto: None,
                resource: None,
                agent: None,
                coerce_target: None,
                workflow_target: None,
                endorsed: false,
                declassified: false,
                selected_by: None,
                exec_target: None,
            });
        }
    }

    let (ast_effects, ast_dependencies) =
        collect_effects_from_ast(&body_ast.statements, &rule.name.name);
    metadata.effects = ast_effects;
    metadata.dependencies = ast_dependencies;

    // `exec ... -> each Schema` produces one `Schema` fact per stream element
    // (spec/json-ingestion.md) — a fact write for liveness and effect-graph
    // analysis, like `record`.
    push_ingest_fact_writes(&body_ast.statements, &mut metadata.fact_writes);

    metadata.fact_reads.sort();
    metadata.fact_reads.dedup();
    sort_projection_reads(&mut metadata.projection_reads);
    metadata.fact_writes.sort();
    metadata.fact_writes.dedup();
    metadata.fact_consumes.sort();
    metadata.fact_consumes.dedup();
    metadata.terminal_outputs = terminal_metadata.outputs;
    metadata.terminal_branches = terminal_metadata.branches;
    // DR-0044 Q5 / P1: an after-arm `case … where <guard>` guard query observes
    // live fact state at continuation time — the same firing-decision implicit
    // flow as a `when`-guard query (the IFC checker reads `projection_reads` to
    // taint guard-gated egresses). Fold both case families' arm guards into
    // `projection_reads` so the analysis sees them; the `when`-guard queries were
    // added above.
    for branch in &metadata.case_branches {
        if let Some(guard) = &branch.guard {
            metadata
                .projection_reads
                .extend(collect_projection_reads(&guard.expr));
        }
    }
    for branch in &metadata.terminal_branches {
        if let Some(guard) = &branch.guard {
            metadata
                .projection_reads
                .extend(collect_projection_reads(&guard.expr));
        }
    }
    sort_projection_reads(&mut metadata.projection_reads);
    // DR-0043 Decision 7 obligation 2: the lapse arm is not in `rule.body.text`
    // (that is the HOLDS variant), so it is checked here, once, with the binding
    // environment the body loop just built.
    if let Some(region) = semantic.regions.get(&rule.name.name) {
        validate_lapse_arm(
            rule,
            region,
            semantic,
            &binding_types,
            &foreign_schemas,
            &effect_payload_types,
            diagnostics,
        );
    }
    collect_terminal_complete_bindings(&body_ast.statements, &mut metadata.terminal_completes);
    metadata.terminal_completes.sort();
    metadata.terminal_completes.dedup();
    collect_redaction_metadata(
        &body_ast.statements,
        &binding_types,
        &mut metadata.redactions,
    );
    collect_bounded_egresses(
        &body_ast.statements,
        &binding_types,
        &mut metadata.bounded_egresses,
    );
    let mut egress_reads = Vec::new();
    collect_egress_payload_reads(&body_ast.statements, &mut egress_reads);
    for (sink, roots) in egress_reads {
        metadata
            .egress_payload_reads
            .entry(sink)
            .or_default()
            .extend(roots);
    }
    collect_complete_field_reads(&body_ast.statements, &mut metadata.complete_field_reads);
    collect_record_field_reads(&body_ast.statements, &mut metadata.record_field_reads);
    collect_milestone_field_reads(&body_ast.statements, &mut metadata.milestone_field_reads);
    collect_crossing_roots(
        &body_ast.statements,
        &mut metadata.declassified_roots,
        &mut metadata.endorsed_roots,
        &mut metadata.endorsed_claim_items,
    );
    collect_provenance_metadata(
        &body_ast.statements,
        &mut metadata.coerce_input_roots,
        &mut metadata.after_aliases,
    );
    collect_egress_case_influence(
        &body_ast.statements,
        &mut Vec::new(),
        &mut metadata.egress_case_influence,
    );
    // Redaction closure over marked roots (redact ∘ marked-crossing): a
    // `redact <marked-output> keep […] as out` projection is still the
    // crossing's carrier — a redaction can only NARROW what the marked
    // coercion released, and the kept fields are additionally held to their
    // per-field schema labels by the redact refinement. Fixpoint so
    // redactions of redactions chain.
    loop {
        let mut changed = false;
        for redaction in &metadata.redactions {
            if metadata.declassified_roots.contains(&redaction.source)
                && metadata
                    .declassified_roots
                    .insert(redaction.binding.clone())
            {
                changed = true;
            }
            if metadata.endorsed_roots.contains(&redaction.source)
                && metadata.endorsed_roots.insert(redaction.binding.clone())
            {
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    metadata
}

/// Collect, per egress sink, the binding roots of every enclosing `case`
/// scrutinee (DR-0046 selector influence). The active-scrutinee stack is
/// threaded through nesting; each egress statement records the union of the
/// stack at its position, keyed exactly like `collect_egress_payload_reads`.
fn collect_egress_case_influence(
    statements: &[body::BodyStmt],
    active: &mut Vec<BTreeSet<String>>,
    out: &mut BTreeMap<String, BTreeSet<String>>,
) {
    let record_sink = |sink: String,
                       active: &[BTreeSet<String>],
                       out: &mut BTreeMap<String, BTreeSet<String>>| {
        if active.is_empty() {
            return;
        }
        let entry = out.entry(sink).or_default();
        for roots in active {
            entry.extend(roots.iter().cloned());
        }
    };
    for statement in statements {
        match statement {
            body::BodyStmt::Terminal(terminal) if terminal.kind == body::TerminalKind::Complete => {
                record_sink(terminal.name.clone(), active, out);
            }
            body::BodyStmt::Record(record) => {
                record_sink(format!("fact:{}", record.schema), active, out);
            }
            body::BodyStmt::Done {
                replacement: Some(record),
                ..
            } => {
                record_sink(format!("fact:{}", record.schema), active, out);
            }
            body::BodyStmt::Milestone { name, .. } => {
                record_sink(format!("milestone:{name}"), active, out);
            }
            body::BodyStmt::Effect(effect) => match &effect.kind {
                body::BodyEffectKind::ConstructCapabilityCall {
                    keyword, fields, ..
                } if keyword == "send" => {
                    if let Some(channel) = fields
                        .iter()
                        .find(|field| field.name == "channel")
                        .map(|field| field.source.clone())
                    {
                        record_sink(channel, active, out);
                    }
                }
                body::BodyEffectKind::FileWrite { store, .. } => {
                    record_sink(store.clone(), active, out);
                }
                _ => {}
            },
            body::BodyStmt::After(after) => {
                collect_egress_case_influence(&after.body, active, out);
            }
            body::BodyStmt::Case(case) => {
                let mut roots = BTreeSet::new();
                if let Ok(expr) = parse_expression(&case.scrutinee) {
                    collect_expr_binding_roots(&expr, &mut roots);
                } else {
                    collect_template_binding_roots(&case.scrutinee, &mut roots);
                }
                active.push(roots);
                for branch in &case.branches {
                    collect_egress_case_influence(&branch.body, active, out);
                }
                active.pop();
            }
            _ => {}
        }
    }
}

/// Collect the raw structure input-side provenance narrowing resolves over:
/// each coerce's argument-expression binding roots (template-scan fallback for
/// unparseable sources, same discipline as `send_payload_reads`), and the
/// `after … succeeds|completes as` alias map.
fn collect_provenance_metadata(
    statements: &[body::BodyStmt],
    coerce_input_roots: &mut BTreeMap<String, BTreeSet<String>>,
    after_aliases: &mut BTreeMap<String, String>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let body::BodyEffectKind::Coerce { args, .. } = &effect.kind {
                    if let Some(binding) = &effect.binding {
                        let mut roots = BTreeSet::new();
                        for arg in args {
                            if let Ok(expr) = parse_expression(arg) {
                                collect_expr_binding_roots(&expr, &mut roots);
                            } else {
                                collect_template_binding_roots(arg, &mut roots);
                            }
                        }
                        coerce_input_roots
                            .entry(binding.clone())
                            .or_default()
                            .extend(roots);
                    }
                }
            }
            body::BodyStmt::After(after) => {
                if matches!(
                    after.predicate,
                    body::AfterPredicate::Succeeds | body::AfterPredicate::Completes
                ) {
                    if let Some(alias) = &after.alias {
                        after_aliases.insert(alias.clone(), after.binding.clone());
                    }
                }
                collect_provenance_metadata(&after.body, coerce_input_roots, after_aliases);
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_provenance_metadata(&branch.body, coerce_input_roots, after_aliases);
                }
            }
            _ => {}
        }
    }
}

/// Collect the output roots of marked crossings (`coerce … declassified` /
/// `coerce … endorsed`, DR-0027 I-IFC3): each marked coerce's binding, plus the
/// aliases its `after <binding> succeeds|completes as <alias>` branches bind —
/// the names an egress payload actually references. Two passes so an `after`
/// textually preceding nothing is impossible to miss; aliases of aliases cannot
/// occur (an `after` subject is always an effect binding).
fn collect_crossing_roots(
    statements: &[body::BodyStmt],
    declassified: &mut BTreeSet<String>,
    endorsed: &mut BTreeSet<String>,
    claim_items: &mut BTreeSet<String>,
) {
    fn collect_marked(
        statements: &[body::BodyStmt],
        declassified: &mut BTreeSet<String>,
        endorsed: &mut BTreeSet<String>,
        claim_items: &mut BTreeSet<String>,
    ) {
        for statement in statements {
            match statement {
                body::BodyStmt::Effect(effect) => {
                    if let body::BodyEffectKind::Coerce {
                        declassified: is_declassified,
                        endorsed: is_endorsed,
                        ..
                    } = &effect.kind
                    {
                        if let Some(binding) = &effect.binding {
                            if *is_declassified {
                                declassified.insert(binding.clone());
                            }
                            if *is_endorsed {
                                endorsed.insert(binding.clone());
                            }
                        }
                    }
                    // DR-0051 §2: an endorsed claim is a marked crossing of the
                    // same kind, so its output binding joins `endorsed_roots`
                    // and every downstream check — the narrowing, the grant
                    // consultation, NMIF-on-the-selector — applies unchanged.
                    if let body::BodyEffectKind::TrackerClaim {
                        endorsed: is_endorsed,
                        item,
                        ..
                    } = &effect.kind
                    {
                        if *is_endorsed {
                            // The crossed value is the *claimed item*, not the
                            // claim's `as` binding: `claim v as hold` binds a
                            // lease in `hold`, while the decision the program
                            // goes on to read lives in `v`. Marking the lease
                            // would mark a handle nothing reads.
                            endorsed.insert(item.clone());
                            claim_items.insert(item.clone());
                        }
                    }
                }
                body::BodyStmt::After(after) => {
                    collect_marked(&after.body, declassified, endorsed, claim_items)
                }
                body::BodyStmt::Case(case) => {
                    for branch in &case.branches {
                        collect_marked(&branch.body, declassified, endorsed, claim_items);
                    }
                }
                _ => {}
            }
        }
    }
    fn collect_aliases(
        statements: &[body::BodyStmt],
        declassified: &mut BTreeSet<String>,
        endorsed: &mut BTreeSet<String>,
    ) {
        for statement in statements {
            match statement {
                body::BodyStmt::After(after) => {
                    if matches!(
                        after.predicate,
                        body::AfterPredicate::Succeeds | body::AfterPredicate::Completes
                    ) {
                        if let Some(alias) = &after.alias {
                            if declassified.contains(&after.binding) {
                                declassified.insert(alias.clone());
                            }
                            if endorsed.contains(&after.binding) {
                                endorsed.insert(alias.clone());
                            }
                        }
                    }
                    collect_aliases(&after.body, declassified, endorsed);
                }
                body::BodyStmt::Case(case) => {
                    for branch in &case.branches {
                        collect_aliases(&branch.body, declassified, endorsed);
                    }
                }
                _ => {}
            }
        }
    }
    collect_marked(statements, declassified, endorsed, claim_items);
    // Aliases can nest under other afters, so run the alias pass to a fixpoint
    // over the (small) statement tree: one extra pass suffices in practice, but
    // loop until stable so deep nesting cannot order-skip an alias.
    loop {
        let before = (declassified.len(), endorsed.len());
        collect_aliases(statements, declassified, endorsed);
        if (declassified.len(), endorsed.len()) == before {
            break;
        }
    }
}

/// For each `complete <binding> { field: <expr>, … }` egress in a rule body
/// (recursing into nested blocks), the binding roots EACH result field references,
/// as `binding -> field -> {roots}`. A `Shorthand` field (`complete result from src
/// { f }`) resolves to the terminal's `from` binding. Unlike
/// `collect_egress_payload_reads` (which joins a sink's fields), this keeps fields
/// separate so the IFC engine can compute a per-field flow signature (DR-0030 X2
/// v2). Union across branches (a field completed in two arms references the union).
fn collect_complete_field_reads(
    statements: &[body::BodyStmt],
    out: &mut BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Terminal(terminal) if terminal.kind == body::TerminalKind::Complete => {
                let per_field = out.entry(terminal.name.clone()).or_default();
                for field in &terminal.fields {
                    let mut roots = BTreeSet::new();
                    match &field.value {
                        body::FieldValue::Shorthand => {
                            if let Some(root) = &terminal.from {
                                roots.insert(root.clone());
                            }
                        }
                        body::FieldValue::Expr { expr, .. } => {
                            collect_expr_binding_roots(expr, &mut roots)
                        }
                        body::FieldValue::Nested { fields, .. } => collect_payload_field_roots(
                            fields,
                            terminal.from.as_deref(),
                            &mut roots,
                        ),
                    }
                    per_field
                        .entry(field.name.clone())
                        .or_default()
                        .extend(roots);
                }
            }
            body::BodyStmt::After(after) => collect_complete_field_reads(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_complete_field_reads(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// For each `emit milestone "<name>" { field: <expr>, … }` egress in a rule body
/// (recursing into nested blocks), collect the binding roots EACH milestone field
/// references. This mirrors `collect_complete_field_reads`: the IFC checker uses it
/// to expose and gate a child-to-parent milestone payload with a per-field flow
/// signature (D3′).
fn collect_milestone_field_reads(
    statements: &[body::BodyStmt],
    out: &mut BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Milestone { name, fields, .. } => {
                let per_field = out.entry(name.clone()).or_default();
                for field in fields {
                    let mut roots = BTreeSet::new();
                    match &field.value {
                        body::FieldValue::Shorthand => {}
                        body::FieldValue::Expr { expr, .. } => {
                            collect_expr_binding_roots(expr, &mut roots)
                        }
                        body::FieldValue::Nested { fields, .. } => {
                            collect_payload_field_roots(fields, None, &mut roots)
                        }
                    }
                    per_field
                        .entry(field.name.clone())
                        .or_default()
                        .extend(roots);
                }
            }
            body::BodyStmt::After(after) => collect_milestone_field_reads(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_milestone_field_reads(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// Collects the `redact <source> keep [..] as <out>` projections of a rule body
/// (recursing into nested blocks) as IFC value-flow metadata, preserving body
/// order so a chained redaction's source resolves against the earlier projection.
/// `binding_types` (the rule's fully-resolved binding -> schema map, including
/// redaction outputs via their synthetic class) supplies each source's schema so
/// the IFC engine can derive the projection's per-field label.
fn collect_redaction_metadata(
    statements: &[body::BodyStmt],
    binding_types: &BTreeMap<String, String>,
    out: &mut Vec<IrRedaction>,
) {
    let mut redacts = Vec::new();
    collect_redact_effects(statements, &mut redacts);
    for (source, keep, binding, _span) in redacts {
        out.push(IrRedaction {
            source: source.to_owned(),
            keep: keep.to_vec(),
            binding: binding.to_owned(),
            source_schema: binding_types.get(source).cloned(),
        });
    }
}

/// Collect the bounded-type projection egresses (`record <T> from <src>`) of a rule
/// body (recursing into nested blocks). A `record T from src` keeps exactly `T`'s
/// declared fields, copied from `src`, so the IFC engine can govern it by the kept
/// fields' per-field labels (sourced from `src`'s schema) — the "bounded-type"
/// auto-redaction reading. Only recorded when the source schema resolves and the
/// target type is declared; otherwise the egress stays conservative.
/// Records a bounded-type projection egress for a PURE `from` projection — a
/// `from <src>` egress every field of which is a shorthand copy of `src.<name>`.
/// The runtime materializes exactly these fields, so the kept set is their names,
/// governed by `src`'s schema per-field labels. `None` source schema, no `from`, or
/// any explicit value field → not a clean projection, so it stays conservative
/// (handled by the whole-read join). `sink` is the engine sink string
/// (`fact:<Schema>` for a record, the completed binding for a `complete`).
fn push_bounded_projection(
    from: Option<&str>,
    fields: &[body::FieldAssign],
    sink: String,
    binding_types: &BTreeMap<String, String>,
    out: &mut Vec<IrBoundedEgress>,
) {
    let Some(source_schema) = from.and_then(|src| binding_types.get(src)) else {
        return;
    };
    if fields.is_empty()
        || !fields
            .iter()
            .all(|field| matches!(field.value, body::FieldValue::Shorthand))
    {
        return;
    }
    out.push(IrBoundedEgress {
        sink,
        source_schema: source_schema.clone(),
        keep: fields.iter().map(|field| field.name.clone()).collect(),
    });
}

fn push_bounded_record(
    record: &body::RecordStmt,
    binding_types: &BTreeMap<String, String>,
    out: &mut Vec<IrBoundedEgress>,
) {
    push_bounded_projection(
        record.from.as_deref(),
        &record.fields,
        format!("fact:{}", record.schema),
        binding_types,
        out,
    );
}

fn collect_bounded_egresses(
    statements: &[body::BodyStmt],
    binding_types: &BTreeMap<String, String>,
    out: &mut Vec<IrBoundedEgress>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Record(record) => push_bounded_record(record, binding_types, out),
            body::BodyStmt::Done {
                replacement: Some(record),
                ..
            } => push_bounded_record(record, binding_types, out),
            // `complete <T> from <src> { … }`: bounded-type projection to the invoker.
            // The engine sink for a complete is the completed binding (its name).
            body::BodyStmt::Terminal(terminal)
                if terminal.kind == body::TerminalKind::Complete && terminal.from.is_some() =>
            {
                push_bounded_projection(
                    terminal.from.as_deref(),
                    &terminal.fields,
                    terminal.name.clone(),
                    binding_types,
                    out,
                );
            }
            body::BodyStmt::After(after) => {
                collect_bounded_egresses(&after.body, binding_types, out)
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_bounded_egresses(&branch.body, binding_types, out);
                }
            }
            _ => {}
        }
    }
}

/// Collect EVERY binding root referenced by an expression, for the information-flow
/// value-flow engine. SOUNDNESS: a missed reference under-approximates a payload's
/// sources — so this over-collects (an over-collected name that is not a relevant
/// binding contributes nothing downstream). It walks every `Expr` variant and, for
/// string literals, extracts `{{ … }}` interpolation roots (those refs live as raw
/// text inside the literal, not as structured nodes). A bare identifier parses as
/// `Literal(Ident)`, a dotted ref as `Path` — both are roots.
fn collect_expr_binding_roots(expr: &Expr, out: &mut BTreeSet<String>) {
    match expr {
        Expr::Literal(ExprLiteral::String(text)) => collect_template_binding_roots(text, out),
        Expr::Literal(ExprLiteral::Ident(name)) => {
            out.insert(name.clone());
        }
        Expr::Literal(ExprLiteral::Number(_) | ExprLiteral::Bool(_) | ExprLiteral::Null) => {}
        Expr::Path(segments) => {
            if let Some(root) = segments.first() {
                out.insert(root.clone());
            }
        }
        Expr::Index { target, key } => {
            collect_expr_binding_roots(target, out);
            collect_expr_binding_roots(key, out);
        }
        Expr::Array(items) => {
            for item in items {
                collect_expr_binding_roots(item, out);
            }
        }
        Expr::Object(fields) => {
            for field in fields {
                collect_expr_binding_roots(&field.value, out);
            }
        }
        Expr::Unary { expr, .. } => collect_expr_binding_roots(expr, out),
        Expr::Binary { left, right, .. } => {
            collect_expr_binding_roots(left, out);
            collect_expr_binding_roots(right, out);
        }
        Expr::Call { args, .. } => {
            for arg in args {
                collect_expr_binding_roots(arg, out);
            }
        }
        Expr::Query { head, guard, .. } => {
            out.insert(head.clone());
            if let Some(guard) = guard {
                collect_expr_binding_roots(guard, out);
            }
        }
    }
}

/// Collect every binding root inside `{{ … }}` interpolations of a string. Unlike
/// `interpolation_roots` (first root per interpolation), value-flow needs EVERY
/// root, so `{{ a.b + c.d }}` yields both `a` and `c`. Each interpolation body is
/// parsed and walked; an unparseable body falls back to a conservative identifier
/// scan (over-collection is sound).
fn collect_template_binding_roots(text: &str, out: &mut BTreeSet<String>) {
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        let after_open = &rest[open + 2..];
        let Some(close) = after_open.find("}}") else {
            break;
        };
        let body = after_open[..close].trim();
        if let Ok(expr) = parse_expression(body) {
            collect_expr_binding_roots(&expr, out);
        } else {
            for token in body.split(|ch: char| !ch.is_alphanumeric() && ch != '_') {
                if token
                    .as_bytes()
                    .first()
                    .is_some_and(|byte| is_ident_start(*byte))
                {
                    out.insert(token.to_owned());
                }
            }
        }
        rest = &after_open[close + 2..];
    }
}

/// Collect the binding roots a payload field list references, threading the
/// enclosing `from <binding>` source so a `Shorthand` field resolves to it.
fn collect_payload_field_roots(
    fields: &[body::FieldAssign],
    from_binding: Option<&str>,
    out: &mut BTreeSet<String>,
) {
    for field in fields {
        match &field.value {
            body::FieldValue::Shorthand => {
                if let Some(root) = from_binding {
                    out.insert(root.to_owned());
                }
            }
            body::FieldValue::Expr { expr, .. } => collect_expr_binding_roots(expr, out),
            body::FieldValue::Nested { fields, .. } => {
                collect_payload_field_roots(fields, from_binding, out)
            }
        }
    }
}

/// For each egress sink in a rule body (recursing into nested blocks), the set of
/// binding roots its payload references, keyed by the sink string the IFC engine
/// uses: a `complete <binding>` by its binding, a `record <Schema>` by
/// `fact:<Schema>`. Surfaced so the engine can recognize a FULLY-REDACTED egress —
/// one whose payload references only redaction outputs (and constants) — and
/// govern it by the projection's per-field label instead of the rule's whole read
/// set. A `record <Schema> from <binding>` references that `from` binding too (its
/// fields are copied). A sink with no recorded entry references nothing resolvable.
fn collect_egress_payload_reads(
    statements: &[body::BodyStmt],
    out: &mut Vec<(String, BTreeSet<String>)>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Terminal(terminal) if terminal.kind == body::TerminalKind::Complete => {
                let mut roots = BTreeSet::new();
                collect_payload_field_roots(&terminal.fields, None, &mut roots);
                // A bare scalar payload's value expression is the whole egress
                // value; its binding roots must join the sink's label (fail-closed
                // — otherwise `complete result secret.value` would under-report).
                if let Some(body::FieldValue::Expr { expr, .. }) = &terminal.scalar {
                    collect_expr_binding_roots(expr, &mut roots);
                }
                out.push((terminal.name.clone(), roots));
            }
            body::BodyStmt::Record(record) => out.push(record_payload_reads(record)),
            // `done <b> -> record <Schema> { … }` is also a record egress.
            body::BodyStmt::Done {
                replacement: Some(record),
                ..
            } => out.push(record_payload_reads(record)),
            body::BodyStmt::Milestone { name, fields, .. } => {
                let mut roots = BTreeSet::new();
                collect_payload_field_roots(fields, None, &mut roots);
                out.push((format!("milestone:{name}"), roots));
            }
            // `send via <channel> { text … }` egresses to the channel; its payload
            // fields (text/markdown/thread_id) are construct-use source text. Keyed by
            // the channel (the engine's send sink, per `resource_for_body`). A
            // `write … to <store>` is likewise an egress to the store: its body
            // AND path expressions are the payload (a path can encode data too),
            // keyed by the store handle.
            body::BodyStmt::Effect(effect) => match &effect.kind {
                body::BodyEffectKind::ConstructCapabilityCall {
                    keyword, fields, ..
                } if keyword == "send" => {
                    if let Some(reads) = send_payload_reads(fields) {
                        out.push(reads);
                    }
                }
                body::BodyEffectKind::FileWrite {
                    store, path, body, ..
                } => {
                    let mut roots = BTreeSet::new();
                    for source in [path, body] {
                        if let Ok(expr) = parse_expression(source) {
                            collect_expr_binding_roots(&expr, &mut roots);
                        } else {
                            collect_template_binding_roots(source, &mut roots);
                        }
                    }
                    out.push((store.clone(), roots));
                }
                _ => {}
            },
            body::BodyStmt::After(after) => collect_egress_payload_reads(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_egress_payload_reads(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// The channel sink key and the binding roots a `send` payload references. The
/// payload fields (`text`/`markdown`/`thread_id`) carry expression SOURCE TEXT, so
/// each is parsed and walked (a string literal's `{{ … }}` interpolations count);
/// the `channel` field names the sink. `None` if no channel is present.
fn send_payload_reads(fields: &[body::ConstructUseField]) -> Option<(String, BTreeSet<String>)> {
    let channel = fields
        .iter()
        .find(|field| field.name == "channel")
        .map(|field| field.source.clone())?;
    let mut roots = BTreeSet::new();
    for field in fields.iter().filter(|field| field.name != "channel") {
        if let Ok(expr) = parse_expression(&field.source) {
            collect_expr_binding_roots(&expr, &mut roots);
        } else {
            // Unparseable source: scan its interpolations conservatively.
            collect_template_binding_roots(&field.source, &mut roots);
        }
    }
    Some((channel, roots))
}

/// The `fact:<Schema>` sink key and the binding roots a `record` payload
/// references — its explicit field values plus, for `record <S> from <b>`, the
/// copied-from binding `b`.
/// DR-0051 §4: per-field binding roots for every `record <Schema> { … }` in a
/// rule body, recursing into nested blocks. Mirrors
/// `collect_complete_field_reads`; see `record_field_reads`.
fn collect_record_field_reads(
    statements: &[body::BodyStmt],
    out: &mut BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
) {
    fn record_fields(
        record: &body::RecordStmt,
        out: &mut BTreeMap<String, BTreeMap<String, BTreeSet<String>>>,
    ) {
        let per_field = out.entry(format!("fact:{}", record.schema)).or_default();
        for field in &record.fields {
            let mut roots = BTreeSet::new();
            match &field.value {
                body::FieldValue::Shorthand => {
                    if let Some(root) = &record.from {
                        roots.insert(root.clone());
                    }
                }
                body::FieldValue::Expr { expr, .. } => collect_expr_binding_roots(expr, &mut roots),
                body::FieldValue::Nested { fields, .. } => {
                    collect_payload_field_roots(fields, record.from.as_deref(), &mut roots)
                }
            }
            per_field
                .entry(field.name.clone())
                .or_default()
                .extend(roots);
        }
    }
    for statement in statements {
        match statement {
            body::BodyStmt::Record(record) => record_fields(record, out),
            body::BodyStmt::Done {
                replacement: Some(record),
                ..
            } => record_fields(record, out),
            body::BodyStmt::After(after) => collect_record_field_reads(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_record_field_reads(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

fn record_payload_reads(record: &body::RecordStmt) -> (String, BTreeSet<String>) {
    let mut roots = BTreeSet::new();
    if let Some(from) = &record.from {
        roots.insert(from.clone());
    }
    collect_payload_field_roots(&record.fields, record.from.as_deref(), &mut roots);
    (format!("fact:{}", record.schema), roots)
}

#[derive(Clone, Debug, Default)]
struct TerminalMetadata {
    outputs: Vec<IrTerminalOutput>,
    branches: Vec<IrTerminalCaseBranch>,
}

#[derive(Clone, Debug)]
struct TerminalBranchSource {
    scrutinee: String,
    pattern: String,
    guard: Option<String>,
    body: String,
    pattern_span: SourceSpan,
}

#[derive(Clone, Debug)]
struct RuleCaseBranchSource {
    scrutinee: String,
    scrutinee_type: TypeSyntax,
    pattern: String,
    guard: Option<String>,
    body: String,
    pattern_span: SourceSpan,
}

fn collect_effect_payload_types(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) -> BTreeMap<String, IrType> {
    let mut payloads = BTreeMap::new();
    for statement in effect_payload_statements(&rule.body.text) {
        let line = statement.trim();
        let Some((kind, Some(binding))) = parse_effect_line(line) else {
            continue;
        };
        let payload = terminal_completed_payload_type(line, &kind, semantic);
        // A binding name keys the per-rule payload map, so reusing it for two effects
        // with DIFFERENT result types makes `after <binding> …` ambiguous (§5.5).
        // Same-type reuse (and mutually-exclusive `case` arms, which never both run)
        // is harmless and left alone.
        match payloads.get(&binding) {
            Some(existing) if existing != &payload => {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` reuses effect binding `{binding}` for effects with conflicting result types",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "give each effect a distinct binding — `as {binding}` is reused with a different result type, so `after {binding} …` is ambiguous"
                    )),
                });
            }
            Some(_) => {}
            None => {
                payloads.insert(binding, payload);
            }
        }
    }

    payloads
}

fn terminal_completed_payload_type(
    line: &str,
    kind: &IrEffectKind,
    semantic: &SemanticContext,
) -> IrType {
    match kind {
        IrEffectKind::SchemaCoerce if line.starts_with("prompt ") => {
            IrType::Primitive(IrPrimitiveType::String)
        }
        IrEffectKind::SchemaCoerce => parse_coerce_call_name(line)
            .and_then(|name| semantic.coerce_outputs.get(name))
            .cloned()
            .map(lower_type)
            .unwrap_or_else(terminal_unknown_payload_type),
        IrEffectKind::AgentTell => IrType::Ref("AgentTurn".to_owned()),
        IrEffectKind::CapabilityCall
        | IrEffectKind::EventEmit
        | IrEffectKind::WorkflowInvoke
        | IrEffectKind::TimerWait
        | IrEffectKind::ExecCommand
        | IrEffectKind::TrackerFile
        | IrEffectKind::TrackerClaim
        | IrEffectKind::TrackerRenew
        | IrEffectKind::TrackerRelease
        | IrEffectKind::TrackerFinish
        | IrEffectKind::LeaseAcquire
        | IrEffectKind::LeaseRenew
        | IrEffectKind::LedgerAppend
        | IrEffectKind::CounterConsume
        | IrEffectKind::SignalEmit
        | IrEffectKind::FileRead
        | IrEffectKind::FileWrite
        | IrEffectKind::FileImport
        | IrEffectKind::FileExport => terminal_unknown_payload_type(),
    }
}

fn collect_rule_case_metadata(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<IrRuleCaseBranch> {
    let mut branches = Vec::new();
    for branch in rule_case_branch_sources(rule, semantic, binding_types) {
        let mut branch_scope = binding_types.clone();
        if let Some((binding, schema)) =
            case_branch_payload_binding(&branch.pattern, &branch.scrutinee_type, semantic)
        {
            branch_scope.insert(binding, schema);
        }
        if let Some(guard) = &branch.guard {
            validate_expression(
                rule,
                guard,
                semantic,
                &branch_scope,
                "case guard",
                diagnostics,
            );
            validate_known_field_paths_at_span(
                rule,
                guard,
                branch.pattern_span,
                semantic,
                &branch_scope,
                diagnostics,
            );
        }
        validate_known_field_paths_at_span(
            rule,
            &branch.body,
            branch.pattern_span,
            semantic,
            &branch_scope,
            diagnostics,
        );
        if let Some(pattern) = lower_case_pattern(&branch.pattern, &branch.scrutinee_type, semantic)
        {
            branches.push(IrRuleCaseBranch {
                scrutinee: branch.scrutinee,
                scrutinee_type: lower_type(branch.scrutinee_type),
                pattern,
                guard: branch.guard.as_ref().and_then(|guard| {
                    lower_expression(
                        guard,
                        SourceSpan {
                            start: branch.pattern_span.start,
                            end: branch.pattern_span.end,
                        },
                    )
                }),
                body_hash: stable_hash(&branch.body),
                pattern_span: branch.pattern_span,
            });
        }
    }
    branches.sort_by(|left, right| {
        (left.scrutinee.as_str(), left.pattern_span.start)
            .cmp(&(right.scrutinee.as_str(), right.pattern_span.start))
    });
    branches
}

fn rule_case_branch_sources(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
) -> Vec<RuleCaseBranchSource> {
    let lines = rule
        .body
        .text
        .lines()
        .scan(0usize, |offset, line| {
            let current = *offset;
            *offset += line.len() + 1;
            Some((line, current))
        })
        .collect::<Vec<_>>();
    let text_lines = lines.iter().map(|(line, _)| *line).collect::<Vec<_>>();
    let mut branches = Vec::new();
    let mut index = 0usize;
    while index < lines.len() {
        let (line, _) = lines[index];
        let trimmed = line.trim();
        let Some(scrutinee) = case_scrutinee(trimmed) else {
            index += 1;
            continue;
        };
        if active_completes_binding_for_case(&text_lines, index, scrutinee) {
            index += 1;
            continue;
        }
        let Some(scrutinee_type) = expression_type(scrutinee, semantic, binding_types) else {
            index += 1;
            continue;
        };
        let mut depth = brace_delta(trimmed).max(1);
        index += 1;
        while index < lines.len() && depth > 0 {
            let (branch_line, branch_line_offset) = lines[index];
            let branch_trimmed = branch_line.trim();
            if depth == 1 {
                if let Some((pattern, guard, body_start)) = terminal_branch_header(branch_trimmed) {
                    let pattern_column = case_pattern_column(branch_line, pattern);
                    let pattern_span = SourceSpan {
                        start: rule_body_text_start(rule) + branch_line_offset + pattern_column,
                        end: rule_body_text_start(rule)
                            + branch_line_offset
                            + pattern_column
                            + pattern.len(),
                    };
                    let mut body_lines = Vec::new();
                    let mut branch_depth = brace_delta(body_start).max(1);
                    index += 1;
                    while index < lines.len() && branch_depth > 0 {
                        let body_line = lines[index].0;
                        let next_depth = branch_depth + brace_delta(body_line);
                        if next_depth >= 1 {
                            body_lines.push(body_line.to_owned());
                        }
                        branch_depth = next_depth;
                        index += 1;
                    }
                    branches.push(RuleCaseBranchSource {
                        scrutinee: scrutinee.to_owned(),
                        scrutinee_type: scrutinee_type.clone(),
                        pattern: pattern.to_owned(),
                        guard,
                        body: body_lines.join("\n"),
                        pattern_span,
                    });
                    continue;
                }
            }
            depth += brace_delta(branch_trimmed);
            index += 1;
        }
    }
    branches
}

fn case_branch_payload_binding(
    pattern: &str,
    scrutinee_type: &TypeSyntax,
    semantic: &SemanticContext,
) -> Option<(String, String)> {
    // Sum types: `Variant as b` binds the payload typed as the generated
    // `<Enum>.<Variant>` class (spec/sum-types.md).
    if let TypeSyntax::Ref { name } = scrutinee_type {
        if semantic.schemas.enums.contains_key(&name.name) {
            let (variant, binding) = sum_case_pattern_parts(pattern);
            let binding = binding?;
            let generated = format!("{}.{variant}", name.name);
            if binding.is_empty() || !semantic.schemas.class_exists(&generated) {
                return None;
            }
            return Some((binding.to_owned(), generated));
        }
    }
    let binding = pattern.strip_prefix("Some ").map(str::trim)?;
    if binding.is_empty() {
        return None;
    }
    let TypeSyntax::Optional { inner, .. } = scrutinee_type else {
        return None;
    };
    let schema = match inner.as_ref() {
        TypeSyntax::Ref { name } if semantic.schemas.class_exists(&name.name) => {
            Some(name.name.clone())
        }
        _ => None,
    }?;
    Some((binding.to_owned(), schema))
}

fn collect_terminal_case_metadata(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    effect_payload_types: &BTreeMap<String, IrType>,
    diagnostics: &mut Vec<Diagnostic>,
) -> TerminalMetadata {
    let mut metadata = TerminalMetadata::default();
    let mut output_bindings = BTreeSet::new();

    for branch in terminal_case_branch_sources(rule) {
        if output_bindings.insert(branch.scrutinee.clone()) {
            let completed_payload = effect_payload_types
                .get(&branch.scrutinee)
                .cloned()
                .unwrap_or_else(terminal_unknown_payload_type);
            metadata.outputs.push(IrTerminalOutput {
                binding: branch.scrutinee.clone(),
                alternatives: terminal_alternatives(completed_payload, branch.pattern_span),
                span: branch.pattern_span,
            });
        }

        let (tag, binding) = parse_terminal_pattern_parts(&branch.pattern);
        let mut branch_scope = binding_types.clone();
        if let (Some(tag), Some(binding)) = (&tag, &binding) {
            if let Some(schema) =
                terminal_payload_schema_for_tag(tag, &branch.scrutinee, effect_payload_types)
            {
                branch_scope.insert(binding.clone(), schema);
            }
        }
        if let Some(guard) = &branch.guard {
            validate_expression(
                rule,
                guard,
                semantic,
                &branch_scope,
                "case guard",
                diagnostics,
            );
            validate_known_field_paths(rule, guard, semantic, &branch_scope, diagnostics);
        }
        validate_known_field_paths(rule, &branch.body, semantic, &branch_scope, diagnostics);
        metadata.branches.push(IrTerminalCaseBranch {
            scrutinee: branch.scrutinee,
            tag,
            binding,
            guard: branch.guard.as_ref().and_then(|guard| {
                lower_expression(
                    guard,
                    SourceSpan {
                        start: branch.pattern_span.start,
                        end: branch.pattern_span.end,
                    },
                )
            }),
            body_hash: stable_hash(&branch.body),
            pattern_span: branch.pattern_span,
        });
    }

    metadata
        .outputs
        .sort_by(|left, right| left.binding.cmp(&right.binding));
    metadata.branches.sort_by(|left, right| {
        (left.scrutinee.as_str(), left.pattern_span.start)
            .cmp(&(right.scrutinee.as_str(), right.pattern_span.start))
    });
    metadata
}

fn terminal_case_branch_sources(rule: &RuleDecl) -> Vec<TerminalBranchSource> {
    let lines = rule
        .body
        .text
        .lines()
        .scan(0usize, |offset, line| {
            let current = *offset;
            *offset += line.len() + 1;
            Some((line, current))
        })
        .collect::<Vec<_>>();
    let text_lines = lines.iter().map(|(line, _)| *line).collect::<Vec<_>>();
    let mut branches = Vec::new();
    let mut index = 0usize;
    while index < lines.len() {
        let (line, line_offset) = lines[index];
        let trimmed = line.trim();
        let Some(scrutinee) = case_scrutinee(trimmed) else {
            index += 1;
            continue;
        };
        if !active_completes_binding_for_case(&text_lines, index, scrutinee) {
            index += 1;
            continue;
        }
        let mut depth = brace_delta(trimmed).max(1);
        index += 1;
        while index < lines.len() && depth > 0 {
            let (branch_line, branch_line_offset) = lines[index];
            let branch_trimmed = branch_line.trim();
            if depth == 1 {
                if let Some((pattern, guard, body_start)) = terminal_branch_header(branch_trimmed) {
                    let pattern_column = case_pattern_column(branch_line, pattern);
                    let pattern_span = SourceSpan {
                        start: rule_body_text_start(rule) + branch_line_offset + pattern_column,
                        end: rule_body_text_start(rule)
                            + branch_line_offset
                            + pattern_column
                            + pattern.len(),
                    };
                    let mut body_lines = Vec::new();
                    let mut branch_depth = brace_delta(body_start).max(1);
                    index += 1;
                    while index < lines.len() && branch_depth > 0 {
                        let body_line = lines[index].0;
                        let next_depth = branch_depth + brace_delta(body_line);
                        if next_depth >= 1 {
                            body_lines.push(body_line.to_owned());
                        }
                        branch_depth = next_depth;
                        index += 1;
                    }
                    branches.push(TerminalBranchSource {
                        scrutinee: scrutinee.to_owned(),
                        pattern: pattern.to_owned(),
                        guard,
                        body: body_lines.join("\n"),
                        pattern_span,
                    });
                    continue;
                }
            }
            depth += brace_delta(branch_trimmed);
            index += 1;
        }
        let _ = line_offset;
    }
    branches
}

fn rule_body_text_start(rule: &RuleDecl) -> usize {
    rule.body.span.end.saturating_sub(2 + rule.body.text.len())
}

fn terminal_branch_header(line: &str) -> Option<(&str, Option<String>, &str)> {
    let (head, body_start) = line.split_once("=>")?;
    let body_start = body_start.trim();
    if !body_start.starts_with('{') {
        return None;
    }
    let head = head.trim();
    let (pattern, guard) = match head.split_once(" where ") {
        Some((pattern, guard)) => (pattern.trim(), Some(guard.trim().to_owned())),
        None => (head, None),
    };
    Some((pattern, guard, body_start))
}

fn case_pattern_column(line: &str, pattern: &str) -> usize {
    line.find(pattern).unwrap_or_else(|| {
        let indent = line.len().saturating_sub(line.trim_start().len());
        indent + line.trim_start().find(pattern).unwrap_or(0)
    })
}

fn parse_terminal_pattern_parts(pattern: &str) -> (Option<String>, Option<String>) {
    if is_fallback_pattern(pattern) {
        return (None, None);
    }
    let mut parts = pattern.split_whitespace();
    let tag = parts.next().map(str::to_owned);
    // Binding is `Tag as binding` (Stage 1b: the space form `Tag binding` is gone).
    let second = parts.next();
    let binding = match second {
        Some("as") => parts.next().map(str::to_owned),
        Some(_) => return (tag, None),
        None => None,
    };
    if parts.next().is_some() {
        return (tag, None);
    }
    (tag, binding)
}

fn terminal_payload_schema_for_tag(
    tag: &str,
    scrutinee: &str,
    effect_payload_types: &BTreeMap<String, IrType>,
) -> Option<String> {
    match tag {
        "Completed" => match effect_payload_types.get(scrutinee) {
            Some(IrType::Ref(schema)) => Some(schema.clone()),
            _ => None,
        },
        "Failed" => Some("TerminalFailed".to_owned()),
        "TimedOut" => Some("TerminalTimedOut".to_owned()),
        "Cancelled" => Some("TerminalCancelled".to_owned()),
        _ => None,
    }
}

fn terminal_alternatives(
    completed_payload: IrType,
    span: SourceSpan,
) -> Vec<IrTerminalAlternative> {
    [
        ("Completed", completed_payload),
        ("Failed", terminal_failure_payload_type()),
        ("TimedOut", terminal_timeout_payload_type()),
        ("Cancelled", terminal_cancelled_payload_type()),
    ]
    .into_iter()
    .map(|(tag, payload_type)| IrTerminalAlternative {
        tag: tag.to_owned(),
        payload_type,
        source_span: span,
    })
    .collect()
}

fn terminal_failure_payload_type() -> IrType {
    IrType::Object(vec![
        ir_field("reason", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("summary", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("effect_id", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("run_id", IrType::Primitive(IrPrimitiveType::String)),
    ])
}

fn terminal_timeout_payload_type() -> IrType {
    IrType::Object(vec![
        ir_field("summary", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("effect_id", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("run_id", IrType::Primitive(IrPrimitiveType::String)),
    ])
}

fn terminal_cancelled_payload_type() -> IrType {
    IrType::Object(vec![
        ir_field("summary", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("effect_id", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("run_id", IrType::Primitive(IrPrimitiveType::String)),
    ])
}

fn terminal_unknown_payload_type() -> IrType {
    IrType::Object(vec![
        ir_field("summary", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("effect_id", IrType::Primitive(IrPrimitiveType::String)),
        ir_field("run_id", IrType::Primitive(IrPrimitiveType::String)),
    ])
}

fn ir_field(name: &str, ty: IrType) -> IrClassField {
    IrClassField {
        name: name.to_owned(),
        ty,
        is_key: false,
        presence_condition: None,
        span: SourceSpan { start: 0, end: 0 },
    }
}

/// Lower parsed access grants to IR for effects that carry authority-narrowing
/// metadata (`tell` turns and `invoke` start grants).
fn ir_access_grants_for_body(kind: &body::BodyEffectKind) -> Vec<IrAccessGrant> {
    match kind {
        body::BodyEffectKind::Tell { access_grants, .. }
        | body::BodyEffectKind::Invoke { access_grants, .. } => access_grants
            .iter()
            .map(|grant| IrAccessGrant {
                resource: grant.resource.clone(),
                operations: grant
                    .operations
                    .iter()
                    .map(|op| IrAccessGrantOp {
                        operation: op.operation.clone(),
                        target: op.target.clone(),
                        globs: op.globs.clone(),
                    })
                    .collect(),
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn ir_effect_kind_for_body(kind: &body::BodyEffectKind) -> IrEffectKind {
    match kind {
        body::BodyEffectKind::Tell { .. } => IrEffectKind::AgentTell,
        body::BodyEffectKind::Coerce { .. }
        | body::BodyEffectKind::Prompt { .. }
        | body::BodyEffectKind::Decide { .. } => IrEffectKind::SchemaCoerce,
        body::BodyEffectKind::Call { .. }
        | body::BodyEffectKind::ConstructCapabilityCall { .. } => IrEffectKind::CapabilityCall,
        body::BodyEffectKind::Invoke { .. } => IrEffectKind::WorkflowInvoke,
        body::BodyEffectKind::Timer { .. } => IrEffectKind::TimerWait,
        body::BodyEffectKind::Exec { .. } => IrEffectKind::ExecCommand,
        body::BodyEffectKind::TrackerFile { .. } => IrEffectKind::TrackerFile,
        body::BodyEffectKind::TrackerClaim { .. } => IrEffectKind::TrackerClaim,
        body::BodyEffectKind::TrackerRelease { .. } => IrEffectKind::TrackerRelease,
        body::BodyEffectKind::TrackerFinish { .. } => IrEffectKind::TrackerFinish,
        body::BodyEffectKind::LeaseAcquire { .. } => IrEffectKind::LeaseAcquire,
        body::BodyEffectKind::LeaseRenew { .. } => IrEffectKind::LeaseRenew,
        body::BodyEffectKind::LedgerAppend { .. } => IrEffectKind::LedgerAppend,
        body::BodyEffectKind::CounterConsume { .. } => IrEffectKind::CounterConsume,
        body::BodyEffectKind::Notify { .. } => IrEffectKind::SignalEmit,
        body::BodyEffectKind::FileRead { .. } => IrEffectKind::FileRead,
        body::BodyEffectKind::FileWrite { .. } => IrEffectKind::FileWrite,
        body::BodyEffectKind::FileImport { .. } => IrEffectKind::FileImport,
        body::BodyEffectKind::FileExport { .. } => IrEffectKind::FileExport,
    }
}

/// The agent a `tell` addresses, surfaced for information-flow analysis of the
/// turn's egress to the agent's provider. `None` for non-`tell` effects.
fn agent_for_body(kind: &body::BodyEffectKind) -> Option<String> {
    match kind {
        body::BodyEffectKind::Tell { target, .. } => Some(target.clone()),
        _ => None,
    }
}

/// The `coerce` declaration a coerce effect invokes (DR-0062). An inline
/// `decide` names no declaration, so it yields `None` and falls back to the
/// un-named-backend principal.
fn coerce_target_for_body(kind: &body::BodyEffectKind) -> Option<String> {
    match kind {
        body::BodyEffectKind::Coerce { name, .. } => Some(name.clone()),
        _ => None,
    }
}

/// Turn-scoped `with skills [...]` pinned onto an `agent.tell` effect (Phase 7).
fn turn_skills_for_body(kind: &body::BodyEffectKind) -> Vec<String> {
    match kind {
        body::BodyEffectKind::Tell { skills, .. } => skills.clone(),
        _ => Vec::new(),
    }
}

/// `on stream <name>` (std.vcs) carried on an `agent.tell` effect.
fn on_stream_for_body(kind: &body::BodyEffectKind) -> Option<String> {
    match kind {
        body::BodyEffectKind::Tell { on_stream, .. } => on_stream.clone(),
        _ => None,
    }
}

/// The std.vcs selective verbs' statically-checkable pieces (DR-0052
/// R4): the raw selection-slot source, and transport's `onto` target.
fn vcs_selective_for_body(kind: &body::BodyEffectKind) -> (Option<String>, Option<String>) {
    let body::BodyEffectKind::ConstructCapabilityCall {
        keyword, fields, ..
    } = kind
    else {
        return (None, None);
    };
    if keyword != "undo" && keyword != "transport" {
        return (None, None);
    }
    let field = |name: &str| {
        fields
            .iter()
            .find(|field| field.name == name)
            .map(|field| field.source.clone())
    };
    (field("selection"), field("onto"))
}

/// The workflow an `invoke` targets, surfaced for IFC membrane-door enumeration.
fn workflow_target_for_body(kind: &body::BodyEffectKind) -> Option<String> {
    match kind {
        body::BodyEffectKind::Invoke { workflow, .. } => Some(workflow.clone()),
        _ => None,
    }
}

/// The `exec` surface form (raw command vs manifest capability), surfaced so
/// check-time gates classify exec effects without re-scanning rule-body text.
fn exec_target_for_body(kind: &body::BodyEffectKind) -> Option<IrExecTarget> {
    match kind {
        body::BodyEffectKind::Exec { target, .. } => Some(match target {
            body::ExecTarget::RawCommand(_) => IrExecTarget::Raw,
            body::ExecTarget::Capability { name, .. } => {
                IrExecTarget::Capability { name: name.clone() }
            }
        }),
        _ => None,
    }
}

/// Whether an effect carries the `endorsed` source marker (I-IFC3) — a `coerce` the
/// author declared an integrity-raising crossing.
fn endorsed_for_body(kind: &body::BodyEffectKind) -> bool {
    matches!(kind, body::BodyEffectKind::Coerce { endorsed: true, .. })
}

/// Whether an effect carries the `declassified` source marker (I-IFC3) — a `coerce`
/// the author declared a confidentiality-lowering crossing.
fn declassified_for_body(kind: &body::BodyEffectKind) -> bool {
    matches!(
        kind,
        body::BodyEffectKind::Coerce {
            declassified: true,
            ..
        }
    )
}

/// The named resource a direct file/channel effect touches, surfaced for
/// information-flow analysis. `None` for effects with no named resource.
fn resource_for_body(kind: &body::BodyEffectKind) -> Option<String> {
    match kind {
        body::BodyEffectKind::FileRead { store, .. }
        | body::BodyEffectKind::FileWrite { store, .. }
        | body::BodyEffectKind::FileImport { store, .. }
        | body::BodyEffectKind::FileExport { store, .. } => Some(store.clone()),
        // `send via <channel>` carries the channel as a construct field.
        body::BodyEffectKind::ConstructCapabilityCall {
            keyword, fields, ..
        } if keyword == "send" => fields
            .iter()
            .find(|field| field.name == "channel")
            .map(|field| field.source.clone()),
        // `emit signal <name> to <peer>` touches the signal port `signal:<name>` (the
        // emit-port door, DR-0027 E6/H8); surfaced so the IFC checker can carry the
        // emitter's label to the receiver and enumerate the port in the surface.
        body::BodyEffectKind::Notify { event, .. } => Some(format!("signal:{event}")),
        // Coordination is governed as a resource label under E-COORD. The IFC
        // checker decides whether this declaration is partitioned or `shared`.
        body::BodyEffectKind::LeaseAcquire { resource, .. } => Some(format!("resource:{resource}")),
        body::BodyEffectKind::LedgerAppend { ledger, .. } => Some(format!("resource:{ledger}")),
        body::BodyEffectKind::CounterConsume { counter, .. } => Some(format!("resource:{counter}")),
        _ => None,
    }
}

fn construct_use_for_body(kind: &body::BodyEffectKind) -> Option<IrConstructUse> {
    match kind {
        body::BodyEffectKind::ConstructCapabilityCall {
            keyword,
            target_capability,
            ..
        } => Some(IrConstructUse {
            keyword: keyword.clone(),
            scope: "rule_body".to_owned(),
            construct_family: "effect_operation".to_owned(),
            lowering_target: "capability_call".to_owned(),
            target_capability: target_capability.clone(),
        }),
        _ => None,
    }
}

fn is_ast_only_effect_kind(kind: &body::BodyEffectKind) -> bool {
    // `send via <channel> { … } as x` closes its `as` on the block line (unlike
    // `recall`, whose `as` is inline), so the line scanner cannot see the binding;
    // seed it from the AST. Other `ConstructCapabilityCall`s (e.g. `recall`) are
    // line-visible and must NOT be treated as AST-only.
    if let body::BodyEffectKind::ConstructCapabilityCall { keyword, .. } = kind {
        return keyword == "send";
    }
    matches!(
        kind,
        body::BodyEffectKind::Prompt { .. }
            | body::BodyEffectKind::Timer { .. }
            | body::BodyEffectKind::Exec { .. }
            | body::BodyEffectKind::Decide { .. }
            | body::BodyEffectKind::TrackerFile { .. }
            | body::BodyEffectKind::TrackerClaim { .. }
            | body::BodyEffectKind::TrackerRelease { .. }
            | body::BodyEffectKind::TrackerFinish { .. }
            | body::BodyEffectKind::LeaseAcquire { .. }
            | body::BodyEffectKind::LeaseRenew { .. }
            | body::BodyEffectKind::LedgerAppend { .. }
            | body::BodyEffectKind::CounterConsume { .. }
            | body::BodyEffectKind::Notify { .. }
            // `invoke` payload blocks put post-payload modifiers on the closing line
            // in flow-generated rules, so the line scanner may miss `as <binding>`.
            | body::BodyEffectKind::Invoke { .. }
            // `write`/`export` put their `as <binding>` on the block's closing
            // line, so the line-based scanner cannot see it; seed it from the AST
            // so `after <binding>` blocks and sequence checks resolve.
            | body::BodyEffectKind::FileWrite { .. }
            | body::BodyEffectKind::FileExport { .. }
    )
}

/// Bindings introduced by AST-only effect kinds are unknown to the
/// line-based scanner; seed them so sequence checks and `after` blocks see
/// them. Binding types for typed outputs are registered where known.
fn seed_ast_only_effect_bindings(
    statements: &[body::BodyStmt],
    seen_bindings: &mut BTreeSet<String>,
    binding_types: &mut BTreeMap<String, String>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) if is_ast_only_effect_kind(&effect.kind) => {
                if let Some(binding) = &effect.binding {
                    seen_bindings.insert(binding.clone());
                    let _ = binding_types;
                }
            }
            body::BodyStmt::After(after) => {
                seed_ast_only_effect_bindings(&after.body, seen_bindings, binding_types)
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    seed_ast_only_effect_bindings(&branch.body, seen_bindings, binding_types);
                }
            }
            _ => {}
        }
    }
}

/// Derives effect nodes and dependency edges from the body AST, in document
/// order, with ids and idempotency keys identical to the historical
/// line-scanner derivation.
/// Collect the output bindings a rule `complete`s, recursing through the body's
/// nested blocks (after / case / branch / handler). A `complete <binding> {…}` is the
/// workflow's output to its invoker; the IFC checker treats it as an egress sink at
/// the invoker boundary (DR-0030 X2). `fail` terminals are NOT collected —
/// they carry an error to the runtime, not a value to the invoker.
fn collect_terminal_complete_bindings(statements: &[body::BodyStmt], out: &mut Vec<String>) {
    for statement in statements {
        match statement {
            body::BodyStmt::Terminal(terminal) if terminal.kind == body::TerminalKind::Complete => {
                out.push(terminal.name.clone());
            }
            body::BodyStmt::After(after) => collect_terminal_complete_bindings(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_terminal_complete_bindings(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

fn collect_effects_from_ast(
    statements: &[body::BodyStmt],
    rule_name: &str,
) -> (Vec<IrEffectNode>, Vec<IrEffectDependency>) {
    let mut effects = Vec::new();
    let mut dependencies = Vec::new();
    let mut counter = 0usize;
    let mut after_stack: Vec<(String, DependencyPredicate)> = Vec::new();
    let mut case_stack: Vec<(String, String)> = Vec::new();
    // Renew disambiguation (T3, mirroring the shipped `release` split): a
    // `renew <binding>` whose binding names a same-rule `claim <issue> as
    // <binding>` is a tracker claim-renew (`tracker.renew`); one naming an
    // `acquire ... as <binding>` stays a lease renew (`lease.renew`). Collect
    // the claim `as` bindings up front so the walk can re-classify.
    let claim_bindings = collect_claim_bindings(statements);
    walk_effects(
        statements,
        rule_name,
        &claim_bindings,
        &mut counter,
        &mut after_stack,
        &mut case_stack,
        &mut effects,
        &mut dependencies,
    );
    (effects, dependencies)
}

/// The `as` bindings of every `claim <issue> as <binding>` in a rule body — the
/// referent set the renew disambiguation flips `lease.renew` to `tracker.renew`
/// against (the claim result binding, whose output fact carries the issue id).
fn collect_claim_bindings(statements: &[body::BodyStmt]) -> BTreeSet<String> {
    let mut bindings = BTreeSet::new();
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::Effect(effect) = stmt {
            if matches!(effect.kind, body::BodyEffectKind::TrackerClaim { .. }) {
                if let Some(binding) = &effect.binding {
                    bindings.insert(binding.clone());
                }
            }
        }
    });
    bindings
}

#[allow(clippy::too_many_arguments)]
fn walk_effects(
    statements: &[body::BodyStmt],
    rule_name: &str,
    claim_bindings: &BTreeSet<String>,
    counter: &mut usize,
    after_stack: &mut Vec<(String, DependencyPredicate)>,
    case_stack: &mut Vec<(String, String)>,
    effects: &mut Vec<IrEffectNode>,
    dependencies: &mut Vec<IrEffectDependency>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                *counter += 1;
                let id = effect
                    .binding
                    .clone()
                    .unwrap_or_else(|| format!("effect{counter}"));
                // A `renew` naming a claim binding lowers to `tracker.renew`;
                // otherwise it stays the coord `lease.renew` its parser produced.
                let kind = match &effect.kind {
                    body::BodyEffectKind::LeaseRenew {
                        acquire_binding, ..
                    } if claim_bindings.contains(acquire_binding) => IrEffectKind::TrackerRenew,
                    other => ir_effect_kind_for_body(other),
                };
                for (upstream, predicate) in after_stack.iter() {
                    dependencies.push(IrEffectDependency {
                        upstream: upstream.clone(),
                        predicate: predicate.clone(),
                        downstream: id.clone(),
                    });
                }
                let idempotency_key =
                    effect_idempotency_key(rule_name, &id, &kind, &effect.binding);
                let mut required_capabilities = effect.requires.clone();
                match &effect.kind {
                    body::BodyEffectKind::Call { capability, .. } => {
                        required_capabilities.push(capability.clone());
                    }
                    body::BodyEffectKind::ConstructCapabilityCall {
                        target_capability, ..
                    } => {
                        required_capabilities.push(target_capability.clone());
                    }
                    _ => {}
                }
                required_capabilities.sort();
                required_capabilities.dedup();
                let construct_use = construct_use_for_body(&effect.kind);
                let access_grants = ir_access_grants_for_body(&effect.kind);
                let turn_skills = turn_skills_for_body(&effect.kind);
                let on_stream = on_stream_for_body(&effect.kind);
                let (selection_source, transport_onto) = vcs_selective_for_body(&effect.kind);
                let resource = resource_for_body(&effect.kind);
                let agent = agent_for_body(&effect.kind);
                let coerce_target = coerce_target_for_body(&effect.kind);
                let workflow_target = workflow_target_for_body(&effect.kind);
                let endorsed = endorsed_for_body(&effect.kind);
                let declassified = declassified_for_body(&effect.kind);
                let exec_target = exec_target_for_body(&effect.kind);
                effects.push(IrEffectNode {
                    id,
                    kind,
                    binding: effect.binding.clone(),
                    required_capabilities,
                    construct_use,
                    idempotency_key,
                    span: effect.span,
                    timeout_seconds: effect.timeout_seconds,
                    access_grants,
                    turn_skills,
                    on_stream,
                    selection_source,
                    transport_onto,
                    resource,
                    agent,
                    coerce_target,
                    workflow_target,
                    endorsed,
                    declassified,
                    selected_by: case_stack.last().cloned(),
                    exec_target,
                });
            }
            body::BodyStmt::After(after) => {
                let predicate = match after.predicate {
                    body::AfterPredicate::Succeeds => DependencyPredicate::Succeeds,
                    body::AfterPredicate::Fails => DependencyPredicate::Fails,
                    // `times out` / `cancelled` are distinct non-success terminal
                    // statuses, so the downstream effect releases only on that
                    // specific status (mirroring succeeds/fails), not on any
                    // terminal.
                    body::AfterPredicate::TimedOut => DependencyPredicate::TimedOut,
                    body::AfterPredicate::Cancelled => DependencyPredicate::Cancelled,
                    // Coordination outcomes are completion-valued: the downstream
                    // depends on the op reaching a terminal state; the outcome
                    // variant selects the arm at lowering.
                    body::AfterPredicate::Completes
                    | body::AfterPredicate::Held
                    | body::AfterPredicate::Contended
                    | body::AfterPredicate::Ok
                    | body::AfterPredicate::Over
                    | body::AfterPredicate::Promoted
                    | body::AfterPredicate::Conflicted
                    | body::AfterPredicate::Applied
                    | body::AfterPredicate::Stranded => DependencyPredicate::Completes,
                    // `reaches "<name>"` (Family C) is completion-shaped for the
                    // construct-graph provenance edge; the milestone-specific
                    // gating happens at runtime against the
                    // `workflow.invoke.reached:<name>` fact (text-keyed, see
                    // `fact_matches_after_predicate`), so this IR predicate is
                    // metadata only.
                    body::AfterPredicate::Reaches => DependencyPredicate::Completes,
                };
                after_stack.push((after.binding.clone(), predicate));
                walk_effects(
                    &after.body,
                    rule_name,
                    claim_bindings,
                    counter,
                    after_stack,
                    case_stack,
                    effects,
                    dependencies,
                );
                after_stack.pop();
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    // Record the selector: an effect in this arm is gated by
                    // `case <scrutinee> { <pattern> => … }` (DR §7.4).
                    case_stack.push((case.scrutinee.clone(), branch.pattern.clone()));
                    walk_effects(
                        &branch.body,
                        rule_name,
                        claim_bindings,
                        counter,
                        after_stack,
                        case_stack,
                        effects,
                        dependencies,
                    );
                    case_stack.pop();
                }
            }
            _ => {}
        }
    }
}

fn effect_idempotency_key(
    rule_name: &str,
    effect_id: &str,
    kind: &IrEffectKind,
    binding: &Option<String>,
) -> String {
    stable_hash(&format!(
        "rule={rule_name};effect={effect_id};kind={};binding={}",
        kind.as_str(),
        binding.as_deref().unwrap_or("-")
    ))
}

fn validate_coerce_call(
    rule: &RuleDecl,
    line: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some((function_name, args)) = parse_coerce_call(line) else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("rule `{}` has malformed coerce call", rule.name.name),
            suggestion: Some("write `coerce functionName(arg, ...) as name`".to_owned()),
        });
        return;
    };
    let Some(params) = semantic.coerce_params.get(function_name) else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` calls unknown coerce function `{function_name}`",
                rule.name.name
            ),
            suggestion: Some(format!(
                "declare `coerce {function_name}(...) -> Output {{ ... }}` before using it"
            )),
        });
        return;
    };
    if args.len() != params.len() {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` calls coerce `{function_name}` with {} argument(s), expected {}",
                rule.name.name,
                args.len(),
                params.len()
            ),
            suggestion: Some("pass one argument for each declared coerce parameter".to_owned()),
        });
        return;
    }
    let scope = ExprScope::from_bindings(binding_types);
    for (arg, param) in args.iter().zip(params) {
        // Dangling-root check (mirrors record/terminal value validation): an arg
        // whose root is not a known binding is a typo/unbound reference, which the
        // type-checker below accepts leniently.
        if let Some(root) = dangling_value_root(arg, known_roots) {
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` has unknown binding `{root}` in coerce `{function_name}` argument",
                    rule.name.name
                ),
                suggestion: Some(
                    "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                        .to_owned(),
                ),
            });
        }
        validate_expr_source_against_type(
            rule,
            &format!("coerce `{function_name}`"),
            &param.name.name,
            &param.ty,
            arg,
            semantic,
            &scope,
            diagnostics,
        );
    }
}

fn validate_effect_payloads(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in effect_payload_statements(&rule.body.text) {
        let trimmed = statement.trim();
        if trimmed.starts_with("coerce ") {
            validate_coerce_call(
                rule,
                trimmed,
                semantic,
                binding_types,
                known_roots,
                diagnostics,
            );
        }
    }
}

fn validate_workflow_invocations(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in workflow_invoke_statements(&rule.body.text) {
        let Some((target, body)) = invoke_statement_parts(&statement) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` has malformed workflow invocation",
                    rule.name.name
                ),
                suggestion: Some("write `invoke Workflow { input value } as binding`".to_owned()),
            });
            continue;
        };
        if semantic.workflow.as_deref() == Some(target) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` recursively invokes workflow `{target}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "split recursive orchestration into an explicit bounded scheduler workflow"
                        .to_owned(),
                ),
            });
            continue;
        }
        let Some(surface) = semantic.workflow_inputs.get(target) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` invokes unknown workflow `{target}`",
                    rule.name.name
                ),
                suggestion: Some("invoke a workflow declared in this source bundle".to_owned()),
            });
            continue;
        };

        let mut invocation_semantic = semantic.clone();
        invocation_semantic.schemas.merge(surface.schemas.clone());
        let assignments = collect_field_assignments(body);
        let mut seen = BTreeSet::new();
        for assignment in assignments {
            let (field, value) = match assignment {
                RecordFieldAssignment::Value { field, value } => (field, value),
                RecordFieldAssignment::Shorthand { field } => (field.clone(), field),
            };
            if !seen.insert(field.clone()) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!("workflow invocation `{target}` repeats input `{field}`"),
                    suggestion: Some("remove the duplicate invocation input".to_owned()),
                });
                continue;
            }
            let Some(input_ty) = surface.inputs.get(&field) else {
                let known = surface
                    .inputs
                    .keys()
                    .map(|input| format!("`{input}`"))
                    .collect::<Vec<_>>()
                    .join(", ");
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!("workflow `{target}` has no input `{field}`"),
                    suggestion: Some(if known.is_empty() {
                        "remove the invocation payload; the target declares no inputs".to_owned()
                    } else {
                        format!("pass one of: {known}")
                    }),
                });
                continue;
            };
            if let Some(root) = dangling_value_root(&value, known_roots) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` has unknown binding `{root}` in `invoke {target}` input `{field}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                            .to_owned(),
                    ),
                });
            }
            validate_expr_source_against_type(
                rule,
                target,
                &field,
                input_ty,
                &value,
                &invocation_semantic,
                &ExprScope::from_bindings(binding_types),
                diagnostics,
            );
        }
        for input in surface.inputs.keys() {
            if seen.contains(input) {
                continue;
            }
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!("workflow invocation `{target}` is missing input `{input}`"),
                suggestion: Some(format!(
                    "add `{input}` to the `{target}` invocation payload"
                )),
            });
        }
    }
}

fn validate_agent_tell_target(
    rule: &RuleDecl,
    line: &str,
    kind: &IrEffectKind,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if kind != &IrEffectKind::AgentTell {
        return;
    }
    let Some(target) = parse_tell_target(line) else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("rule `{}` has malformed tell target", rule.name.name),
            suggestion: Some("write `tell agentName ...` or `tell task.agentRef ...`".to_owned()),
        });
        return;
    };
    if target.starts_with('"') {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` uses a string literal as a tell target",
                rule.name.name
            ),
            suggestion: Some("use a declared agent name or an AgentRef field".to_owned()),
        });
        return;
    }
    let required_capabilities = parse_required_capabilities(line);
    if target.contains('.') {
        let Some(ty) = expression_type(target, semantic, binding_types) else {
            // Unknown type can mean a dangling root (the path's binding does not
            // exist) — caught here since the type lookup returns None silently. A
            // known root with a bad path is left to other validation.
            if let Some(root) = dangling_value_root(target, known_roots) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "rule `{}` has unknown binding `{root}` in tell target `{target}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "reference a binding from a `when ... as name` clause or an effect `as` binding"
                            .to_owned(),
                    ),
                });
            }
            return;
        };
        if let TypeSyntax::AgentRef { agents, .. } = ty {
            for agent in agents {
                validate_agent_capabilities(
                    rule,
                    &agent.name,
                    &required_capabilities,
                    semantic,
                    diagnostics,
                );
            }
        } else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` uses non-AgentRef dynamic tell target `{target}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "declare the field as `AgentRef<...>` before using it as a tell target"
                        .to_owned(),
                ),
            });
        }
        return;
    }
    if !semantic.agents.contains(target) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("rule `{}` tells unknown agent `{target}`", rule.name.name),
            suggestion: Some("declare the target agent before telling it".to_owned()),
        });
        return;
    }
    validate_agent_capabilities(rule, target, &required_capabilities, semantic, diagnostics);
}

fn validate_agent_capabilities(
    rule: &RuleDecl,
    agent: &str,
    required_capabilities: &[String],
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if required_capabilities.is_empty() {
        return;
    }
    let declared = semantic
        .agent_capabilities
        .get(agent)
        .cloned()
        .unwrap_or_default();
    for capability in required_capabilities {
        if !declared.contains(capability) {
            diagnostics.push(Diagnostic { related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` tells agent `{agent}` requiring undeclared capability `{capability}`",
                    rule.name.name
                ),
                suggestion: Some(format!(
                    "add `{capability}` to agent `{agent}` capabilities or choose another AgentRef target"
                )),
            });
        }
    }
}

fn validate_availability_when(
    rule: &RuleDecl,
    when: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let (pattern, _) = split_when_guard(when);
    let Some(target) = pattern.strip_suffix(" is available").map(str::trim) else {
        return;
    };
    if target.contains('.') {
        let Some(ty) = expression_type(target, semantic, binding_types) else {
            return;
        };
        if !matches!(ty, TypeSyntax::AgentRef { .. }) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` checks availability for non-AgentRef `{target}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "availability checks must name a declared agent or an AgentRef field"
                        .to_owned(),
                ),
            });
        }
        return;
    }
    if !semantic.agents.contains(target) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("rule `{}` checks unknown agent `{target}`", rule.name.name),
            suggestion: Some("declare the target agent before checking availability".to_owned()),
        });
    }
}

#[derive(Clone, Debug, Default)]
struct ExprScope {
    binding_types: BTreeMap<String, String>,
    implicit_schema: Option<String>,
}

impl ExprScope {
    fn from_bindings(binding_types: &BTreeMap<String, String>) -> Self {
        Self {
            binding_types: binding_types.clone(),
            implicit_schema: None,
        }
    }

    fn with_implicit_schema(&self, schema: String) -> Self {
        let mut scope = self.clone();
        scope.implicit_schema = Some(schema);
        scope
    }
}

#[derive(Clone, Debug)]
struct ExprValidationContext {
    subject: String,
    span: SourceSpan,
}

impl ExprValidationContext {
    fn rule(rule: &RuleDecl) -> Self {
        Self {
            subject: format!("rule `{}`", rule.name.name),
            span: rule.body.span,
        }
    }

    fn assertion(span: SourceSpan) -> Self {
        Self {
            subject: "assertion".to_owned(),
            span,
        }
    }
}

fn validate_expression(
    rule: &RuleDecl,
    expr: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    label: &str,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match parse_expression(expr) {
        Ok(expr) => {
            validate_parsed_expression(
                &expr,
                semantic,
                &ExprScope::from_bindings(binding_types),
                &ExprValidationContext::rule(rule),
                label,
                diagnostics,
            );
        }
        Err(message) => diagnostics.push(Diagnostic { related: Vec::new(),
            span: rule.body.span,
            message: format!("rule `{}` has invalid {label} expression: {message}", rule.name.name),
            suggestion: Some("use deterministic field paths, literals, boolean operators, comparisons, membership, count, or exists".to_owned()),
        }),
    }
}

fn validate_parsed_expression(
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    label: &str,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let presence_proofs = BTreeSet::new();
    validate_expr_node(
        expr,
        semantic,
        scope,
        context,
        &presence_proofs,
        diagnostics,
    );
    let ty = infer_expr_type(expr, semantic, scope, context, diagnostics);
    if ty != ExprType::Bool && ty != ExprType::Unknown {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: context.span,
            message: format!("{} has non-boolean {label} expression", context.subject),
            suggestion: Some(format!("{label} expressions must evaluate to bool")),
        });
    }
}

fn validate_expr_node(
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    presence_proofs: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match expr {
        Expr::Path(path) => {
            if path.len() < 2 {
                return;
            }
            let root = &path[0];
            let Some(schema) = scope.binding_types.get(root) else {
                if let Some(schema) = &scope.implicit_schema {
                    if let Err(message) =
                        validate_optional_path_access(schema, path, semantic, presence_proofs)
                    {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: context.span,
                            message: format!(
                                "{} has unsafe optional path `{}`: {message}",
                                context.subject,
                                path.join(".")
                            ),
                            suggestion: Some(
                                "prove the optional value is present before reading through it"
                                    .to_owned(),
                            ),
                        });
                        return;
                    }
                    if let Err(message) = semantic.schemas.resolve_field_path(schema, path) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: context.span,
                            message: format!(
                                "{} has invalid expression path `{}`: {message}",
                                context.subject,
                                path.join(".")
                            ),
                            suggestion: Some(
                                "use a field declared on the queried schema".to_owned(),
                            ),
                        });
                    }
                    return;
                }
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} has unknown expression root `{root}`", context.subject),
                    suggestion: Some(
                        "use a binding introduced by a `when ... as name` clause".to_owned(),
                    ),
                });
                return;
            };
            if let Err(message) =
                validate_optional_path_access(schema, &path[1..], semantic, presence_proofs)
            {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} has unsafe optional path `{}`: {message}",
                        context.subject,
                        path.join(".")
                    ),
                    suggestion: Some(
                        "prove the optional value is present before reading through it".to_owned(),
                    ),
                });
                return;
            }
            if let Err(message) = semantic.schemas.resolve_field_path(schema, &path[1..]) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} has invalid expression path `{}`: {message}",
                        context.subject,
                        path.join(".")
                    ),
                    suggestion: Some("use a field declared on the bound schema".to_owned()),
                });
            }
        }
        Expr::Index { target, key } => {
            validate_expr_node(
                target,
                semantic,
                scope,
                context,
                presence_proofs,
                diagnostics,
            );
            validate_expr_node(key, semantic, scope, context, presence_proofs, diagnostics);
            let key_ty = infer_expr_type(key, semantic, scope, context, diagnostics);
            if !matches!(key_ty, ExprType::String | ExprType::Unknown) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} indexes a map with a non-string key", context.subject),
                    suggestion: Some(
                        "use a string literal or string expression as the map key".to_owned(),
                    ),
                });
            }
        }
        Expr::Array(items) => {
            for item in items {
                validate_expr_node(item, semantic, scope, context, presence_proofs, diagnostics);
            }
        }
        Expr::Object(fields) => {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: context.span,
                message: format!(
                    "{} uses an object literal without an expected object or map type",
                    context.subject
                ),
                suggestion: Some(
                    "use object literals only in typed record fields or typed effect arguments"
                        .to_owned(),
                ),
            });
            for field in fields {
                validate_expr_node(
                    &field.value,
                    semantic,
                    scope,
                    context,
                    presence_proofs,
                    diagnostics,
                );
            }
        }
        Expr::Unary { expr, .. } => {
            validate_expr_node(expr, semantic, scope, context, presence_proofs, diagnostics)
        }
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => {
            validate_expr_node(left, semantic, scope, context, presence_proofs, diagnostics);
            let mut right_proofs = presence_proofs.clone();
            collect_presence_proofs(left, &mut right_proofs);
            validate_expr_node(right, semantic, scope, context, &right_proofs, diagnostics);
        }
        Expr::Binary { op, left, right } => {
            validate_expr_node(left, semantic, scope, context, presence_proofs, diagnostics);
            validate_expr_node(
                right,
                semantic,
                scope,
                context,
                presence_proofs,
                diagnostics,
            );
            validate_unknown_implicit_idents(
                *op,
                left,
                right,
                semantic,
                scope,
                context,
                diagnostics,
            );
            validate_finite_domain_expr(*op, left, right, semantic, scope, context, diagnostics);
        }
        Expr::Call { name, args } => {
            validate_function_call(name, args, semantic, scope, context, diagnostics);
            for arg in args {
                validate_expr_node(arg, semantic, scope, context, presence_proofs, diagnostics);
            }
        }
        Expr::Query { guard, .. } => {
            validate_query_expr(expr, semantic, scope, context, diagnostics);
            if let Some(guard) = guard {
                let guard_scope = query_guard_scope(expr, semantic, scope);
                validate_expr_node(
                    guard,
                    semantic,
                    &guard_scope,
                    context,
                    presence_proofs,
                    diagnostics,
                );
            }
        }
        Expr::Literal(_) => {}
    }
}

fn validate_unknown_implicit_idents(
    op: BinaryOp,
    left: &Expr,
    right: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !matches!(
        op,
        BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge
    ) {
        return;
    }
    validate_unknown_implicit_ident(left, right, semantic, scope, context, diagnostics);
    validate_unknown_implicit_ident(right, left, semantic, scope, context, diagnostics);
}

fn validate_unknown_implicit_ident(
    expr: &Expr,
    other: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Expr::Literal(ExprLiteral::Ident(name)) = expr else {
        return;
    };
    let Some(schema) = &scope.implicit_schema else {
        return;
    };
    let field_exists = semantic
        .schemas
        .classes
        .get(schema)
        .is_some_and(|fields| fields.contains_key(name));
    if field_exists
        || expr_domain(other, semantic, scope).is_some()
        || implicit_ident_field_exists(other, semantic, scope)
    {
        return;
    }
    diagnostics.push(Diagnostic {
        related: Vec::new(),
        span: context.span,
        message: format!(
            "{} fact query `{schema}` has unknown field `{name}`",
            context.subject
        ),
        suggestion: Some(format!(
            "use a field declared on `{schema}` inside the query `where` expression"
        )),
    });
}

fn implicit_ident_field_exists(expr: &Expr, semantic: &SemanticContext, scope: &ExprScope) -> bool {
    let Expr::Literal(ExprLiteral::Ident(name)) = expr else {
        return false;
    };
    let Some(schema) = &scope.implicit_schema else {
        return false;
    };
    semantic
        .schemas
        .classes
        .get(schema)
        .is_some_and(|fields| fields.contains_key(name))
}

fn validate_function_call(
    name: &str,
    args: &[Expr],
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match name {
        "count" => {
            if args.len() != 1 {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `count` with {} arguments, expected 1",
                        context.subject,
                        args.len()
                    ),
                    suggestion: Some(
                        "call `count` with exactly one array, map, fact query, or effect query argument"
                            .to_owned(),
                    ),
                });
                return;
            }
            let ty = infer_expr_type(&args[0], semantic, scope, context, diagnostics);
            if !is_countable_type(&ty) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `count` with unsupported argument type `{}`",
                        context.subject,
                        expr_type_label(&ty)
                    ),
                    suggestion: Some(
                        "use `count` only with arrays, maps, fact queries, or effect queries"
                            .to_owned(),
                    ),
                });
            }
        }
        "exists" => {
            if args.len() != 1 {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `exists` with {} arguments, expected 1",
                        context.subject,
                        args.len()
                    ),
                    suggestion: Some("call `exists` with exactly one argument".to_owned()),
                });
                return;
            }
            let ty = infer_expr_type(&args[0], semantic, scope, context, diagnostics);
            if !matches!(args[0], Expr::Index { .. }) && !is_exists_type(&ty) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `exists` with unsupported argument type `{}`",
                        context.subject,
                        expr_type_label(&ty)
                    ),
                    suggestion: Some(
                        "use `exists path` for optional/map presence checks or pass an array, map, fact query, or effect query"
                            .to_owned(),
                    ),
                });
            }
        }
        "empty" => {
            if args.len() != 1 {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `empty` with {} arguments, expected 1",
                        context.subject,
                        args.len()
                    ),
                    suggestion: Some(
                        "call `empty` with exactly one array, map, string, fact query, or effect query argument"
                            .to_owned(),
                    ),
                });
                return;
            }
            let ty = infer_expr_type(&args[0], semantic, scope, context, diagnostics);
            if !is_emptiable_type(&ty) {
                // An optional gets its own message: the inner type is what
                // makes it unsupported (spec: `empty(Optional<T>)` is defined
                // only when `empty(T)` is).
                let optional = matches!(ty, ExprType::Optional(_));
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls `empty` with unsupported {}argument type `{}`",
                        context.subject,
                        if optional { "optional " } else { "" },
                        expr_type_label(&ty)
                    ),
                    suggestion: Some(
                        "use `empty` only with arrays, maps, strings, fact queries, effect queries, null, or supported optional values"
                            .to_owned(),
                    ),
                });
            }
        }
        _ => {}
    }
}

fn validate_query_expr(
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Expr::Query { kind, head, guard } = expr else {
        return;
    };
    if *kind == QueryKind::Fact {
        let Some(schema) = query_head_schema(head, semantic) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: context.span,
                message: format!(
                    "{} queries unknown fact schema `{}`",
                    context.subject,
                    head.trim()
                ),
                suggestion: Some("use a declared class name in fact queries".to_owned()),
            });
            return;
        };
        if let Some(guard) = guard {
            let guard_scope = scope.with_implicit_schema(schema);
            let ty = infer_expr_type(guard, semantic, &guard_scope, context, diagnostics);
            if !matches!(ty, ExprType::Bool | ExprType::Unknown) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} fact query `{}` has non-boolean `where` expression",
                        context.subject,
                        head.trim()
                    ),
                    suggestion: Some("query `where` expressions must evaluate to bool".to_owned()),
                });
            }
        }
    }
}

fn validate_optional_path_access(
    root_schema: &str,
    path: &[String],
    semantic: &SemanticContext,
    presence_proofs: &BTreeSet<String>,
) -> Result<(), String> {
    let mut schema = root_schema.to_owned();
    let mut prefix = Vec::new();
    for (index, field) in path.iter().enumerate() {
        let Some(fields) = semantic.schemas.classes.get(&schema) else {
            return Ok(());
        };
        let Some(field_ty) = fields.get(field) else {
            return Ok(());
        };
        prefix.push(field.clone());
        if let TypeSyntax::Optional { inner, .. } = field_ty {
            if index + 1 < path.len() && !presence_proofs.contains(&prefix.join(".")) {
                return Err(format!(
                    "`{}` must be proven present before accessing `{}`",
                    prefix.join("."),
                    path[index + 1..].join(".")
                ));
            }
            if let Some(next_schema) = schema_name_for_path(inner) {
                schema = next_schema;
            }
            continue;
        }
        if let Some(next_schema) = schema_name_for_path(field_ty) {
            schema = next_schema;
        }
    }
    Ok(())
}

fn collect_presence_proofs(expr: &Expr, proofs: &mut BTreeSet<String>) {
    match expr {
        Expr::Binary {
            op: BinaryOp::Ne,
            left,
            right,
        } => {
            if matches!(**right, Expr::Literal(ExprLiteral::Null)) {
                if let Some(path) = expr_path_key(left) {
                    proofs.insert(path);
                }
            }
            if matches!(**left, Expr::Literal(ExprLiteral::Null)) {
                if let Some(path) = expr_path_key(right) {
                    proofs.insert(path);
                }
            }
        }
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => {
            if let Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            } = expr.as_ref()
            {
                if matches!(**right, Expr::Literal(ExprLiteral::Null)) {
                    if let Some(path) = expr_path_key(left) {
                        proofs.insert(path);
                    }
                }
                if matches!(**left, Expr::Literal(ExprLiteral::Null)) {
                    if let Some(path) = expr_path_key(right) {
                        proofs.insert(path);
                    }
                }
            }
        }
        Expr::Call { name, args } if name == "exists" && args.len() == 1 => {
            if let Some(path) = expr_path_key(&args[0]) {
                proofs.insert(path);
            }
        }
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => {
            collect_presence_proofs(left, proofs);
            collect_presence_proofs(right, proofs);
        }
        _ => {}
    }
}

fn expr_path_key(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Literal(ExprLiteral::Ident(name)) => Some(name.clone()),
        Expr::Path(path) if path.len() >= 2 => Some(path[1..].join(".")),
        Expr::Index { target, key } => {
            let target = expr_path_key(target)?;
            let key = match key.as_ref() {
                Expr::Literal(ExprLiteral::String(value) | ExprLiteral::Ident(value)) => value,
                _ => return None,
            };
            Some(format!("{target}[{key:?}]"))
        }
        _ => None,
    }
}

fn query_guard_scope(expr: &Expr, semantic: &SemanticContext, scope: &ExprScope) -> ExprScope {
    let Expr::Query {
        kind: QueryKind::Fact,
        head,
        ..
    } = expr
    else {
        return scope.clone();
    };
    query_head_schema(head, semantic)
        .map(|schema| scope.with_implicit_schema(schema))
        .unwrap_or_else(|| scope.clone())
}

fn query_head_schema(head: &str, semantic: &SemanticContext) -> Option<String> {
    let mut parts = head.split_whitespace();
    let schema = parts.next()?;
    if parts.next().is_some() {
        return None;
    }
    semantic
        .schemas
        .class_exists(schema)
        .then(|| schema.to_owned())
}

fn implicit_field_type(
    name: &str,
    semantic: &SemanticContext,
    scope: &ExprScope,
) -> Option<TypeSyntax> {
    let schema = scope.implicit_schema.as_ref()?;
    semantic
        .schemas
        .resolve_field_path(schema, &[name.to_owned()])
        .ok()
}

fn infer_expr_type(
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) -> ExprType {
    match expr {
        Expr::Literal(ExprLiteral::Ident(name)) => implicit_field_type(name, semantic, scope)
            .map(|ty| expr_type_from_type_syntax(&ty, semantic))
            .unwrap_or_else(|| expr_literal_type(&ExprLiteral::Ident(name.clone()))),
        Expr::Literal(literal) => expr_literal_type(literal),
        Expr::Path(path) => expr_path_type(path, semantic, scope).unwrap_or(ExprType::Unknown),
        Expr::Index { target, key } => {
            let target_ty = infer_expr_type(target, semantic, scope, context, diagnostics);
            let key_ty = infer_expr_type(key, semantic, scope, context, diagnostics);
            if !matches!(key_ty, ExprType::String | ExprType::Unknown) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} indexes a map with a non-string key", context.subject),
                    suggestion: Some(
                        "use a string literal or string expression as the map key".to_owned(),
                    ),
                });
            }
            match target_ty {
                ExprType::Map(inner) => *inner,
                ExprType::Unknown => ExprType::Unknown,
                _ => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: context.span,
                        message: format!("{} indexes a non-map expression", context.subject),
                        suggestion: Some("use indexing only on map values".to_owned()),
                    });
                    ExprType::Unknown
                }
            }
        }
        Expr::Array(items) => infer_array_type(items, semantic, scope, context, diagnostics),
        Expr::Object(fields) => {
            for field in fields {
                infer_expr_type(&field.value, semantic, scope, context, diagnostics);
            }
            ExprType::Object
        }
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => {
            let inner = infer_expr_type(expr, semantic, scope, context, diagnostics);
            if !matches!(inner, ExprType::Bool | ExprType::Unknown) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} applies `!` to a non-boolean expression",
                        context.subject
                    ),
                    suggestion: Some("use `!` only with boolean expressions".to_owned()),
                });
            }
            ExprType::Bool
        }
        Expr::Binary { op, left, right } => {
            infer_binary_type(*op, left, right, semantic, scope, context, diagnostics)
        }
        Expr::Call { name, args } => match name.as_str() {
            "count" => ExprType::Int,
            "exists" => ExprType::Bool,
            "empty" => ExprType::Bool,
            _ => {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} calls unsupported expression function `{name}`",
                        context.subject
                    ),
                    suggestion: Some("use `count`, `exists`, or `empty`".to_owned()),
                });
                for arg in args {
                    infer_expr_type(arg, semantic, scope, context, diagnostics);
                }
                ExprType::Unknown
            }
        },
        Expr::Query { guard, .. } => {
            if let Some(guard) = guard {
                let guard_scope = query_guard_scope(expr, semantic, scope);
                infer_expr_type(guard, semantic, &guard_scope, context, diagnostics);
            }
            ExprType::Collection
        }
    }
}

fn infer_binary_type(
    op: BinaryOp,
    left: &Expr,
    right: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) -> ExprType {
    let left_ty = infer_expr_type(left, semantic, scope, context, diagnostics);
    let right_ty = infer_expr_type(right, semantic, scope, context, diagnostics);
    match op {
        BinaryOp::And | BinaryOp::Or => {
            for ty in [&left_ty, &right_ty] {
                if !matches!(ty, ExprType::Bool | ExprType::Unknown) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: context.span,
                        message: format!(
                            "{} uses boolean operator with non-boolean operand",
                            context.subject
                        ),
                        suggestion: Some(
                            "use `&&` and `||` only with boolean expressions".to_owned(),
                        ),
                    });
                    break;
                }
            }
            ExprType::Bool
        }
        BinaryOp::Eq | BinaryOp::Ne => {
            if !types_comparable(&left_ty, &right_ty) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} compares incompatible expression types", context.subject),
                    suggestion: Some(
                        "compare values with compatible scalar or finite-domain types".to_owned(),
                    ),
                });
            }
            ExprType::Bool
        }
        BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => {
            if !is_orderable_pair(&left_ty, &right_ty) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} orders non-orderable expression values", context.subject),
                    suggestion: Some(
                        "use ordering only with int, float, duration, or time values".to_owned(),
                    ),
                });
            }
            ExprType::Bool
        }
        BinaryOp::In | BinaryOp::NotIn => {
            match &right_ty {
                ExprType::Array(item_ty) => {
                    if !types_comparable(&left_ty, item_ty) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: context.span,
                            message: format!(
                                "{} uses membership with incompatible item type",
                                context.subject
                            ),
                            suggestion: Some(
                                "make the left value compatible with the array item type"
                                    .to_owned(),
                            ),
                        });
                    }
                }
                ExprType::Map(_) => {
                    if !is_string_like_key_type(&left_ty) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: context.span,
                            message: format!(
                                "{} uses map membership with a non-string key",
                                context.subject
                            ),
                            suggestion: Some(
                                "use a string value on the left side of map membership".to_owned(),
                            ),
                        });
                    }
                }
                ExprType::Unknown => {}
                _ => diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} uses membership against a non-array/non-map expression",
                        context.subject
                    ),
                    suggestion: Some(
                        "use `in` with an array literal, array value, or map value".to_owned(),
                    ),
                }),
            }
            ExprType::Bool
        }
        BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div => {
            for ty in [&left_ty, &right_ty] {
                if !matches!(ty, ExprType::Int | ExprType::Float | ExprType::Unknown) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: context.span,
                        message: format!(
                            "{} uses arithmetic with a non-numeric operand",
                            context.subject
                        ),
                        suggestion: Some("use `+ - * /` only with int or float values".to_owned()),
                    });
                    break;
                }
            }
            if matches!(left_ty, ExprType::Float) || matches!(right_ty, ExprType::Float) {
                ExprType::Float
            } else if matches!(left_ty, ExprType::Int) && matches!(right_ty, ExprType::Int) {
                ExprType::Int
            } else {
                ExprType::Unknown
            }
        }
    }
}

fn infer_array_type(
    items: &[Expr],
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) -> ExprType {
    let mut item_ty: Option<ExprType> = None;
    for item in items {
        let ty = infer_expr_type(item, semantic, scope, context, diagnostics);
        if matches!(ty, ExprType::Unknown) {
            continue;
        }
        match &item_ty {
            None => item_ty = Some(ty),
            Some(existing) if types_comparable(existing, &ty) => {}
            Some(_) => {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!("{} has mixed-type array literal", context.subject),
                    suggestion: Some("use array literals whose elements share one type".to_owned()),
                });
                return ExprType::Array(Box::new(ExprType::Unknown));
            }
        }
    }
    ExprType::Array(Box::new(item_ty.unwrap_or(ExprType::Unknown)))
}

fn expr_path_type(
    path: &[String],
    semantic: &SemanticContext,
    scope: &ExprScope,
) -> Option<ExprType> {
    if path.len() < 2 {
        return None;
    }
    if let Some(schema) = scope.binding_types.get(&path[0]) {
        if schema.contains('.') {
            // Untyped runtime fact binding (general `when fact <name>`).
            return Some(ExprType::Unknown);
        }
        return semantic
            .schemas
            .resolve_field_path(schema, &path[1..])
            .ok()
            .map(|ty| expr_type_from_type_syntax(&ty, semantic));
    }
    let schema = scope.implicit_schema.as_ref()?;
    if schema.contains('.') {
        return Some(ExprType::Unknown);
    }
    semantic
        .schemas
        .resolve_field_path(schema, path)
        .ok()
        .map(|ty| expr_type_from_type_syntax(&ty, semantic))
}

fn expr_type_from_type_syntax(ty: &TypeSyntax, semantic: &SemanticContext) -> ExprType {
    match ty {
        TypeSyntax::Primitive { name, .. } => match name.as_str() {
            "bool" => ExprType::Bool,
            "int" => ExprType::Int,
            "float" => ExprType::Float,
            "string" => ExprType::String,
            "duration" => ExprType::Duration,
            "time" => ExprType::Time,
            "secret" => ExprType::Secret,
            _ => ExprType::Unknown,
        },
        TypeSyntax::LiteralString { value, .. } => ExprType::Finite {
            label: "literal".to_owned(),
            values: vec![value.clone()],
        },
        TypeSyntax::AgentRef { agents, .. } => ExprType::Finite {
            label: "AgentRef".to_owned(),
            values: agents.iter().map(|agent| agent.name.clone()).collect(),
        },
        TypeSyntax::Ref { name } => semantic
            .schemas
            .enums
            .get(&name.name)
            .map(|variants| ExprType::Finite {
                label: format!("enum `{}`", name.name),
                values: variants.iter().cloned().collect(),
            })
            .unwrap_or(ExprType::Object),
        TypeSyntax::Optional { inner, .. } => {
            ExprType::Optional(Box::new(expr_type_from_type_syntax(inner, semantic)))
        }
        TypeSyntax::Array { inner, .. } => {
            ExprType::Array(Box::new(expr_type_from_type_syntax(inner, semantic)))
        }
        TypeSyntax::Map { inner, .. } => {
            ExprType::Map(Box::new(expr_type_from_type_syntax(inner, semantic)))
        }
        TypeSyntax::Union { variants, .. } => {
            let values = variants
                .iter()
                .filter_map(|variant| match variant {
                    TypeSyntax::LiteralString { value, .. } => Some(value.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>();
            if values.len() == variants.len() && !values.is_empty() {
                ExprType::Finite {
                    label: "literal union".to_owned(),
                    values,
                }
            } else {
                ExprType::Unknown
            }
        }
    }
}

fn expr_literal_type(literal: &ExprLiteral) -> ExprType {
    match literal {
        ExprLiteral::String(_) | ExprLiteral::Ident(_) => ExprType::String,
        ExprLiteral::Number(value) if value.contains('.') => ExprType::Float,
        ExprLiteral::Number(_) => ExprType::Int,
        ExprLiteral::Bool(_) => ExprType::Bool,
        ExprLiteral::Null => ExprType::Null,
    }
}

fn types_comparable(left: &ExprType, right: &ExprType) -> bool {
    if matches!(left, ExprType::Unknown) || matches!(right, ExprType::Unknown) {
        return true;
    }
    if matches!(left, ExprType::Null) || matches!(right, ExprType::Null) {
        return true;
    }
    if is_numeric_type(left) && is_numeric_type(right) {
        return true;
    }
    match (left, right) {
        (ExprType::Optional(left), right) | (right, ExprType::Optional(left)) => {
            types_comparable(left, right)
        }
        (ExprType::Finite { .. }, ExprType::String)
        | (ExprType::String, ExprType::Finite { .. })
        | (ExprType::Finite { .. }, ExprType::Finite { .. }) => true,
        _ => left == right,
    }
}

fn is_numeric_type(ty: &ExprType) -> bool {
    matches!(ty, ExprType::Int | ExprType::Float)
}

fn is_string_like_key_type(ty: &ExprType) -> bool {
    match ty {
        ExprType::String | ExprType::Unknown | ExprType::Finite { .. } => true,
        ExprType::Optional(inner) => is_string_like_key_type(inner),
        _ => false,
    }
}

fn is_orderable_pair(left: &ExprType, right: &ExprType) -> bool {
    if matches!(left, ExprType::Unknown) || matches!(right, ExprType::Unknown) {
        return true;
    }
    (is_numeric_type(left) && is_numeric_type(right))
        || matches!(
            (left, right),
            (ExprType::Duration, ExprType::Duration)
                | (ExprType::Time, ExprType::Time)
                // A quoted ISO-8601 string in a time-typed comparison is a
                // time literal (spec/scheduled-time.md).
                | (ExprType::Time, ExprType::String)
                | (ExprType::String, ExprType::Time)
        )
}

fn is_countable_type(ty: &ExprType) -> bool {
    matches!(
        ty,
        ExprType::Array(_) | ExprType::Map(_) | ExprType::Collection | ExprType::Unknown
    )
}

fn is_exists_type(ty: &ExprType) -> bool {
    matches!(
        ty,
        ExprType::Array(_)
            | ExprType::Map(_)
            | ExprType::Collection
            | ExprType::Optional(_)
            | ExprType::Unknown
    )
}

/// Spec "Count And Empty": `empty` is a structural emptiness test for arrays,
/// maps, strings, fact/effect queries, and null; `empty(Optional<T>)` is
/// defined only when `empty(T)` is (so `empty(string?)` works, `empty(int?)`
/// does not). It never coerces scalars, objects, enum variants, or agent refs.
fn is_emptiable_type(ty: &ExprType) -> bool {
    match ty {
        ExprType::Array(_)
        | ExprType::Map(_)
        | ExprType::String
        | ExprType::Collection
        | ExprType::Null
        | ExprType::Unknown => true,
        ExprType::Optional(inner) => is_emptiable_type(inner),
        _ => false,
    }
}

fn expr_type_label(ty: &ExprType) -> String {
    match ty {
        ExprType::Bool => "bool".to_owned(),
        ExprType::Int => "int".to_owned(),
        ExprType::Float => "float".to_owned(),
        ExprType::String => "string".to_owned(),
        ExprType::Finite { label, values } => format!("{label}<{}>", values.join(" | ")),
        ExprType::Duration => "duration".to_owned(),
        ExprType::Time => "time".to_owned(),
        ExprType::Secret => "secret".to_owned(),
        ExprType::Null => "null".to_owned(),
        ExprType::Object => "object".to_owned(),
        ExprType::Array(inner) => format!("{}[]", expr_type_label(inner)),
        ExprType::Map(inner) => format!("map<{}>", expr_type_label(inner)),
        ExprType::Optional(inner) => format!("{}?", expr_type_label(inner)),
        ExprType::Collection => "query".to_owned(),
        ExprType::Unknown => "unknown".to_owned(),
    }
}

fn validate_finite_domain_expr(
    op: BinaryOp,
    left: &Expr,
    right: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !matches!(
        op,
        BinaryOp::Eq | BinaryOp::Ne | BinaryOp::In | BinaryOp::NotIn
    ) {
        return;
    }
    let Some((domain, literals)) = finite_domain_comparison(left, right, semantic, scope)
        .or_else(|| finite_domain_comparison(right, left, semantic, scope))
    else {
        validate_finite_domain_relation(op, left, right, semantic, scope, context, diagnostics);
        return;
    };
    for literal in literals.into_iter().flatten() {
        if !domain.iter().any(|value| value == &literal) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: context.span,
                message: format!(
                    "{} compares finite-domain value to unknown `{literal}`",
                    context.subject
                ),
                suggestion: Some(format!("use one of: {}", domain.join(", "))),
            });
        }
    }
    validate_finite_domain_relation(op, left, right, semantic, scope, context, diagnostics);
}

fn validate_finite_domain_relation(
    op: BinaryOp,
    left: &Expr,
    right: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    context: &ExprValidationContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match op {
        BinaryOp::Eq => {
            let Some(left_domain) = expr_domain(left, semantic, scope) else {
                return;
            };
            let Some(right_domain) = expr_domain(right, semantic, scope) else {
                return;
            };
            if left_domain
                .iter()
                .all(|value| !right_domain.iter().any(|right| right == value))
            {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} has statically unsatisfiable finite-domain equality",
                        context.subject
                    ),
                    suggestion: Some(format!(
                        "compare domains with at least one shared value; left: {}, right: {}",
                        left_domain.join(", "),
                        right_domain.join(", ")
                    )),
                });
            }
        }
        BinaryOp::In => {
            let Some(domain) = expr_domain(left, semantic, scope) else {
                return;
            };
            let Some(literals) = literal_array_values(right) else {
                return;
            };
            if literals
                .iter()
                .all(|literal| !domain.iter().any(|value| value == literal))
            {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} has statically unsatisfiable finite-domain membership",
                        context.subject
                    ),
                    suggestion: Some(format!("use one of: {}", domain.join(", "))),
                });
            }
        }
        BinaryOp::NotIn => {
            let Some(domain) = expr_domain(left, semantic, scope) else {
                return;
            };
            let Some(literals) = literal_array_values(right) else {
                return;
            };
            if !domain.is_empty()
                && domain
                    .iter()
                    .all(|value| literals.iter().any(|literal| literal == value))
            {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: context.span,
                    message: format!(
                        "{} has statically unsatisfiable finite-domain exclusion",
                        context.subject
                    ),
                    suggestion: Some(
                        "leave at least one domain value outside the exclusion set".to_owned(),
                    ),
                });
            }
        }
        _ => {}
    }
}

fn finite_domain_comparison(
    domain_expr: &Expr,
    literal_expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
) -> Option<(Vec<String>, Vec<Option<String>>)> {
    let domain = expr_domain(domain_expr, semantic, scope)?;
    let literals = match literal_expr {
        Expr::Literal(literal) => vec![expr_literal_name(literal)],
        Expr::Array(items) => items
            .iter()
            .filter_map(|item| match item {
                Expr::Literal(literal) => Some(expr_literal_name(literal)),
                _ => None,
            })
            .collect(),
        _ => Vec::new(),
    };
    Some((domain, literals))
}

fn expr_domain(expr: &Expr, semantic: &SemanticContext, scope: &ExprScope) -> Option<Vec<String>> {
    let ty = match expr {
        Expr::Path(path) => {
            let root = path.first()?;
            if let Some(schema) = scope.binding_types.get(root) {
                semantic
                    .schemas
                    .resolve_field_path(schema, path.get(1..)?)
                    .ok()?
            } else {
                let schema = scope.implicit_schema.as_ref()?;
                semantic.schemas.resolve_field_path(schema, path).ok()?
            }
        }
        Expr::Literal(ExprLiteral::Ident(name)) => implicit_field_type(name, semantic, scope)?,
        _ => return None,
    };
    finite_expr_domain(&ty, semantic)
}

fn finite_expr_domain(ty: &TypeSyntax, semantic: &SemanticContext) -> Option<Vec<String>> {
    match ty {
        TypeSyntax::Ref { name } => semantic
            .schemas
            .enums
            .get(&name.name)
            .map(|variants| variants.iter().cloned().collect()),
        TypeSyntax::Union { variants, .. } => {
            let values = variants
                .iter()
                .filter_map(|variant| match variant {
                    TypeSyntax::LiteralString { value, .. } => Some(value.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>();
            (!values.is_empty()).then_some(values)
        }
        TypeSyntax::AgentRef { agents, .. } => {
            Some(agents.iter().map(|agent| agent.name.clone()).collect())
        }
        _ => None,
    }
}

fn expr_literal_name(literal: &ExprLiteral) -> Option<String> {
    match literal {
        ExprLiteral::String(value) | ExprLiteral::Ident(value) => Some(value.clone()),
        _ => None,
    }
}

fn literal_array_values(expr: &Expr) -> Option<Vec<String>> {
    let Expr::Array(items) = expr else {
        return None;
    };
    items
        .iter()
        .map(|item| match item {
            Expr::Literal(literal) => expr_literal_name(literal),
            _ => None,
        })
        .collect()
}

fn parse_tell_target(line: &str) -> Option<&str> {
    line.strip_prefix("tell ")?
        .split_whitespace()
        .next()
        .filter(|target| !target.is_empty())
}

fn parse_required_capabilities(line: &str) -> Vec<String> {
    let Some(rest) = line.split_once(" requires ") else {
        return Vec::new();
    };
    let Some(list) = rest.1.trim_start().strip_prefix('[') else {
        return Vec::new();
    };
    let Some((items, _)) = list.split_once(']') else {
        return Vec::new();
    };
    let mut capabilities = items
        .split(',')
        .filter_map(|item| {
            let value = item.trim().trim_matches('"');
            (!value.is_empty()).then(|| value.to_owned())
        })
        .collect::<Vec<_>>();
    capabilities.sort();
    capabilities.dedup();
    capabilities
}

fn validate_case_blocks(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let lines = rule
        .body
        .text
        .lines()
        .scan(0usize, |offset, line| {
            let current = *offset;
            *offset += line.len() + 1;
            Some((line, current))
        })
        .collect::<Vec<_>>();
    let text_lines = lines.iter().map(|(line, _)| *line).collect::<Vec<_>>();
    let mut index = 0usize;
    while index < lines.len() {
        let trimmed = lines[index].0.trim();
        let Some(scrutinee) = case_scrutinee(trimmed) else {
            index += 1;
            continue;
        };
        let scrutinee_ty = expression_type(scrutinee, semantic, binding_types);
        let terminal_case = scrutinee_ty.is_none()
            && active_completes_binding_for_case(&text_lines, index, scrutinee);
        if scrutinee_ty.is_none() && !terminal_case {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` has case scrutinee `{scrutinee}` that is not a typed path",
                    rule.name.name
                ),
                suggestion: Some("match on a bound field such as `task.provider`".to_owned()),
            });
        }
        let mut depth = brace_delta(trimmed).max(1);
        let mut case_index = index + 1;
        let mut branches = Vec::new();
        while case_index < lines.len() && depth > 0 {
            let (raw_line, line_offset) = lines[case_index];
            let line = raw_line.trim();
            if depth == 1 {
                if let Some(branch) = parse_case_branch_head(line) {
                    let pattern_column = case_pattern_column(raw_line, branch.pattern);
                    let branch = SpanCaseBranchHead {
                        pattern: branch.pattern,
                        guard: branch.guard,
                        pattern_span: SourceSpan {
                            start: rule_body_text_start(rule) + line_offset + pattern_column,
                            end: rule_body_text_start(rule)
                                + line_offset
                                + pattern_column
                                + branch.pattern.len(),
                        },
                    };
                    branches.push(branch);
                    if terminal_case {
                        validate_terminal_case_pattern(
                            rule,
                            branch.pattern,
                            branch.pattern_span,
                            diagnostics,
                        );
                    } else {
                        validate_case_pattern(
                            rule,
                            branch.pattern,
                            scrutinee_ty.as_ref(),
                            branch.pattern_span,
                            semantic,
                            diagnostics,
                        );
                    }
                    // Terminal-case guards are validated by
                    // `collect_terminal_case_metadata`, which is the only path
                    // with `effect_payload_types` and so the only one that can
                    // bind the tag-refined payload (`Completed as result where
                    // result.x ...`) into the guard scope. Validating them here
                    // too would reject that binding as an unknown root.
                    if let Some(guard) = branch.guard.filter(|_| !terminal_case) {
                        let mut branch_scope = binding_types.clone();
                        if let Some(scrutinee_ty) = scrutinee_ty.as_ref() {
                            if let Some((binding, schema)) =
                                case_branch_payload_binding(branch.pattern, scrutinee_ty, semantic)
                            {
                                branch_scope.insert(binding, schema);
                            }
                        }
                        validate_expression(
                            rule,
                            guard,
                            semantic,
                            &branch_scope,
                            "case guard",
                            diagnostics,
                        );
                        validate_known_field_paths_at_span(
                            rule,
                            guard,
                            branch.pattern_span,
                            semantic,
                            &branch_scope,
                            diagnostics,
                        );
                    }
                }
            }
            depth += brace_delta(line);
            case_index += 1;
        }
        if terminal_case {
            validate_terminal_case_coverage(rule, &branches, diagnostics);
        } else {
            validate_case_coverage(
                rule,
                scrutinee_ty.as_ref(),
                &branches,
                semantic,
                diagnostics,
            );
        }
        index += 1;
    }
}

fn active_completes_binding_for_case(lines: &[&str], case_index: usize, scrutinee: &str) -> bool {
    let mut scopes: Vec<(String, DependencyPredicate, i32)> = Vec::new();
    for line in lines.iter().take(case_index) {
        let trimmed = line.trim();
        if let Some((binding, predicate)) = parse_after_line(trimmed) {
            scopes.push((binding, predicate, brace_delta(trimmed).max(1)));
        } else {
            let delta = brace_delta(trimmed);
            for (_, _, depth) in &mut scopes {
                *depth += delta;
            }
            scopes.retain(|(_, _, depth)| *depth > 0);
        }
    }
    scopes.iter().any(|(binding, predicate, _)| {
        binding == scrutinee && predicate == &DependencyPredicate::Completes
    })
}

fn brace_delta(line: &str) -> i32 {
    line.chars().fold(0, |depth, ch| match ch {
        '{' => depth + 1,
        '}' => depth - 1,
        _ => depth,
    })
}

fn case_scrutinee(line: &str) -> Option<&str> {
    let rest = line.strip_prefix("case ")?;
    let expr = rest.strip_suffix('{').unwrap_or(rest).trim();
    (!expr.is_empty()).then_some(expr)
}

fn is_case_branch_start(line: &str) -> bool {
    line.contains("=>")
}

#[derive(Clone, Copy)]
struct CaseBranchHead<'a> {
    pattern: &'a str,
    guard: Option<&'a str>,
}

#[derive(Clone, Copy)]
struct SpanCaseBranchHead<'a> {
    pattern: &'a str,
    guard: Option<&'a str>,
    pattern_span: SourceSpan,
}

fn parse_case_branch_head(line: &str) -> Option<CaseBranchHead<'_>> {
    let (pattern, _) = line.split_once("=>")?;
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return None;
    }
    match pattern.split_once(" where ") {
        Some((pattern, guard)) => Some(CaseBranchHead {
            pattern: pattern.trim(),
            guard: Some(guard.trim()),
        }),
        None => Some(CaseBranchHead {
            pattern,
            guard: None,
        }),
    }
}

fn expression_type(
    expr: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
) -> Option<TypeSyntax> {
    // A bare enum-typed binding is a valid scrutinee: `case o` dispatches a
    // sum-type payload (spec/sum-types.md). Class-typed bare bindings stay
    // untyped here so the "match on a bound field" guidance still fires.
    let is_bare_ident = !expr.is_empty()
        && expr.chars().all(|ch| ch.is_alphanumeric() || ch == '_')
        && expr.chars().next().is_some_and(char::is_alphabetic);
    if is_bare_ident {
        let schema = binding_types.get(expr)?;
        if semantic.schemas.enums.contains_key(schema) {
            return Some(TypeSyntax::Ref {
                name: Ident {
                    name: schema.clone(),
                    span: zero_span(),
                },
            });
        }
        return None;
    }
    let (root, path) = expression_path(expr)?;
    let schema = binding_types.get(&root)?;
    semantic.schemas.resolve_field_path(schema, &path).ok()
}

fn validate_case_pattern(
    rule: &RuleDecl,
    pattern: &str,
    scrutinee_ty: Option<&TypeSyntax>,
    span: SourceSpan,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if matches!(pattern, "_" | "default") {
        return;
    }
    if pattern == "None" {
        if !matches!(scrutinee_ty, Some(TypeSyntax::Optional { .. })) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span,
                message: format!(
                    "rule `{}` uses `None` for a non-optional case",
                    rule.name.name
                ),
                suggestion: Some("use `None` only when matching an optional field".to_owned()),
            });
        }
        return;
    }
    if pattern.starts_with("Some ") {
        if !matches!(scrutinee_ty, Some(TypeSyntax::Optional { .. })) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span,
                message: format!(
                    "rule `{}` uses `Some` for a non-optional case",
                    rule.name.name
                ),
                suggestion: Some("use `Some name` only when matching an optional field".to_owned()),
            });
        }
        return;
    }
    let Some(scrutinee_ty) = scrutinee_ty else {
        return;
    };
    match scrutinee_ty {
        TypeSyntax::Ref { name } => {
            let Some(variants) = semantic.schemas.enums.get(&name.name) else {
                return;
            };
            let (variant, binding) = sum_case_pattern_parts(pattern);
            if !variants.contains(variant) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!("enum `{}` has no variant `{variant}`", name.name),
                    suggestion: Some(format!(
                        "use one of: {}",
                        variants.iter().cloned().collect::<Vec<_>>().join(", ")
                    )),
                });
                return;
            }
            // `as` binds a data-carrying variant's payload (spec/sum-types.md);
            // a bare variant has no payload to bind.
            if binding.is_some()
                && !semantic
                    .schemas
                    .class_exists(&format!("{}.{variant}", name.name))
            {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!(
                        "variant `{variant}` of enum `{}` carries no payload to bind",
                        name.name
                    ),
                    suggestion: Some(format!("write `{variant} => {{ ... }}` without `as`")),
                });
            }
        }
        TypeSyntax::Union { variants, .. } => {
            let Some(literal) = parse_literal_expr(pattern) else {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!(
                        "rule `{}` has unsupported case pattern `{pattern}`",
                        rule.name.name
                    ),
                    suggestion: Some("use a literal branch value or `_`".to_owned()),
                });
                return;
            };
            validate_union_case_pattern(rule, variants, &literal, span, diagnostics);
        }
        TypeSyntax::AgentRef { agents, .. } => {
            let Some(literal) = parse_literal_expr(pattern) else {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!(
                        "rule `{}` has unsupported AgentRef case pattern `{pattern}`",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "use a declared agent name, a string literal, or `_`".to_owned(),
                    ),
                });
                return;
            };
            validate_agent_ref_case_pattern(rule, agents, &literal, span, diagnostics);
        }
        TypeSyntax::Optional { inner, .. } => {
            validate_case_pattern(rule, pattern, Some(inner), span, semantic, diagnostics);
        }
        // `case` over a `bool` field: only the two literals `true`/`false` (plus
        // the `_`/`default` fallbacks already handled above) are valid patterns.
        TypeSyntax::Primitive { name, .. } if name == "bool" => {
            if !matches!(pattern, "true" | "false") {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!(
                        "rule `{}` has case pattern `{pattern}` that is not a `bool` value",
                        rule.name.name
                    ),
                    suggestion: Some("match `true`, `false`, or `_`".to_owned()),
                });
            }
        }
        _ => {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span,
                message: format!(
                    "rule `{}` cannot pattern-match this scrutinee type",
                    rule.name.name
                ),
                suggestion: Some(
                    "match an enum, literal union, optional, or tagged output union".to_owned(),
                ),
            });
        }
    }
}

fn terminal_case_tags() -> [&'static str; 4] {
    ["Completed", "Failed", "TimedOut", "Cancelled"]
}

fn validate_terminal_case_pattern(
    rule: &RuleDecl,
    pattern: &str,
    span: SourceSpan,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if is_fallback_pattern(pattern) {
        return;
    }
    let mut parts = pattern.split_whitespace();
    let Some(tag) = parts.next() else {
        return;
    };
    // Binding is `Tag as binding` (Stage 1b: the legacy space form `Tag binding` is
    // no longer accepted — it aligns terminal cases with enum-variant `as` binding).
    let second = parts.next();
    let binding = match second {
        Some("as") => parts.next(),
        other => other,
    };
    let uses_as = matches!(second, Some("as"));
    if parts.next().is_some() || binding.is_none() || !uses_as {
        diagnostics.push(Diagnostic { related: Vec::new(),
            span,
            message: format!(
                "rule `{}` has malformed terminal-output case pattern `{pattern}`",
                rule.name.name
            ),
            suggestion: Some("write `Completed as result`, `Failed as failure`, `TimedOut as timeout`, or `Cancelled as cancel` (the `as` is required)".to_owned()),
        });
        return;
    }
    let tags = terminal_case_tags();
    if !tags.contains(&tag) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!(
                "rule `{}` terminal-output case pattern cannot be `{tag}`",
                rule.name.name
            ),
            suggestion: Some(format!("use one of: {}", tags.join(", "))),
        });
    }
}

fn validate_terminal_case_coverage(
    rule: &RuleDecl,
    branches: &[SpanCaseBranchHead<'_>],
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_unreachable_after_fallback(rule, branches, diagnostics);
    if branches.is_empty()
        || branches
            .iter()
            .any(|branch| is_fallback_pattern(branch.pattern))
    {
        validate_duplicate_terminal_case_patterns(rule, branches, diagnostics);
        return;
    }
    validate_duplicate_terminal_case_patterns(rule, branches, diagnostics);
    let covered = branches
        .iter()
        .filter(|branch| branch.guard.is_none())
        .filter_map(|branch| normalized_terminal_case_pattern(branch.pattern))
        .collect::<BTreeSet<_>>();
    let missing = terminal_case_tags()
        .iter()
        .filter(|tag| !covered.contains(**tag))
        .copied()
        .collect::<Vec<_>>();
    if !missing.is_empty() {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` has non-exhaustive terminal-output case; missing {}",
                rule.name.name,
                missing.join(", ")
            ),
            suggestion: Some(
                "add terminal branches for every value or add `_ => { ... }`".to_owned(),
            ),
        });
    }
}

fn validate_duplicate_terminal_case_patterns(
    rule: &RuleDecl,
    branches: &[SpanCaseBranchHead<'_>],
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut seen = BTreeSet::new();
    for branch in branches.iter().filter(|branch| branch.guard.is_none()) {
        let Some(pattern) = normalized_terminal_case_pattern(branch.pattern) else {
            continue;
        };
        if !seen.insert(pattern.to_owned()) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: branch.pattern_span,
                message: format!(
                    "rule `{}` has duplicate unguarded terminal-output case pattern `{pattern}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "remove the duplicate branch or add mutually exclusive `where` guards"
                        .to_owned(),
                ),
            });
        }
    }
}

fn validate_case_coverage(
    rule: &RuleDecl,
    scrutinee_ty: Option<&TypeSyntax>,
    branches: &[SpanCaseBranchHead<'_>],
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_unreachable_after_fallback(rule, branches, diagnostics);
    if branches.is_empty()
        || branches
            .iter()
            .any(|branch| is_fallback_pattern(branch.pattern))
    {
        validate_duplicate_case_patterns(rule, branches, diagnostics);
        return;
    }
    validate_duplicate_case_patterns(rule, branches, diagnostics);

    let Some(domain) = finite_case_domain(scrutinee_ty, semantic) else {
        return;
    };
    let covered = branches
        .iter()
        .filter(|branch| branch.guard.is_none())
        .filter_map(|branch| normalized_case_pattern(branch.pattern))
        .collect::<BTreeSet<_>>();
    let missing = domain
        .iter()
        .filter(|value| !covered.contains(value.as_str()))
        .cloned()
        .collect::<Vec<_>>();
    if !missing.is_empty() {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` has non-exhaustive case; missing {}",
                rule.name.name,
                missing.join(", ")
            ),
            suggestion: Some("add branches for every value or add `_ => { ... }`".to_owned()),
        });
    }
}

fn validate_duplicate_case_patterns(
    rule: &RuleDecl,
    branches: &[SpanCaseBranchHead<'_>],
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut seen = BTreeSet::new();
    for branch in branches.iter().filter(|branch| branch.guard.is_none()) {
        let Some(pattern) = normalized_case_pattern(branch.pattern) else {
            continue;
        };
        if !seen.insert(pattern.to_owned()) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: branch.pattern_span,
                message: format!(
                    "rule `{}` has duplicate unguarded case pattern `{pattern}`",
                    rule.name.name
                ),
                suggestion: Some(
                    "remove the duplicate branch or add mutually exclusive `where` guards"
                        .to_owned(),
                ),
            });
        }
    }
}

/// Flags case branches that can never be reached because an earlier *unguarded*
/// wildcard (`_`/`default`) already matches everything. Shared by rule cases and
/// terminal-output cases. Mirrors case-family.maude inv c (redundant-postwild): any
/// arm after the wildcard is redundant. A *guarded* fallback (`_ where g`) does not
/// shadow, since its guard can fail at runtime.
fn validate_unreachable_after_fallback(
    rule: &RuleDecl,
    branches: &[SpanCaseBranchHead<'_>],
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut ordered: Vec<&SpanCaseBranchHead<'_>> = branches.iter().collect();
    ordered.sort_by_key(|branch| branch.pattern_span.start);
    let mut fallback_span: Option<SourceSpan> = None;
    for branch in ordered {
        if let Some(prior) = fallback_span {
            diagnostics.push(
                Diagnostic {
                    related: Vec::new(),
                    span: branch.pattern_span,
                    message: format!(
                        "rule `{}` has an unreachable case branch after the `_` wildcard",
                        rule.name.name
                    ),
                    suggestion: Some(
                        "move this branch before the wildcard, or remove it".to_owned(),
                    ),
                }
                .with_related(
                    prior,
                    "this unguarded wildcard already matches every remaining value",
                ),
            );
        } else if branch.guard.is_none() && is_fallback_pattern(branch.pattern) {
            fallback_span = Some(branch.pattern_span);
        }
    }
}

fn finite_case_domain(
    scrutinee_ty: Option<&TypeSyntax>,
    semantic: &SemanticContext,
) -> Option<Vec<String>> {
    match scrutinee_ty? {
        TypeSyntax::Ref { name } => semantic
            .schemas
            .enums
            .get(&name.name)
            .map(|variants| variants.iter().cloned().collect()),
        TypeSyntax::Union { variants, .. } => {
            let values = variants
                .iter()
                .filter_map(|variant| match variant {
                    TypeSyntax::LiteralString { value, .. } => Some(value.clone()),
                    _ => None,
                })
                .collect::<Vec<_>>();
            (!values.is_empty()).then_some(values)
        }
        TypeSyntax::Optional { .. } => Some(vec!["Some".to_owned(), "None".to_owned()]),
        TypeSyntax::AgentRef { agents, .. } => {
            Some(agents.iter().map(|agent| agent.name.clone()).collect())
        }
        // `bool` is a finite two-value domain: an exhaustive `case` over it must
        // cover both `true` and `false` (or carry a `_`).
        TypeSyntax::Primitive { name, .. } if name == "bool" => {
            Some(vec!["true".to_owned(), "false".to_owned()])
        }
        _ => None,
    }
}

/// Splits a sum-type case pattern `Variant as binding` into variant and
/// binding (spec/sum-types.md); a plain pattern returns no binding.
fn sum_case_pattern_parts(pattern: &str) -> (&str, Option<&str>) {
    match pattern.split_once(" as ") {
        Some((variant, binding)) => (variant.trim(), Some(binding.trim())),
        None => (pattern.trim(), None),
    }
}

fn normalized_case_pattern(pattern: &str) -> Option<&str> {
    if is_fallback_pattern(pattern) {
        return None;
    }
    if pattern.starts_with("Some ") {
        return Some("Some");
    }
    if pattern == "None" {
        return Some("None");
    }
    // Coverage counts the variant, not its payload binding.
    let (pattern, _) = sum_case_pattern_parts(pattern);
    // `bool` literals parse to the value-less `LiteralExpr::Bool`; return them
    // verbatim so they count toward `true`/`false` coverage.
    if matches!(pattern, "true" | "false") {
        return Some(pattern);
    }
    parse_literal_expr(pattern).and_then(|literal| match literal {
        LiteralExpr::String(value) | LiteralExpr::Ident(value) => Some(value),
        _ => None,
    })
}

fn normalized_terminal_case_pattern(pattern: &str) -> Option<&str> {
    if is_fallback_pattern(pattern) {
        return None;
    }
    pattern.split_whitespace().next()
}

fn is_fallback_pattern(pattern: &str) -> bool {
    matches!(pattern, "_" | "default")
}

fn validate_union_case_pattern(
    rule: &RuleDecl,
    variants: &[TypeSyntax],
    literal: &LiteralExpr<'_>,
    span: SourceSpan,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let allowed = variants
        .iter()
        .filter_map(|variant| match variant {
            TypeSyntax::LiteralString { value, .. } => Some(value.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>();
    if allowed.is_empty() {
        return;
    }
    let LiteralExpr::String(value) = literal else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!(
                "rule `{}` case pattern must be one of its literal variants",
                rule.name.name
            ),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
        return;
    };
    if !allowed.contains(value) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("rule `{}` case pattern cannot be `{value}`", rule.name.name),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
    }
}

fn validate_agent_ref_case_pattern(
    rule: &RuleDecl,
    agents: &[Ident],
    literal: &LiteralExpr<'_>,
    span: SourceSpan,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let allowed = agents
        .iter()
        .map(|agent| agent.name.as_str())
        .collect::<Vec<_>>();
    let (LiteralExpr::String(value) | LiteralExpr::Ident(value)) = literal else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("rule `{}` has non-agent case pattern", rule.name.name),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
        return;
    };
    if !allowed.contains(value) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!("AgentRef has no agent `{value}`"),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
    }
}

fn validate_binding_uses(
    rule: &RuleDecl,
    line: &str,
    seen_bindings: &BTreeSet<String>,
    scope_stack: &[(String, DependencyPredicate)],
    diagnostics: &mut Vec<Diagnostic>,
) {
    for root in interpolation_roots(line) {
        if !seen_bindings.contains(&root) {
            continue;
        }
        if scope_stack.iter().any(|(binding, _)| binding == &root) {
            continue;
        }

        diagnostics.push(Diagnostic { related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` uses effect output `{root}` outside a matching `after {root} ...` block",
                rule.name.name
            ),
            suggestion: Some(format!(
                "move this use into `after {root} succeeds {{ ... }}` or another matching terminal branch"
            )),
        });
    }
}

fn after_scopes(block_stack: &[BlockFrame]) -> Vec<(String, DependencyPredicate)> {
    block_stack
        .iter()
        .map(|frame| match frame {
            BlockFrame::After { binding, predicate } => (binding.clone(), predicate.clone()),
        })
        .collect()
}

/// The single lowering table for readiness sugar: maps a `when` pattern to
/// the runtime fact name it matches. The general form is
/// `when fact <name> as x`; the English phrases are documented abbreviations
/// of it.
pub fn runtime_fact_name_for_pattern(pattern: &str) -> Option<String> {
    let pattern = pattern.trim();
    if let Some(rest) = pattern.strip_prefix("fact ") {
        let name = rest.split_whitespace().next()?;
        return Some(name.to_owned());
    }
    // Inbound messaging (spec/messaging.md): `message from <channel>` matches the
    // channel-specific `message.<channel>` fact ingested by `whip message`.
    if let Some(rest) = pattern.strip_prefix("message from ") {
        if let Some(channel) = rest.split_whitespace().next() {
            return Some(format!("message.{channel}"));
        }
    }
    // std.vcs readiness sugar (DR-0052 grammar pass): each phrase is a
    // defined lowering onto a generated-only `vcs.*` fact; the leading
    // word of the stream forms is the stream guard's subject.
    if pattern == "line changed" || pattern == "line changed by others" {
        return Some("vcs.cut.recorded".to_owned());
    }
    if pattern == "reconcile stalled" {
        return Some("vcs.reconcile.stalled".to_owned());
    }
    {
        let words: Vec<&str> = pattern.split_whitespace().collect();
        match words.as_slice() {
            [_, "has", "contention"] => {
                return Some("vcs.contention.predicted".to_owned());
            }
            [_, "promoted"] => {
                return Some("vcs.stream.promoted".to_owned());
            }
            [_, "is", "quiescent"] => {
                return Some("vcs.stream.quiescent".to_owned());
            }
            _ => {}
        }
    }
    let mut words = pattern.split_whitespace();
    let first = words.next()?;
    if words.next() == Some("completed") && words.next() == Some("turn") {
        let _ = first;
        return Some("agent.turn.completed".to_owned());
    }
    {
        let mut words = pattern.split_whitespace();
        let _tracker = words.next();
        if words.next() == Some("has")
            && words.next() == Some("ready")
            && words.next() == Some("issue")
        {
            return Some("tracker.issue.ready".to_owned());
        }
    }
    if first.chars().next().is_some_and(char::is_uppercase) {
        return Some(first.to_owned());
    }
    None
}

/// The schema used to type-check fields on the pattern's binding. Dotted
/// runtime fact names are untyped (no class declares them); the sugar forms
/// map to their builtin schemas.
fn binding_from_when(when: &str) -> Option<(String, String)> {
    let (pattern, _) = split_when_guard(when);
    let binding = binding_after_as(pattern)?;
    let first = pattern.split_whitespace().next()?;
    let completed_turn = {
        let mut words = pattern.split_whitespace();
        words.next();
        words.next() == Some("completed") && words.next() == Some("turn")
    };
    let has_ready_issue = {
        let mut words = pattern.split_whitespace();
        words.next();
        words.next() == Some("has")
            && words.next() == Some("ready")
            && words.next() == Some("issue")
    };
    let schema = if let Some(rest) = pattern.strip_prefix("fact ") {
        rest.split_whitespace().next()?.to_owned()
    } else if first.chars().next().is_some_and(char::is_uppercase) {
        first.to_owned()
    } else if first.contains('.') {
        // Bare dotted reaction `when deploy.finished as d` — typed against a
        // declared `event` (validated at the call site,
        // spec/event-ingress.md).
        first.to_owned()
    } else if completed_turn {
        "AgentTurn".to_owned()
    } else if has_ready_issue {
        "WorkItem".to_owned()
    } else if pattern.starts_with("message from ") {
        // Inbound messaging (spec/messaging.md): `when message from <channel> as
        // msg` binds the generic `Message` envelope, never a domain type.
        "Message".to_owned()
    } else {
        let schema = vcs_sugar_schema(pattern.split(" as ").next().unwrap_or(pattern).trim())?;
        // std.vcs readiness sugar (DR-0052): each phrase binds its
        // builtin observer schema, like `completed turn` -> AgentTurn.
        schema.to_owned()
    };

    Some((binding, schema))
}

/// The builtin observer schema each std.vcs sugar phrase binds.
fn vcs_sugar_schema(phrase: &str) -> Option<&'static str> {
    if phrase == "line changed" || phrase == "line changed by others" {
        return Some("VcsChange");
    }
    if phrase == "reconcile stalled" {
        return Some("VcsStall");
    }
    let words: Vec<&str> = phrase.split_whitespace().collect();
    match words.as_slice() {
        [_, "has", "contention"] => Some("VcsContention"),
        [_, "promoted"] => Some("VcsPromotion"),
        _ => None,
    }
}

pub(crate) fn split_when_guard(when: &str) -> (&str, Option<&str>) {
    match when.split_once(" where ") {
        Some((pattern, guard)) => (pattern.trim(), Some(guard.trim())),
        None => (when.trim(), None),
    }
}

fn effect_binding_schema(
    line: &str,
    kind: &IrEffectKind,
    semantic: &SemanticContext,
) -> Option<String> {
    match kind {
        IrEffectKind::SchemaCoerce => parse_coerce_call_name(line).and_then(|name| {
            semantic
                .coerce_outputs
                .get(name)
                .and_then(schema_name_for_path)
        }),
        IrEffectKind::AgentTell
        | IrEffectKind::CapabilityCall
        | IrEffectKind::EventEmit
        | IrEffectKind::WorkflowInvoke
        | IrEffectKind::TimerWait
        | IrEffectKind::ExecCommand
        | IrEffectKind::TrackerFile
        | IrEffectKind::TrackerClaim
        | IrEffectKind::TrackerRenew
        | IrEffectKind::TrackerRelease
        | IrEffectKind::TrackerFinish
        | IrEffectKind::LeaseAcquire
        | IrEffectKind::LeaseRenew
        | IrEffectKind::LedgerAppend
        | IrEffectKind::CounterConsume
        | IrEffectKind::SignalEmit
        | IrEffectKind::FileRead
        | IrEffectKind::FileWrite
        | IrEffectKind::FileImport
        | IrEffectKind::FileExport => None,
    }
}

fn parse_coerce_call_name(line: &str) -> Option<&str> {
    let rest = line.strip_prefix("coerce ")?;
    rest.split_once('(').map(|(name, _)| name.trim())
}

fn parse_coerce_call(line: &str) -> Option<(&str, Vec<&str>)> {
    let rest = line.strip_prefix("coerce ")?;
    let call = rest.split(" as ").next().unwrap_or(rest).trim();
    let (name, tail) = call.split_once('(')?;
    let (args, _) = tail.rsplit_once(')')?;
    Some((name.trim(), split_expression_args(args)))
}

fn split_expression_args(args: &str) -> Vec<&str> {
    let mut values = Vec::new();
    let mut start = 0usize;
    let mut depth = 0i32;
    let mut in_string = false;
    let mut previous = '\0';
    for (index, ch) in args.char_indices() {
        if ch == '"' && previous != '\\' {
            in_string = !in_string;
        } else if !in_string {
            match ch {
                '(' | '[' | '{' => depth += 1,
                ')' | ']' | '}' => depth -= 1,
                ',' if depth == 0 => {
                    let value = args[start..index].trim();
                    if !value.is_empty() {
                        values.push(value);
                    }
                    start = index + ch.len_utf8();
                }
                _ => {}
            }
        }
        previous = ch;
    }
    let value = args[start..].trim();
    if !value.is_empty() {
        values.push(value);
    }
    values
}

fn effect_payload_statements(body: &str) -> Vec<String> {
    collect_body_statements(body, effect_payload_statement_balance)
}

fn workflow_invoke_statements(body: &str) -> Vec<String> {
    collect_body_statements(body, workflow_invoke_statement_balance)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StatementBalance {
    None,
    Parens,
    Braces,
}

fn collect_body_statements(
    body: &str,
    statement_balance: fn(&str) -> Option<StatementBalance>,
) -> Vec<String> {
    let lines = body.lines().collect::<Vec<_>>();
    let mut statements = Vec::new();
    let mut index = 0usize;
    let mut record_depth = 0i32;
    let mut multiline_string = false;
    while index < lines.len() {
        let trimmed = lines[index].trim();
        if trimmed.is_empty() {
            index += 1;
            continue;
        }
        if multiline_string {
            if trimmed.contains("\"\"\"") {
                multiline_string = false;
            }
            index += 1;
            continue;
        }
        if record_depth > 0 {
            record_depth += brace_delta(trimmed);
            index += 1;
            continue;
        }
        if parse_record_start(trimmed).is_some() {
            record_depth = brace_delta(trimmed).max(1);
            index += 1;
            continue;
        }
        if trimmed.contains("\"\"\"") {
            multiline_string = trimmed.matches("\"\"\"").count() % 2 == 1;
            index += 1;
            continue;
        }
        if let Some(balance) = statement_balance(trimmed) {
            match balance {
                StatementBalance::None => statements.push(trimmed.to_owned()),
                StatementBalance::Parens => {
                    let (statement, next_index) =
                        statement_until_balanced(&lines, index, trimmed, paren_delta);
                    statements.push(statement);
                    index = next_index + 1;
                    continue;
                }
                StatementBalance::Braces => {
                    let (statement, next_index) =
                        statement_until_balanced(&lines, index, trimmed, brace_delta);
                    statements.push(statement);
                    index = next_index + 1;
                    continue;
                }
            }
        }
        index += 1;
    }
    statements
}

fn effect_payload_statement_balance(trimmed: &str) -> Option<StatementBalance> {
    if trimmed.starts_with("coerce ") {
        Some(StatementBalance::Parens)
    } else if trimmed.starts_with("claim ") {
        Some(StatementBalance::None)
    } else {
        None
    }
}

fn workflow_invoke_statement_balance(trimmed: &str) -> Option<StatementBalance> {
    trimmed
        .starts_with("invoke ")
        .then_some(StatementBalance::Braces)
}

fn invoke_statement_parts(statement: &str) -> Option<(&str, &str)> {
    let rest = statement.trim().strip_prefix("invoke ")?;
    let target = rest
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_end_matches('{');
    if target.is_empty() {
        return None;
    }
    let open = statement.find('{')?;
    let mut depth = 0i32;
    let mut close = None;
    for (offset, ch) in statement[open..].char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    close = Some(open + offset);
                    break;
                }
            }
            _ => {}
        }
    }
    let close = close?;
    (close > open).then_some((target, statement[open + 1..close].trim()))
}

fn statement_until_balanced(
    lines: &[&str],
    index: usize,
    trimmed: &str,
    delta: fn(&str) -> i32,
) -> (String, usize) {
    let mut statement = trimmed.to_owned();
    let mut depth = delta(trimmed);
    let mut cursor = index;
    while depth > 0 && cursor + 1 < lines.len() {
        cursor += 1;
        let next = lines[cursor].trim();
        statement.push(' ');
        statement.push_str(next);
        depth += delta(next);
    }
    (statement, cursor)
}

fn paren_delta(line: &str) -> i32 {
    line.chars().fold(0, |depth, ch| match ch {
        '(' => depth + 1,
        ')' => depth - 1,
        _ => depth,
    })
}

/// The hygienic class name synthesized for an inline `decide -> { … } as
/// <binding>`. Dots are illegal in user class names (like the `flow.<name>.seg*`
/// rule convention), so `decide.<rule>.<binding>` can never collide with a
/// declared schema. The lowering pass, the type checker, and the runtime fixture
/// all derive the same name, so the anonymous result shape flows exactly like a
/// named `coerce -> Schema`: `after <binding> succeeds as r` resolves `r`'s
/// fields for `case` dispatch and field access.
pub fn inline_decide_schema_name(rule: &str, binding: &str) -> String {
    format!("decide.{rule}.{binding}")
}

/// A single-identifier `decide` field type is either a primitive keyword
/// (`bool`, `string`, …) or a reference to a declared class/enum. The `decide`
/// grammar only admits single identifiers, so no compound parsing is needed.
fn decide_field_type_syntax(ty: &str, span: SourceSpan) -> TypeSyntax {
    if is_primitive_type(ty) {
        TypeSyntax::Primitive {
            name: ty.to_owned(),
            span,
        }
    } else {
        TypeSyntax::Ref {
            name: Ident {
                name: ty.to_owned(),
                span,
            },
        }
    }
}

/// Collects every inline `decide … as <binding>` in a rule body — recursing
/// through nested after/case/branch/handler blocks — yielding
/// `(binding, result_fields, span)` for synthesis and type registration.
#[allow(clippy::type_complexity)]
fn collect_decide_effects<'a>(
    statements: &'a [body::BodyStmt],
    out: &mut Vec<(&'a str, &'a [(String, String)], SourceSpan)>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let body::BodyEffectKind::Decide { result_fields } = &effect.kind {
                    if let Some(binding) = &effect.binding {
                        out.push((binding.as_str(), result_fields.as_slice(), effect.span));
                    }
                }
            }
            body::BodyStmt::After(after) => collect_decide_effects(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_decide_effects(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// Registers each inline `decide … as <binding>` result as `Ref(decide.<rule>.<binding>)`
/// so the after-binding type flow resolves the anonymous shape's fields, exactly
/// like a named `coerce -> Schema`. The synthesized class is injected into both
/// the semantic schema index and the IR by [`collect_inline_decide_schemas`].
fn collect_decide_payload_types(
    statements: &[body::BodyStmt],
    rule_name: &str,
    payloads: &mut BTreeMap<String, IrType>,
) {
    let mut decides = Vec::new();
    collect_decide_effects(statements, &mut decides);
    for (binding, _fields, _span) in decides {
        payloads.insert(
            binding.to_owned(),
            IrType::Ref(inline_decide_schema_name(rule_name, binding)),
        );
    }
}

fn collect_prompt_payload_types(
    statements: &[body::BodyStmt],
    payloads: &mut BTreeMap<String, IrType>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if matches!(&effect.kind, body::BodyEffectKind::Prompt { .. }) {
                    if let Some(binding) = &effect.binding {
                        payloads
                            .insert(binding.clone(), IrType::Primitive(IrPrimitiveType::String));
                    }
                }
            }
            body::BodyStmt::After(after) => collect_prompt_payload_types(&after.body, payloads),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_prompt_payload_types(&branch.body, payloads);
                }
            }
            _ => {}
        }
    }
}

/// Synthesizes a hygienic `decide.<rule>.<binding>` class for every inline
/// `decide -> { … } as <binding>`, injecting it into both the semantic schema
/// index (so field access / `case` type-check) and the IR (so the runtime
/// fixture can generate the anonymous shape). Mirrors the generated
/// `<Enum>.<Variant>` class synthesis for data-carrying sum-type variants.
fn collect_inline_decide_schemas(
    items: &[Item],
    semantic: &mut SemanticContext,
    ir: &mut IrProgram,
) {
    for item in items {
        let Item::Rule(rule) = item else {
            continue;
        };
        let (body_ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
        let mut decides = Vec::new();
        collect_decide_effects(&body_ast.statements, &mut decides);
        for (binding, fields, span) in decides {
            let name = inline_decide_schema_name(&rule.name.name, binding);
            // Build the field shape once as `TypeSyntax` (the schema-index form),
            // then lower it for the IR so both representations stay in lockstep.
            let mut syntax_fields: BTreeMap<String, TypeSyntax> = BTreeMap::new();
            let mut ir_fields = Vec::new();
            for (field_name, field_ty) in fields {
                let ty = decide_field_type_syntax(field_ty, span);
                ir_fields.push(IrClassField {
                    name: field_name.clone(),
                    ty: lower_type(ty.clone()),
                    is_key: false,
                    presence_condition: None,
                    span,
                });
                syntax_fields.insert(field_name.clone(), ty);
            }
            semantic.schemas.classes.insert(name.clone(), syntax_fields);
            ir.schemas.push(IrSchema::Class(IrClass {
                name,
                fields: ir_fields,
                span,
            }));
        }
    }
}

/// The hygienic synthetic class name for a `redact … as <binding>` projection:
/// `redact.<rule>.<binding>`, holding only the kept fields of the source schema.
pub fn redact_schema_name(rule: &str, binding: &str) -> String {
    format!("redact.{rule}.{binding}")
}

/// Collects every `redact <source> keep [..] as <binding>` in a rule body —
/// recursing through nested after/case/branch/handler blocks — for projected-type
/// synthesis, type registration, and IFC value-flow.
#[allow(clippy::type_complexity)]
fn collect_redact_effects<'a>(
    statements: &'a [body::BodyStmt],
    out: &mut Vec<(&'a str, &'a [String], &'a str, SourceSpan)>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Redact {
                source,
                keep,
                binding,
                span,
            } => out.push((source.as_str(), keep.as_slice(), binding.as_str(), *span)),
            body::BodyStmt::After(after) => collect_redact_effects(&after.body, out),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_redact_effects(&branch.body, out);
                }
            }
            _ => {}
        }
    }
}

/// Resolves binding -> schema name for a rule's redact SOURCES: `when Class as x`
/// matches, plus coerce/decide/exec result bindings. Used only to find the schema
/// a `redact` projects from, so the synthetic projected class copies the kept
/// fields' types. (`after`-alias sources are a documented follow-up; an
/// unresolved source surfaces as an empty projection + a `validate_redactions`
/// diagnostic.) Diagnostics from the reused collector are discarded — the real
/// pass re-emits them.
fn rule_binding_schemas(rule: &RuleDecl, semantic: &SemanticContext) -> BTreeMap<String, String> {
    let mut schemas = binding_types_for_rule(rule);
    let (body_ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
    let mut payloads = collect_effect_payload_types(rule, semantic, &mut Vec::new());
    collect_exec_payload_types(&body_ast.statements, semantic, &mut payloads);
    collect_decide_payload_types(&body_ast.statements, &rule.name.name, &mut payloads);
    collect_redact_payload_types(&body_ast.statements, &rule.name.name, &mut payloads);
    // `after <binding> <predicate> as <alias>` aliases the effect's completed
    // payload schema, so a `coerce … as c` then `after c succeeds as cust` then
    // `redact cust …` resolves (the primary read-then-redact flow). Only
    // payload-carrying predicates are mapped here; terminal predicates
    // (`times out`/`fails`) bind synthetic terminal schemas not usefully redacted.
    for line in rule.body.text.lines() {
        let Some(rest) = line.trim().strip_prefix("after ") else {
            continue;
        };
        let mut words = rest.split_whitespace();
        let Some(binding) = words.next() else {
            continue;
        };
        let Some(predicate) = words.next() else {
            continue;
        };
        if predicate == "times" && words.next() != Some("out") {
            continue;
        }
        let (Some("as"), Some(alias)) = (words.next(), words.next()) else {
            continue;
        };
        let alias = alias.trim_end_matches('{').trim();
        if alias.is_empty() {
            continue;
        }
        if let Some(IrType::Ref(schema)) = payloads.get(binding) {
            schemas.insert(alias.to_owned(), schema.clone());
        }
    }
    for (binding, ty) in payloads {
        if let IrType::Ref(schema) = ty {
            schemas.insert(binding, schema);
        }
    }
    schemas
}

/// Synthesizes a hygienic `redact.<rule>.<binding>` class for every
/// `redact <source> keep [..] as <binding>`, holding ONLY the kept fields of the
/// source schema (with their source types). This is what makes a redaction sound:
/// the projected binding cannot expose a dropped field (accessing one is a
/// type error, since it is absent from the synthetic class), so the lowered IFC
/// label the checker assigns the projection is honoured by the type system too.
/// Mirrors [`collect_inline_decide_schemas`]; run before the rule loop so
/// `analyze_rule` sees the class. A redact chained off an earlier redact's output
/// resolves via the local map built as the pass proceeds.
fn collect_redact_schemas(items: &[Item], semantic: &mut SemanticContext, ir: &mut IrProgram) {
    for item in items {
        let Item::Rule(rule) = item else {
            continue;
        };
        let (body_ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
        let mut redacts = Vec::new();
        collect_redact_effects(&body_ast.statements, &mut redacts);
        if redacts.is_empty() {
            continue;
        }
        let binding_schemas = rule_binding_schemas(rule, semantic);
        let mut local: BTreeMap<String, String> = BTreeMap::new();
        for (source, keep, binding, span) in redacts {
            let name = redact_schema_name(&rule.name.name, binding);
            let source_schema = binding_schemas
                .get(source)
                .cloned()
                .or_else(|| local.get(source).cloned());
            // Clone the kept fields' types out of the source schema first, so the
            // immutable borrow ends before we insert the new class.
            let projected: Vec<(String, TypeSyntax)> = source_schema
                .as_ref()
                .and_then(|schema| semantic.schemas.classes.get(schema))
                .map(|src_fields| {
                    keep.iter()
                        .filter_map(|field| {
                            src_fields.get(field).map(|ty| (field.clone(), ty.clone()))
                        })
                        .collect()
                })
                .unwrap_or_default();
            let mut syntax_fields: BTreeMap<String, TypeSyntax> = BTreeMap::new();
            let mut ir_fields = Vec::new();
            for (field_name, ty) in &projected {
                syntax_fields.insert(field_name.clone(), ty.clone());
                ir_fields.push(IrClassField {
                    name: field_name.clone(),
                    ty: lower_type(ty.clone()),
                    is_key: false,
                    presence_condition: None,
                    span,
                });
            }
            semantic.schemas.classes.insert(name.clone(), syntax_fields);
            ir.schemas.push(IrSchema::Class(IrClass {
                name: name.clone(),
                fields: ir_fields,
                span,
            }));
            local.insert(binding.to_owned(), name);
        }
    }
}

/// Registers each `redact … as <binding>` result as `Ref(redact.<rule>.<binding>)`
/// so field access / `case` through the projection resolves against the kept-only
/// synthetic class (a dropped field is an unknown-field error). Mirrors
/// [`collect_decide_payload_types`].
fn collect_redact_payload_types(
    statements: &[body::BodyStmt],
    rule_name: &str,
    payloads: &mut BTreeMap<String, IrType>,
) {
    let mut redacts = Vec::new();
    collect_redact_effects(statements, &mut redacts);
    for (_source, _keep, binding, _span) in redacts {
        payloads.insert(
            binding.to_owned(),
            IrType::Ref(redact_schema_name(rule_name, binding)),
        );
    }
}

/// Validates each `redact <source> keep [..] as <out>`: the source must resolve to
/// a known schema, and every kept field must exist on it. Fail-closed — an
/// unresolvable source or unknown kept field is a hard error, so a redaction can
/// never silently project nothing (which would carry no data and mask a mistake).
fn validate_redactions(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    semantic: &SemanticContext,
    binding_schemas: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut redacts = Vec::new();
    collect_redact_effects(statements, &mut redacts);
    let mut local: BTreeMap<String, String> = BTreeMap::new();
    for (source, keep, binding, span) in redacts {
        let source_schema = binding_schemas
            .get(source)
            .cloned()
            .or_else(|| local.get(source).cloned());
        local.insert(
            binding.to_owned(),
            redact_schema_name(&rule.name.name, binding),
        );
        let Some(schema) = source_schema else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span,
                message: format!(
                    "rule `{}` redacts `{source}`, which has no known schema",
                    rule.name.name
                ),
                suggestion: Some(
                    "redact a binding with a known record type — a matched `when Class as x`, or a \
                     coerce/decide/exec result"
                        .to_owned(),
                ),
            });
            continue;
        };
        let Some(src_fields) = semantic.schemas.classes.get(&schema) else {
            continue;
        };
        for field in keep {
            if !src_fields.contains_key(field) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span,
                    message: format!(
                        "rule `{}` redacts `{source}` keeping unknown field `{field}` of `{schema}`",
                        rule.name.name
                    ),
                    suggestion: Some(format!("keep a field declared on `{schema}`")),
                });
            }
        }
    }
}

/// Registers the typed result of the single `exec "..." -> Schema as binding`
/// form so `after <binding> succeeds as r` resolves `r`'s fields — the same
/// after-binding type flow a named `coerce -> Schema` already gets. The
/// streaming `-> each Schema` form records one fact per element (not a single
/// bound value), so it is skipped here.
fn collect_exec_payload_types(
    statements: &[body::BodyStmt],
    semantic: &SemanticContext,
    payloads: &mut BTreeMap<String, IrType>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let body::BodyEffectKind::Exec {
                    parse_target: Some(parse),
                    ..
                } = &effect.kind
                {
                    if !parse.each {
                        if let Some(binding) = &effect.binding {
                            if semantic.schemas.class_exists(&parse.schema) {
                                payloads.insert(binding.clone(), IrType::Ref(parse.schema.clone()));
                            }
                        }
                    }
                }
            }
            body::BodyStmt::After(after) => {
                collect_exec_payload_types(&after.body, semantic, payloads)
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    collect_exec_payload_types(&branch.body, semantic, payloads);
                }
            }
            _ => {}
        }
    }
}

/// Collects the schemas an `exec ... -> each` stream records as facts.
fn push_ingest_fact_writes(statements: &[body::BodyStmt], fact_writes: &mut Vec<String>) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                match &effect.kind {
                    body::BodyEffectKind::Exec {
                        parse_target: Some(parse),
                        ..
                    } if parse.each => {
                        fact_writes.push(format!("schema:{}", parse.schema));
                    }
                    // `import <fmt> <Schema>` admits one `<Schema>` fact per row
                    // (spec/std-library/files.md), so a `when <Schema>` rule has a
                    // producer for liveness/effect-graph analysis.
                    body::BodyEffectKind::FileImport { schema, .. } => {
                        fact_writes.push(format!("schema:{schema}"));
                    }
                    _ => {}
                }
            }
            body::BodyStmt::After(after) => push_ingest_fact_writes(&after.body, fact_writes),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    push_ingest_fact_writes(&branch.body, fact_writes);
                }
            }
            _ => {}
        }
    }
}

/// Body-effect operand checks that need schema knowledge:
/// - `timer until <operand>`: a non-literal operand must be a dotted path
///   resolving to a `time`-typed field (spec/scheduled-time.md). Literals were
///   format-validated by the body parser, so anything that still looks like an
///   instant here is a valid literal and passes.
/// - `exec ... -> Schema` / `-> each Schema`: the parse target must name a
///   declared class (spec/json-ingestion.md).
///
/// The coordination safety model (spec/coordination.md): at most one held
/// lease per progression (hard default), exhaustive outcome handling, and
/// the linear must-release discipline (instance terminals auto-release, so
/// a path that ends in `complete`/`fail` is safe without an explicit
/// `release`).
fn validate_coordination_discipline(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut acquires = Vec::new();
    let mut consumes = Vec::new();
    let mut claims = Vec::new();
    collect_coordination_effects(statements, &mut acquires, &mut consumes, &mut claims);

    // std.vcs completion-valued verbs (DR-0052): promote, undo, and
    // transport are exhaustive exactly like acquire — an unwritten
    // refusal arm is a workflow with no policy at the refusal.
    let mut vcs_verbs: Vec<(&'static str, [&'static str; 2], String, SourceSpan)> = Vec::new();
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::Effect(effect) = stmt {
            if let body::BodyEffectKind::ConstructCapabilityCall { keyword, .. } = &effect.kind {
                let arms: Option<(&'static str, [&'static str; 2])> = match keyword.as_str() {
                    "promote" => Some(("promote", ["promoted", "conflicted"])),
                    "undo" => Some(("undo", ["applied", "stranded"])),
                    "transport" => Some(("transport", ["applied", "conflicted"])),
                    _ => None,
                };
                if let (Some((verb, required)), Some(binding)) = (arms, &effect.binding) {
                    vcs_verbs.push((verb, required, binding.clone(), effect.span));
                }
            }
        }
    });
    for (verb, required_arms, binding, span) in &vcs_verbs {
        let mut predicates = BTreeSet::new();
        collect_after_predicates(statements, binding, &mut predicates);
        for required in required_arms {
            if !predicates.contains(*required) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: *span,
                    message: format!(
                        "rule `{}` does not handle the `{required}` outcome of {verb} `{binding}`",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "{verb} outcomes are exhaustive: add `after {binding} {required} {{ ... }}`"
                    )),
                });
            }
        }
    }

    // A `renew <binding>` names ONE OF TWO legitimate referents (T3, mirroring
    // the `release` disambiguation below):
    //   (1) an `acquire ... as <binding>` LEASE binding acquired in this rule —
    //       lowers to `lease.renew` (std.coord); resolves the acquire's recorded
    //       resource/key at runtime;
    //   (2) a `claim <issue> as <binding>` CLAIM binding claimed in this rule —
    //       lowers to `tracker.renew` (std.tracker); resolves the claimed issue
    //       id from the claim's output fact.
    // A `renew <binding>` naming NEITHER renews nothing, so catch the typo at
    // `whip check`. (Scoped to `renew`, which is new.)
    let claim_bindings = collect_claim_bindings(statements);
    let renewable: BTreeSet<&str> = acquires
        .iter()
        .map(|(b, _, _)| b.as_str())
        .chain(claim_bindings.iter().map(String::as_str))
        .collect();
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::Effect(effect) = stmt {
            if let body::BodyEffectKind::LeaseRenew {
                acquire_binding, ..
            } = &effect.kind
            {
                if !renewable.contains(acquire_binding.as_str()) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: format!(
                            "rule `{}` renews unbound coordination binding `{}`",
                            rule.name.name, acquire_binding
                        ),
                        suggestion: Some(format!(
                            "`renew {acquire_binding}` must name a lease acquired here (`acquire ... as {acquire_binding}`) or an issue claimed here (`claim ... as {acquire_binding}`)"
                        )),
                    });
                }
            }
        }
    });

    // A `release <x>` names ONE OF THREE legitimate referents (spec/coordination.md,
    // verified against the corpus + the rule-body matrix test):
    //   (1) an `acquire ... as <x>` LEASE binding acquired in this rule;
    //   (2) a `claim <x> as ...` — the *item* being claimed (the `TrackerClaim.item`,
    //       NOT the claim's `as` binding);
    //   (3) a `when <queue> has ready <x> as <x>` WORK-ITEM binding, released
    //       without a same-rule claim.
    // A naive `acquire ∪ claim-binding` model false-positives forms (2) and (3);
    // admit exactly these three and flag a `release <x>` that matches none as a
    // genuinely-unbound release. Scoped per-rule like the `renew` check above.
    let work_items: Vec<String> = rule
        .whens
        .iter()
        .filter_map(|when| when_has_ready_binding(&when.text))
        .collect();
    let releasable: BTreeSet<&str> = acquires
        .iter()
        .map(|(b, _, _)| b.as_str())
        .chain(claims.iter().map(|(item, _)| item.as_str()))
        .chain(work_items.iter().map(String::as_str))
        .collect();
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::Effect(effect) = stmt {
            if let body::BodyEffectKind::TrackerRelease { item } = &effect.kind {
                if !releasable.contains(item.as_str()) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: effect.span,
                        message: format!(
                            "rule `{}` releases unbound coordination item `{}`",
                            rule.name.name, item
                        ),
                        suggestion: Some(format!(
                            "`release {item}` must name a lease acquired here (`acquire ... as {item}`), an item claimed here (`claim {item} as ...`), or a work item bound by a `when <queue> has ready ... as {item}` reaction"
                        )),
                    });
                }
            }
        }
    });

    if acquires.len() > 1 {
        diagnostics.push(Diagnostic { related: Vec::new(),
            span: acquires[1].2,
            message: format!(
                "rule `{}` acquires more than one lease in a single progression",
                rule.name.name
            ),
            suggestion: Some(
                "the hard default is at most one held lease per progression (it breaks hold-and-wait); restructure into separate rules"
                    .to_owned(),
            ),
        });
    }
    for (binding, until_ttl, span) in &acquires {
        if *until_ttl {
            continue;
        }
        let mut predicates = BTreeSet::new();
        collect_after_predicates(statements, binding, &mut predicates);
        for required in ["held", "contended"] {
            if !predicates.contains(required) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: *span,
                    message: format!(
                        "rule `{}` does not handle the `{required}` outcome of lease `{binding}`",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "coordination outcomes are exhaustive: add `after {binding} {required} {{ ... }}`"
                    )),
                });
            }
        }
        if let Some(held_body) = find_after_body(statements, binding, body::AfterPredicate::Held) {
            if !releases_or_terminates(held_body, binding) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: *span,
                    message: format!(
                        "rule `{}` can hold lease `{binding}` forever: the `held` branch neither releases it nor reaches a workflow terminal",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "add `release {binding}` on every non-terminal path, or use `acquire ... until ttl` for fire-and-forget"
                    )),
                });
            }
        }
    }
    for (binding, span) in &consumes {
        let mut predicates = BTreeSet::new();
        collect_after_predicates(statements, binding, &mut predicates);
        for required in ["ok", "over"] {
            if !predicates.contains(required) {
                diagnostics.push(Diagnostic { related: Vec::new(),
                    span: *span,
                    message: format!(
                        "rule `{}` does not handle the `{required}` outcome of counter consume `{binding}`",
                        rule.name.name
                    ),
                    suggestion: Some(format!(
                        "coordination outcomes are exhaustive: add `after {binding} {required} {{ ... }}`"
                    )),
                });
            }
        }
    }
}

fn collect_coordination_effects(
    statements: &[body::BodyStmt],
    acquires: &mut Vec<(String, bool, SourceSpan)>,
    consumes: &mut Vec<(String, SourceSpan)>,
    claims: &mut Vec<(String, SourceSpan)>,
) {
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::Effect(effect) = stmt {
            match &effect.kind {
                body::BodyEffectKind::LeaseAcquire { until_ttl, .. } => {
                    if let Some(binding) = &effect.binding {
                        acquires.push((binding.clone(), *until_ttl, effect.span));
                    }
                }
                body::BodyEffectKind::CounterConsume { .. } => {
                    if let Some(binding) = &effect.binding {
                        consumes.push((binding.clone(), effect.span));
                    }
                }
                // A `claim <item> as <lease>` makes `<item>` releasable: the
                // releasable referent is the *item* being claimed (the
                // `TrackerClaim.item`), not the claim's `as` binding.
                body::BodyEffectKind::TrackerClaim { item, .. } => {
                    claims.push((item.clone(), effect.span));
                }
                _ => {}
            }
        }
    });
}

/// The work-item binding of a `when <queue> has ready <item> as <binding>`
/// reaction: the `as <binding>` names a claimable/releasable work item pulled
/// off the queue (spec/coordination.md). Returns `None` for every other `when`
/// pattern (plain fact binds are not releasable). Guards (`where ...`) are
/// stripped first so the pattern words line up.
fn when_has_ready_binding(when: &str) -> Option<String> {
    let (pattern, _) = split_when_guard(when);
    let mut words = pattern.split_whitespace();
    let _queue = words.next()?;
    if words.next() == Some("has") && words.next() == Some("ready") {
        return binding_after_as(pattern);
    }
    None
}

fn collect_after_predicates(
    statements: &[body::BodyStmt],
    binding: &str,
    predicates: &mut BTreeSet<&'static str>,
) {
    for_each_body(statements, &mut |stmt| {
        if let body::BodyStmt::After(after) = stmt {
            if after.binding == binding {
                predicates.insert(after.predicate.as_str());
            }
        }
    });
}

fn find_after_body<'a>(
    statements: &'a [body::BodyStmt],
    binding: &str,
    predicate: body::AfterPredicate,
) -> Option<&'a [body::BodyStmt]> {
    for statement in statements {
        match statement {
            body::BodyStmt::After(after) => {
                if after.binding == binding && after.predicate == predicate {
                    return Some(&after.body);
                }
                if let Some(found) = find_after_body(&after.body, binding, predicate) {
                    return Some(found);
                }
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    if let Some(found) = find_after_body(&branch.body, binding, predicate) {
                        return Some(found);
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// Linear must-release, prototype form: a statement list is safe if some
/// statement guarantees release — an explicit `release <binding>`, a
/// workflow terminal (instance-terminal auto-release), a nested after-block
/// that is safe, or a branching construct ALL of whose branches are safe.
fn releases_or_terminates(statements: &[body::BodyStmt], binding: &str) -> bool {
    statements.iter().any(|statement| match statement {
        body::BodyStmt::Effect(effect) => matches!(
            &effect.kind,
            body::BodyEffectKind::TrackerRelease { item } if item == binding
        ),
        body::BodyStmt::Terminal(_) => true,
        body::BodyStmt::After(after) => releases_or_terminates(&after.body, binding),
        body::BodyStmt::Case(case) => {
            !case.branches.is_empty()
                && case
                    .branches
                    .iter()
                    .all(|branch| releases_or_terminates(&branch.body, binding))
        }
        _ => false,
    })
}

fn for_each_body(statements: &[body::BodyStmt], visit: &mut impl FnMut(&body::BodyStmt)) {
    for statement in statements {
        visit(statement);
        match statement {
            body::BodyStmt::After(after) => for_each_body(&after.body, visit),
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    for_each_body(&branch.body, visit);
                }
            }
            _ => {}
        }
    }
}

/// Family B: the `(root, field)` pairs a `case <root>.<disc> { "<lit>" => ... }` arm
/// makes readable — the fields conditioned on `<disc> is "<lit>"`. Empty unless the
/// scrutinee is a single-level `<root>.<disc>` path bound to a schema and the arm
/// pattern is the matching string literal.
fn family_b_arm_allowed(
    scrutinee: &str,
    pattern: &str,
    binding_types: &BTreeMap<String, String>,
    semantic: &SemanticContext,
) -> BTreeSet<(String, String)> {
    let mut allowed = BTreeSet::new();
    let Some((root, disc)) = scrutinee.split_once('.') else {
        return allowed;
    };
    if disc.contains('.') {
        return allowed;
    }
    let trimmed = pattern.trim();
    if trimmed == "_" || trimmed == "default" {
        return allowed;
    }
    let literal = trimmed.trim_matches('"');
    if literal.is_empty() {
        return allowed;
    }
    let Some(schema) = binding_types.get(root) else {
        return allowed;
    };
    if let Some(conditions) = semantic.schemas.presence.get(schema) {
        for (field, (cond_disc, cond_literal)) in conditions {
            if cond_disc == disc && cond_literal == literal {
                allowed.insert((root.to_owned(), field.clone()));
            }
        }
    }
    allowed
}

/// Reject ONE read of `<root>.<field>` when that field is Family B
/// presence-conditioned and `allowed` (the conditioned fields this scope's `case`
/// arm makes present) does not carry it. The single place the diagnostic is
/// worded, so a written read, a `from` shorthand copy, and an implicit `from`
/// copy all report identically.
#[allow(clippy::too_many_arguments)]
fn check_conditioned_read(
    rule: &RuleDecl,
    root: &str,
    field: &str,
    span: SourceSpan,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(schema) = binding_types.get(root) else {
        return;
    };
    let Some((disc, _literal)) = semantic.schemas.field_presence(schema, field) else {
        return;
    };
    if allowed.contains(&(root.to_owned(), field.to_owned())) {
        return;
    }
    diagnostics.push(Diagnostic {
        related: Vec::new(),
        span,
        message: format!(
            "rule `{}` reads conditional field `{root}.{field}` outside a matching `case {root}.{disc}` arm",
            rule.name.name
        ),
        suggestion: Some(format!(
            "read `{root}.{field}` inside `case {root}.{disc} {{ \"...\" => ... }}` — it is present only for a specific `{disc}`"
        )),
    });
}

/// Reject reads of a Family B presence-conditioned field in `text` that are not
/// permitted by `allowed` (the conditioned fields this scope's `case` arm makes
/// present). `text` is any source fragment that may contain dotted field paths.
fn check_conditioned_reads_in_text(
    rule: &RuleDecl,
    text: &str,
    span: SourceSpan,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for (root, path) in dotted_paths(text) {
        let Some(first) = path.first() else {
            continue;
        };
        check_conditioned_read(
            rule,
            &root,
            first,
            span,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        );
    }
}

/// The dotted paths inside a free-text fragment's `{{ … }}` interpolations, which
/// are the only place a prompt or a command string reads a binding. Prose outside
/// the braces is NOT a read — scanning it whole would turn an `e.g.` in an English
/// sentence into a read of a binding named `e`.
fn interpolation_paths(text: &str) -> Vec<(String, Vec<String>)> {
    let mut paths = Vec::new();
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        let after_open = &rest[open + 2..];
        let Some(close) = after_open.find("}}") else {
            break;
        };
        paths.extend(dotted_paths(&after_open[..close]));
        rest = &after_open[close + 2..];
    }
    paths
}

/// Reject conditioned reads in a FREE-TEXT operand — a prompt body, an `exec`
/// command line. Only `{{ … }}` interpolations are scanned (see
/// `interpolation_paths`); the surrounding prose is not source.
fn check_conditioned_reads_in_interpolations(
    rule: &RuleDecl,
    text: &str,
    span: SourceSpan,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for (root, path) in interpolation_paths(text) {
        let Some(first) = path.first() else {
            continue;
        };
        check_conditioned_read(
            rule,
            &root,
            first,
            span,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        );
    }
}

/// `from_binding` is the enclosing statement's `from <binding>` source (`None`
/// when the statement has none). A bare `Shorthand` field copies the same-named
/// field OFF that source, so it is a read of `<from_binding>.<field>` and narrows
/// exactly like a written-out `<from_binding>.<field>` expression. A nested block
/// keeps the same source (nesting introduces no new `from`).
fn check_conditioned_reads_in_fields(
    rule: &RuleDecl,
    fields: &[body::FieldAssign],
    from_binding: Option<&str>,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for field in fields {
        match &field.value {
            body::FieldValue::Expr { source, .. } => check_conditioned_reads_in_text(
                rule,
                source,
                field.span,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::FieldValue::Nested { fields, .. } => check_conditioned_reads_in_fields(
                rule,
                fields,
                from_binding,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::FieldValue::Shorthand => {
                if let Some(root) = from_binding {
                    check_conditioned_read(
                        rule,
                        root,
                        &field.name,
                        field.span,
                        semantic,
                        binding_types,
                        allowed,
                        diagnostics,
                    );
                }
            }
        }
    }
}

/// The copies a `from <binding>` block makes that nobody wrote down. A `from`
/// projection copies EVERY same-named field of the target shape off the source
/// binding, the written block only overriding (`parse_record_fields_with_from` in
/// the kernel is the runtime authority) — so omitting a field name copies it just
/// the same, and a presence-conditioned one is read whether or not it is spelled.
/// `target_fields` is the destination's declared field set, which bounds the copy;
/// fields the block assigns explicitly are not copied and are checked as their own
/// expressions.
#[allow(clippy::too_many_arguments)]
fn check_conditioned_implicit_copies(
    rule: &RuleDecl,
    from_binding: Option<&str>,
    target_fields: Option<&BTreeMap<String, TypeSyntax>>,
    fields: &[body::FieldAssign],
    span: SourceSpan,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let (Some(root), Some(target_fields)) = (from_binding, target_fields) else {
        return;
    };
    let written: BTreeSet<&str> = fields.iter().map(|field| field.name.as_str()).collect();
    for name in target_fields.keys() {
        if written.contains(name.as_str()) {
            continue;
        }
        check_conditioned_read(
            rule,
            root,
            name,
            span,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        );
    }
}

/// A `record <Class> [from <binding>] { … }` in either of its two statement
/// positions (a plain `record`, or the `done … -> record` replacement).
fn check_conditioned_record_reads(
    rule: &RuleDecl,
    record: &body::RecordStmt,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    check_conditioned_reads_in_fields(
        rule,
        &record.fields,
        record.from.as_deref(),
        semantic,
        binding_types,
        allowed,
        diagnostics,
    );
    check_conditioned_implicit_copies(
        rule,
        record.from.as_deref(),
        semantic.schemas.classes.get(&record.schema),
        &record.fields,
        record.span,
        semantic,
        binding_types,
        allowed,
        diagnostics,
    );
}

/// Every read position of one effect statement. An effect is an EGRESS as much as a
/// terminal is — a prompt, a command line, an invoke payload, a coordination key all
/// carry the field's value out of the rule — so a presence-conditioned field is
/// narrowed here exactly as it is in a record or terminal value.
///
/// The `kind` match is wildcard-free on purpose: a new `BodyEffectKind` must state
/// which of its operands are reads rather than inherit silence from a `_` arm. Three
/// operand shapes:
///
///   * EXPRESSION text (`dotted_paths`) — an operand written as an expression:
///     coerce arguments, coordination keys, a timer's `until` path, file paths and
///     bodies, an export predicate, a signal's target instance.
///   * FREE text (`interpolation_paths`, `{{ … }}` only) — a model prompt or an
///     `exec` command line, where the surrounding prose is not source.
///   * FIELD BLOCKS (`check_conditioned_reads_in_fields`) — an invoke payload, a
///     tracker file/finish payload, a ledger row, a signal's override block, which
///     narrow through the same walk record and terminal payloads use.
///
/// Named identifiers are not reads: an agent, capability, workflow, queue, ledger,
/// counter, lease, file store, format, mode, or schema NAME references a declaration,
/// and a bare binding operand (`claim <item>`, `release <item>`, `renew <lease>`,
/// `call … for <binding>`, `exec <capability> with <binding>`) reads the whole
/// binding rather than a conditioned field of it.
fn check_conditioned_effect_reads(
    rule: &RuleDecl,
    effect: &body::EffectStmt,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let span = effect.span;
    let expression = |text: &str, diagnostics: &mut Vec<Diagnostic>| {
        check_conditioned_reads_in_text(
            rule,
            text,
            span,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        );
    };

    // Every effect kind may carry a prompt (`tell`/`prompt`/`decide`/`coerce`
    // bodies), and a prompt is free text: only its interpolations are reads.
    if let Some(prompt) = &effect.prompt {
        check_conditioned_reads_in_interpolations(
            rule,
            &prompt.text,
            span,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        );
    }

    match &effect.kind {
        body::BodyEffectKind::Coerce { args, .. } => {
            for arg in args {
                expression(arg, diagnostics);
            }
        }
        body::BodyEffectKind::ConstructCapabilityCall { fields, .. } => {
            for field in fields {
                expression(&field.source, diagnostics);
            }
        }
        body::BodyEffectKind::Invoke { payload, .. } => check_conditioned_reads_in_fields(
            rule,
            payload,
            // An invoke payload block takes no `from` projection.
            None,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        ),
        body::BodyEffectKind::Timer { until, .. } => {
            if let Some(until) = until {
                expression(until, diagnostics);
            }
        }
        body::BodyEffectKind::Exec {
            target,
            parse_target: _,
        } => match target {
            // A raw command is a string literal: prose plus interpolations.
            body::ExecTarget::RawCommand(command) => {
                check_conditioned_reads_in_interpolations(
                    rule,
                    command,
                    span,
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
            }
            // `with <binding>` pipes the whole binding to stdin.
            body::ExecTarget::Capability { .. } => {}
        },
        body::BodyEffectKind::TrackerFile { fields, .. }
        | body::BodyEffectKind::TrackerFinish { fields, .. }
        | body::BodyEffectKind::LedgerAppend { fields, .. } => check_conditioned_reads_in_fields(
            rule,
            fields,
            None,
            semantic,
            binding_types,
            allowed,
            diagnostics,
        ),
        body::BodyEffectKind::LeaseAcquire { key_expr, .. } => expression(key_expr, diagnostics),
        body::BodyEffectKind::CounterConsume {
            key_expr,
            amount_expr,
            ..
        } => {
            expression(key_expr, diagnostics);
            expression(amount_expr, diagnostics);
        }
        // `emit signal <name> to <target> from <binding> { overrides }` is both an
        // operand position (the target instance) and the third COPY position (the
        // `record … from` precedent, S6): the block overrides, the projection copies
        // every same-named field the signal declares.
        body::BodyEffectKind::Notify {
            target_expr,
            event,
            from,
            fields,
        } => {
            expression(target_expr, diagnostics);
            check_conditioned_reads_in_fields(
                rule,
                fields,
                from.as_deref(),
                semantic,
                binding_types,
                allowed,
                diagnostics,
            );
            check_conditioned_implicit_copies(
                rule,
                from.as_deref(),
                semantic.schemas.classes.get(event),
                fields,
                span,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            );
        }
        body::BodyEffectKind::FileRead { path, .. }
        | body::BodyEffectKind::FileImport { path, .. } => expression(path, diagnostics),
        body::BodyEffectKind::FileWrite { path, body, .. } => {
            expression(path, diagnostics);
            expression(body, diagnostics);
        }
        body::BodyEffectKind::FileExport {
            path, predicate, ..
        } => {
            expression(path, diagnostics);
            if let Some(predicate) = predicate {
                expression(predicate, diagnostics);
            }
        }
        // Prompt-only or name-only kinds: every operand is a declaration name, a
        // bare binding, or the prompt already scanned above.
        body::BodyEffectKind::Tell { .. }
        | body::BodyEffectKind::Prompt { .. }
        | body::BodyEffectKind::Decide { .. }
        | body::BodyEffectKind::Call { .. }
        | body::BodyEffectKind::TrackerClaim { .. }
        | body::BodyEffectKind::TrackerRelease { .. }
        | body::BodyEffectKind::LeaseRenew { .. } => {}
    }
}

/// The declared field set of the workflow output contract a `complete <name> from
/// <binding>` projects onto — the bound on what that projection copies. `None`
/// when the contract is scalar, inline-typed to something other than a class, or
/// not resolvable in this workflow's scope (nothing is claimed about the copy).
fn terminal_output_fields<'a>(
    terminal: &body::TerminalStmt,
    semantic: &'a SemanticContext,
) -> Option<&'a BTreeMap<String, TypeSyntax>> {
    if terminal.kind != body::TerminalKind::Complete {
        return None;
    }
    let workflow = semantic.workflow.as_ref()?;
    let surface = semantic.workflow_inputs.get(workflow)?;
    match surface.outputs.get(&terminal.name)? {
        TypeSyntax::Ref { name } => semantic.schemas.classes.get(&name.name),
        _ => None,
    }
}

/// Family B read-narrowing (discriminated-families-design.md §5.6/§5.7): walk the
/// rule body and reject a read of a presence-conditioned field that is not inside a
/// matching `case <root>.<disc>` arm. Each `case` arm extends `allowed` with the
/// fields its discriminant=literal makes present. Coverage is every read position a
/// rule body has: record/terminal/done/milestone values, branch conditions, case
/// guards, and effect operands (`check_conditioned_effect_reads` — prompts, command
/// lines, payloads, coordination keys). Every `from`-carrying statement passes its
/// source binding down, so both spellings of a copy — the written `Shorthand` field
/// and the field the projection copies implicitly — narrow like the
/// `<binding>.<field>` read each one is.
fn validate_conditioned_field_reads(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    allowed: &BTreeSet<(String, String)>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Record(record) => {
                check_conditioned_record_reads(
                    rule,
                    record,
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
            }
            body::BodyStmt::Terminal(terminal) => {
                check_conditioned_reads_in_fields(
                    rule,
                    &terminal.fields,
                    terminal.from.as_deref(),
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
                check_conditioned_implicit_copies(
                    rule,
                    terminal.from.as_deref(),
                    terminal_output_fields(terminal, semantic),
                    &terminal.fields,
                    terminal.span,
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
                // A bare scalar payload value is also an egress read.
                if let Some(body::FieldValue::Expr { source, .. }) = &terminal.scalar {
                    check_conditioned_reads_in_text(
                        rule,
                        source,
                        terminal.span,
                        semantic,
                        binding_types,
                        allowed,
                        diagnostics,
                    );
                }
            }
            body::BodyStmt::Done {
                replacement: Some(record),
                ..
            } => check_conditioned_record_reads(
                rule,
                record,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::BodyStmt::Milestone { fields, .. } => check_conditioned_reads_in_fields(
                rule,
                fields,
                // `emit milestone` carries no `from` projection.
                None,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::BodyStmt::Effect(effect) => check_conditioned_effect_reads(
                rule,
                effect,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::BodyStmt::Done { .. }
            | body::BodyStmt::Cancel { .. }
            | body::BodyStmt::Redact { .. } => {}
            body::BodyStmt::After(after) => validate_conditioned_field_reads(
                rule,
                &after.body,
                semantic,
                binding_types,
                allowed,
                diagnostics,
            ),
            body::BodyStmt::Region(region) => {
                validate_conditioned_field_reads(
                    rule,
                    &region.body,
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
                validate_conditioned_field_reads(
                    rule,
                    &region.lapse_body,
                    semantic,
                    binding_types,
                    allowed,
                    diagnostics,
                );
            }
            body::BodyStmt::Case(case) => {
                for arm in &case.branches {
                    let mut arm_allowed = allowed.clone();
                    arm_allowed.extend(family_b_arm_allowed(
                        &case.scrutinee,
                        &arm.pattern,
                        binding_types,
                        semantic,
                    ));
                    if let Some(guard) = &arm.guard {
                        check_conditioned_reads_in_text(
                            rule,
                            guard,
                            arm.span,
                            semantic,
                            binding_types,
                            &arm_allowed,
                            diagnostics,
                        );
                    }
                    validate_conditioned_field_reads(
                        rule,
                        &arm.body,
                        semantic,
                        binding_types,
                        &arm_allowed,
                        diagnostics,
                    );
                }
            }
        }
    }
}

fn validate_body_effect_operands(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                match &effect.kind {
                    body::BodyEffectKind::LeaseAcquire { resource, .. }
                        if !semantic.leases.contains(resource) =>
                    {
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` acquires undeclared lease `{resource}`",
                                rule.name.name
                            ),
                            suggestion: Some(format!(
                                "declare `lease {resource} {{ key <Type>  slots <N>  ttl <duration> }}`"
                            )),
                        });
                    }
                    body::BodyEffectKind::LedgerAppend { ledger, schema, .. } => {
                        if !semantic.ledgers.contains(ledger) {
                            diagnostics.push(Diagnostic { related: Vec::new(),
                                span: effect.span,
                                message: format!(
                                    "rule `{}` appends to undeclared ledger `{ledger}`",
                                    rule.name.name
                                ),
                                suggestion: Some(format!(
                                    "declare `ledger {ledger} {{ entry <Type>  partition by <field>  retain <duration> }}`"
                                )),
                            });
                        }
                        if !semantic.schemas.class_exists(schema) {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: effect.span,
                                message: format!(
                                    "rule `{}` appends unknown entry class `{schema}`",
                                    rule.name.name
                                ),
                                suggestion: Some(format!("declare `class {schema}` first")),
                            });
                        }
                    }
                    body::BodyEffectKind::CounterConsume { counter, .. }
                        if !semantic.counters.contains(counter) =>
                    {
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` consumes undeclared counter `{counter}`",
                                rule.name.name
                            ),
                            suggestion: Some(format!(
                                "declare `counter {counter} {{ key <Type>  cap <N>  reset <period> }}`"
                            )),
                        });
                    }
                    _ => {}
                }
                // `exec <name> with <binding>` requires a typed record binding
                // (spec/std-script.md "Static checks" item 4): the binding is
                // serialized to the script's stdin as a typed record, so an
                // unknown or untyped binding cannot cross.
                if let body::BodyEffectKind::Exec {
                    target:
                        body::ExecTarget::Capability {
                            name,
                            stdin_binding,
                        },
                    ..
                } = &effect.kind
                {
                    match binding_types.get(stdin_binding) {
                        None => {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: effect.span,
                                message: format!(
                                    "rule `{}` uses unknown binding `{stdin_binding}` in `exec {name} with {stdin_binding}` — `with` requires a typed record binding",
                                    rule.name.name
                                ),
                                suggestion: Some(format!(
                                    "bind a typed record first (e.g. `when <Class> as {stdin_binding}` or `coerce ... -> <Class> as {stdin_binding}`) and pass that binding to `with`"
                                )),
                            });
                        }
                        // A dotted binding without an indexed payload class is an
                        // untyped runtime fact (`when fact <name> as x`) — no
                        // static record shape crosses to stdin. Non-dotted
                        // unknown classes are already reported at their binding
                        // site (`matches unknown class` / unknown parse schema).
                        Some(schema)
                            if schema.contains('.') && !semantic.schemas.class_exists(schema) =>
                        {
                            diagnostics.push(Diagnostic {
                                related: Vec::new(),
                                span: effect.span,
                                message: format!(
                                    "rule `{}` passes untyped fact binding `{stdin_binding}` to `exec {name} with` — `with` requires a typed record binding",
                                    rule.name.name
                                ),
                                suggestion: Some(format!(
                                    "declare `signal {schema} {{ ... }}` for a typed reaction, or bind a declared class and pass that to `with`"
                                )),
                            });
                        }
                        Some(_) => {}
                    }
                }
                if let body::BodyEffectKind::Exec {
                    parse_target: Some(parse),
                    ..
                } = &effect.kind
                {
                    if !semantic.schemas.class_exists(&parse.schema) {
                        let suggestion =
                            match closest_name(&parse.schema, semantic.schemas.classes.keys()) {
                                Some(candidate) => format!(
                                    "did you mean `{candidate}`? otherwise declare `class {}`",
                                    parse.schema
                                ),
                                None => format!(
                                    "declare `class {}` before parsing into it",
                                    parse.schema
                                ),
                            };
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` parses exec output into unknown schema `{}`",
                                rule.name.name, parse.schema
                            ),
                            suggestion: Some(suggestion),
                        });
                    }
                }
                let body::BodyEffectKind::Timer {
                    until: Some(until), ..
                } = &effect.kind
                else {
                    continue;
                };
                if body::is_iso8601_instant(until) {
                    continue;
                }
                let mut segments = until.split('.');
                let root = segments.next().unwrap_or_default();
                let path = segments.map(str::to_owned).collect::<Vec<_>>();
                let Some(schema) = binding_types.get(root) else {
                    diagnostics.push(Diagnostic { related: Vec::new(),
                        span: effect.span,
                        message: format!(
                            "rule `{}` uses unknown binding `{root}` in `timer until {until}`",
                            rule.name.name
                        ),
                        suggestion: Some(
                            "bind a fact in `when` and reference a `time` field on it, or use an ISO-8601 literal"
                                .to_owned(),
                        ),
                    });
                    continue;
                };
                // Dotted runtime fact bindings are untyped; their fields
                // cannot be statically checked.
                if schema.contains('.') {
                    continue;
                }
                let resolved = if path.is_empty() {
                    Err(format!(
                        "`{root}` is a `{schema}` record, not a `time` value"
                    ))
                } else {
                    semantic.schemas.resolve_field_path(schema, &path)
                };
                match resolved {
                    Ok(TypeSyntax::Primitive { ref name, .. }) if name == "time" => {}
                    Ok(_) => {
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` uses non-time operand `{until}` in `timer until`",
                                rule.name.name
                            ),
                            suggestion: Some(format!(
                                "declare the field as `time` on `{schema}` or use an ISO-8601 literal"
                            )),
                        });
                    }
                    Err(message) => {
                        diagnostics.push(Diagnostic { related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` has invalid `timer until` operand `{until}`: {message}",
                                rule.name.name
                            ),
                            suggestion: Some(
                                "reference a `time`-typed field on a bound fact, or use an ISO-8601 literal"
                                    .to_owned(),
                            ),
                        });
                    }
                }
            }
            body::BodyStmt::After(after) => {
                validate_body_effect_operands(
                    rule,
                    &after.body,
                    semantic,
                    binding_types,
                    diagnostics,
                );
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    validate_body_effect_operands(
                        rule,
                        &branch.body,
                        semantic,
                        binding_types,
                        diagnostics,
                    );
                }
            }
            _ => {}
        }
    }
}

/// The reserved namespace the synthesized progress-view classes live under. A `.`
/// cannot appear in a declared class name, so these can never collide with an
/// author's class — the same guarantee the `<Enum>.<Variant>` sum-type lowering
/// relies on.
const PROGRESS_VIEW_NAMESPACE: &str = "region";

/// DR-0043 Decision 7 obligation 2 — type the lapse arm.
///
/// The `on lapse` arm is spliced out of the canonical (condition-HOLDS) rule body,
/// so *nothing* validated it: not the progress view, and not ordinary bindings
/// either — `fail error { reason task.bogus }` in an arm was accepted in full.
/// This walks the arm text with the rule's binding environment extended by the
/// progress view, against a schema index extended with two synthesized classes:
///
///   `region.<rule>.Progress`  one optional field per step (the step's own settled
///                             payload) plus `steps`
///   `region.<rule>.Steps`     one `string` field per step (its status)
///
/// The DR's four rules then fall out of the ordinary path resolver: a field that is
/// neither a step nor `steps` has no field on Progress; an unknown step has no field
/// on Steps; a path *through* a status hits "is not a schema value"; and a deeper
/// path under a step resolves against that step's own schema because
/// `schema_name_for_path` sees through the optional.
///
/// The same splice hid the arm from Family B read-narrowing, so the arm is walked
/// with that pass too: an arm is an egress position like any other, and the region
/// it belongs to may itself sit inside a `case` arm whose allowances the arm keeps.
fn validate_lapse_arm(
    rule: &RuleDecl,
    region: &IrRegion,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    foreign_schemas: &BTreeMap<String, String>,
    effect_payload_types: &BTreeMap<String, IrType>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let mut schemas = semantic.schemas.clone();
    let mut arm_bindings = binding_types.clone();

    if let Some(view) = &region.lapse_binding {
        let progress = format!("{PROGRESS_VIEW_NAMESPACE}.{}.Progress", rule.name.name);
        let steps = format!("{PROGRESS_VIEW_NAMESPACE}.{}.Steps", rule.name.name);

        let mut progress_fields = BTreeMap::new();
        let mut steps_fields = BTreeMap::new();
        // Derive the step set from `region.effects` — the same list the kernel
        // walks when it pins the view (rule_pass.rs), including the `__then_`
        // strip, so the checker's field set and the runtime's key set cannot
        // drift apart.
        for effect in &region.effects {
            let step = effect
                .binding
                .strip_prefix(then_expand::THEN_BINDING_PREFIX)
                .unwrap_or(&effect.binding)
                .to_owned();
            // A step's status is always a string; its settled value is optional
            // because the arm can run before that step settled — or at all.
            steps_fields.insert(step.clone(), string_ty());
            let settled = match effect_payload_types.get(&effect.binding) {
                Some(IrType::Ref(name)) if semantic.schemas.class_exists(name) => TypeSyntax::Ref {
                    name: Ident {
                        name: name.clone(),
                        span: zero_span(),
                    },
                },
                // No resolvable payload schema: the step reads as a settled scalar,
                // so a bare read is fine and a deeper path correctly errors.
                _ => string_ty(),
            };
            progress_fields.insert(step, optional_ty(settled));
        }
        progress_fields.insert(
            "steps".to_owned(),
            TypeSyntax::Ref {
                name: Ident {
                    name: steps.clone(),
                    span: zero_span(),
                },
            },
        );

        schemas.classes.insert(steps, steps_fields);
        schemas.classes.insert(progress.clone(), progress_fields);
        arm_bindings.insert(view.clone(), progress);
    }

    for line in region.arm_content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        validate_known_field_paths_in_index(
            rule,
            line,
            rule.body.span,
            // The synthesized view classes are local to this check; an ambient
            // binding the arm inherits may still be invoke-derived and resolve in
            // a child's index.
            SchemaScopes {
                local: &schemas,
                foreign: foreign_schemas,
                workflows: &semantic.workflow_inputs,
            },
            &arm_bindings,
            diagnostics,
        );
    }

    // Family B read-narrowing. The arm is an egress like any other body position —
    // `coerce fa(e.region)` in an arm carries the conditioned value out of the
    // instance — and the splice is the only reason the rule-body pass never saw it.
    // The allowed set starts from the `case` arms the region sits inside, so an arm
    // under `case e.kind { "deploy" => … }` keeps that arm's allowances.
    let (arm_ast, _) = body::parse_rule_body(&region.arm_content, 0);
    let mut allowed = BTreeSet::new();
    for (scrutinee, pattern) in &region.arm_case_arms {
        allowed.extend(family_b_arm_allowed(
            scrutinee,
            pattern,
            &arm_bindings,
            semantic,
        ));
    }
    let mut arm_diagnostics = Vec::new();
    validate_conditioned_field_reads(
        rule,
        &arm_ast.statements,
        semantic,
        &arm_bindings,
        &allowed,
        &mut arm_diagnostics,
    );
    // `arm_content` is cut from the then-expanded body text, so offsets into it are
    // not source positions. Every arm diagnostic is reported at the body span, the
    // same span the field-path walk above uses.
    for mut diagnostic in arm_diagnostics {
        diagnostic.span = rule.body.span;
        diagnostics.push(diagnostic);
    }
}

/// No binding in this scope carries a foreign (child-workflow) schema.
static NO_FOREIGN_SCHEMAS: BTreeMap<String, String> = BTreeMap::new();
static NO_WORKFLOW_SURFACES: BTreeMap<String, WorkflowInputSurface> = BTreeMap::new();

/// Which schema index a binding's field paths resolve in.
///
/// A parent that observes a child workflow's result, failure, or milestone
/// payload holds a value whose class may be declared *inside that child*. The
/// class is not nameable in the parent — and must not become nameable, or a
/// child's private types would leak into the parent's declaration space — but
/// its fields are exactly the contract the parent was handed, so the parent's
/// reads resolve in the child's own index. That is structural typing across the
/// workflow boundary, not an import.
///
/// A binding with no `foreign` entry resolves locally, which is every ordinary
/// binding.
#[derive(Clone, Copy)]
struct SchemaScopes<'a> {
    local: &'a SchemaIndex,
    /// Binding -> the child workflow whose index types it.
    foreign: &'a BTreeMap<String, String>,
    workflows: &'a BTreeMap<String, WorkflowInputSurface>,
}

impl<'a> SchemaScopes<'a> {
    fn local(local: &'a SchemaIndex) -> Self {
        Self {
            local,
            foreign: &NO_FOREIGN_SCHEMAS,
            workflows: &NO_WORKFLOW_SURFACES,
        }
    }

    fn index_for(&self, binding: &str) -> &'a SchemaIndex {
        self.foreign
            .get(binding)
            .and_then(|workflow| self.workflows.get(workflow))
            .map_or(self.local, |surface| &surface.schemas)
    }
}

fn validate_known_field_paths(
    rule: &RuleDecl,
    line: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_known_field_paths_at_span(
        rule,
        line,
        rule.body.span,
        semantic,
        binding_types,
        diagnostics,
    );
}

/// `validate_known_field_paths` for a scope that can hold invoke-derived
/// bindings, whose payload classes may live in the child workflow's index.
fn validate_known_field_paths_scoped(
    rule: &RuleDecl,
    line: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    foreign: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_known_field_paths_in_index(
        rule,
        line,
        rule.body.span,
        SchemaScopes {
            local: &semantic.schemas,
            foreign,
            workflows: &semantic.workflow_inputs,
        },
        binding_types,
        diagnostics,
    );
}

fn validate_known_field_paths_at_span(
    rule: &RuleDecl,
    line: &str,
    span: SourceSpan,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    validate_known_field_paths_in_index(
        rule,
        line,
        span,
        SchemaScopes::local(&semantic.schemas),
        binding_types,
        diagnostics,
    );
}

/// `validate_known_field_paths_at_span` against explicit schema scopes rather
/// than the program's index alone. The lapse arm resolves its progress view
/// against an index extended with that region's synthesized view classes, which
/// exist only for the duration of the check; an invoke-derived binding resolves
/// against the child workflow that produced it.
/// What resolving one `<root>.<path>` read established. Callers that only want
/// the diagnostic ignore this; the record-field walk acts on it, because a read
/// it cannot resolve suppresses the literal and expected-value checks that
/// follow it.
#[derive(Clone, Copy, Eq, PartialEq)]
enum FieldPathCheck {
    /// `root` is not a typed binding here. Nothing was checked or reported —
    /// the caller decides whether that means a dangling reference.
    Unbound,
    /// `root` is typed, but its schema is absent from the index consulted. A
    /// child workflow's private class reads this way in a scope that was not
    /// given the child's index. Nothing was checked or reported.
    ///
    /// Distinct from `Resolved` for one caller only: `validate_record_field`
    /// stops the field here rather than running the literal and expected-value
    /// checks against a schema it cannot see. That is observable in a narrow
    /// shape — `expression_path` accepts any expression holding exactly ONE
    /// dotted path, so a brace- or bracket-valued field carrying one reaches
    /// `validate_expected_assignment`, which acts on it. For a bare path both of
    /// those validators return immediately and the distinction does not show.
    SchemaNotIndexed,
    /// The path was resolved. A diagnostic was pushed if it did not.
    Resolved,
}

/// Resolve one `<root>.<path>` read against the index that types `root`, and
/// report an unresolvable one.
///
/// This is the single implementation. It used to exist three times — here, in
/// `validate_scalar_terminal_payload`, and in `validate_record_field` — with the
/// same message and suggestion but three different control flows, so a change to
/// one (scope awareness, say) silently left the other two behind.
fn check_field_path(
    rule: &RuleDecl,
    root: &str,
    path: &[String],
    span: SourceSpan,
    scopes: SchemaScopes,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) -> FieldPathCheck {
    let Some(schema) = binding_types.get(root) else {
        return FieldPathCheck::Unbound;
    };
    let schemas = scopes.index_for(root);
    if !schemas.class_exists(schema) {
        return FieldPathCheck::SchemaNotIndexed;
    }
    if let Err(message) = schemas.resolve_field_path(schema, path) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!(
                "rule `{}` has invalid field path `{root}.{}`: {message}",
                rule.name.name,
                path.join(".")
            ),
            suggestion: Some(
                "use a field declared on the bound schema or add it to the class declaration"
                    .to_owned(),
            ),
        });
    }
    FieldPathCheck::Resolved
}

fn validate_known_field_paths_in_index(
    rule: &RuleDecl,
    line: &str,
    span: SourceSpan,
    scopes: SchemaScopes,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for (root, path) in dotted_paths(line) {
        check_field_path(rule, &root, &path, span, scopes, binding_types, diagnostics);
    }
}

fn dotted_paths(line: &str) -> Vec<(String, Vec<String>)> {
    let bytes = line.as_bytes();
    let mut paths = Vec::new();
    let mut index = 0;

    while index < bytes.len() {
        if !is_ident_start(bytes[index]) {
            index += 1;
            continue;
        }

        let root_start = index;
        index += 1;
        while index < bytes.len() && is_ident_continue(bytes[index]) {
            index += 1;
        }
        let root = &line[root_start..index];
        let mut fields = Vec::new();

        while bytes.get(index) == Some(&b'.')
            && bytes
                .get(index + 1)
                .is_some_and(|byte| is_ident_start(*byte))
        {
            index += 1;
            let field_start = index;
            index += 1;
            while index < bytes.len() && is_ident_continue(bytes[index]) {
                index += 1;
            }
            fields.push(line[field_start..index].to_owned());
        }

        if !fields.is_empty() {
            paths.push((root.to_owned(), fields));
        }
    }

    paths
}

fn interpolation_roots(line: &str) -> Vec<String> {
    let mut roots = Vec::new();
    let mut rest = line;

    while let Some(open) = rest.find("{{") {
        let after_open = &rest[open + 2..];
        let Some(close) = after_open.find("}}") else {
            break;
        };
        let expr = after_open[..close].trim();
        if let Some(root) = expr
            .split(|ch: char| !ch.is_alphanumeric() && ch != '_')
            .find(|part| !part.is_empty())
        {
            roots.push(root.to_owned());
        }
        rest = &after_open[close + 2..];
    }

    roots
}

// `claim` stays bindable: `claim item as claim` is an established idiom and
// the trailing binding position is unambiguous.
const RESERVED_BINDING_KEYWORDS: &[&str] = &[
    "after", "call", "case", "coerce", "complete", "consume", "done", "emit", "fail", "invoke",
    "record", "tell", "when", "where",
];

fn validate_binding_name(
    rule: &RuleDecl,
    binding: &str,
    span: SourceSpan,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if RESERVED_BINDING_KEYWORDS.contains(&binding) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span,
            message: format!(
                "rule `{}` binds reserved keyword `{binding}`",
                rule.name.name
            ),
            suggestion: Some(format!(
                "`{binding}` is a rule body keyword; choose another binding name"
            )),
        });
    }
}

fn closest_name<'a>(target: &str, candidates: impl Iterator<Item = &'a String>) -> Option<String> {
    let target_lower = target.to_lowercase();
    candidates
        .map(|candidate| {
            let distance = edit_distance(&target_lower, &candidate.to_lowercase());
            (distance, candidate)
        })
        .filter(|(distance, candidate)| {
            *distance <= 2 && *distance < target.len().min(candidate.len())
        })
        .min_by_key(|(distance, candidate)| (*distance, candidate.as_str().to_owned()))
        .map(|(_, candidate)| candidate.clone())
}

fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut previous: Vec<usize> = (0..=b.len()).collect();
    let mut current = vec![0usize; b.len() + 1];
    for (i, a_char) in a.iter().enumerate() {
        current[0] = i + 1;
        for (j, b_char) in b.iter().enumerate() {
            let substitution = previous[j] + usize::from(a_char != b_char);
            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[b.len()]
}

fn fact_read_from_when(when: &str) -> String {
    let (pattern, _) = split_when_guard(when);
    let first = pattern.split_whitespace().next().unwrap_or("<empty>");
    if first.chars().next().is_some_and(char::is_uppercase) {
        format!("schema:{first}")
    } else {
        format!("pattern:{pattern}")
    }
}

fn parse_record_start(line: &str) -> Option<(String, Option<String>)> {
    let rest = line.strip_prefix("record ").or_else(|| {
        line.strip_prefix("done ")
            .and_then(|rest| rest.split_once("->"))
            .map(|(_, record)| record.trim())
            .and_then(|record| record.strip_prefix("record "))
    })?;
    let before_brace = rest.split('{').next().unwrap_or(rest).trim();
    let mut parts = before_brace.split_whitespace();
    let schema = parts.next()?.to_owned();
    let from_binding = match (parts.next(), parts.next(), parts.next()) {
        (None, None, None) => None,
        (Some("from"), Some(binding), None) => Some(binding.to_owned()),
        _ => return None,
    };
    Some((schema, from_binding))
}

fn validate_record_field(
    rule: &RuleDecl,
    line: &str,
    record_schema: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some((field, expr)) = record_field_assignment(line) else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` has malformed field assignment in `record {record_schema}`",
                rule.name.name
            ),
            suggestion: Some("write record fields as `field value`".to_owned()),
        });
        return;
    };

    let Some(fields) = semantic.schemas.classes.get(record_schema) else {
        return;
    };
    let Some(field_ty) = fields.get(field) else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("class `{record_schema}` has no field `{field}`"),
            suggestion: Some(format!(
                "add `{field}` to `class {record_schema}` or record an existing field"
            )),
        });
        return;
    };

    if let Some((root, path)) = expression_path(expr) {
        // Local scopes only, for the same reason as the terminal payload above.
        match check_field_path(
            rule,
            &root,
            &path,
            rule.body.span,
            SchemaScopes::local(&semantic.schemas),
            binding_types,
            diagnostics,
        ) {
            // A read this scope cannot resolve says nothing about the literal
            // and expected-value checks below either, so it stops the field
            // here rather than letting them judge a schema they cannot see.
            FieldPathCheck::SchemaNotIndexed => return,
            FieldPathCheck::Resolved => {}
            // A field access whose root is neither a bound name nor a special
            // root is a dangling reference: the binding does not exist.
            FieldPathCheck::Unbound => {
                if let Some(root) = dangling_value_root(expr, known_roots) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` has unknown binding `{root}` in `record {record_schema}` field `{field}`",
                            rule.name.name
                        ),
                        suggestion: Some(
                            "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                                .to_owned(),
                        ),
                    });
                }
            }
        }
    }

    validate_literal_assignment(
        rule,
        record_schema,
        field,
        field_ty,
        expr,
        semantic,
        diagnostics,
    );
    validate_expected_assignment(
        rule,
        record_schema,
        field,
        field_ty,
        expr,
        semantic,
        binding_types,
        diagnostics,
    );
}

fn record_field_assignment(line: &str) -> Option<(&str, &str)> {
    let field_end = line.find(char::is_whitespace)?;
    let field = &line[..field_end];
    let expr = line[field_end..].trim();
    (!field.is_empty() && !expr.is_empty()).then_some((field, expr))
}

/// Roots valid in value positions without being author bindings: the
/// external-event payload and the coerce prompt context. An explicit allowlist
/// so genuine typos are still caught.
const SPECIAL_VALUE_ROOTS: &[&str] = &["external", "ctx"];

/// Collects every binding NAME a rule body introduces, from the parsed AST so it
/// is robust to multi-line prompts and nesting (the line-based effect collectors
/// only track `coerce`/`claim`, so `tell`/`exec`/etc. bindings are invisible to
/// `binding_types`). Used to reject dangling roots in value positions without
/// false-flagging valid effect results, `after` aliases, or case bindings.
fn collect_all_binding_names(statements: &[body::BodyStmt], out: &mut BTreeSet<String>) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let Some(binding) = &effect.binding {
                    out.insert(binding.clone());
                }
            }
            body::BodyStmt::Region(region) => {
                if let Some(view) = &region.lapse_binding {
                    out.insert(view.clone());
                }
                collect_all_binding_names(&region.body, out);
                collect_all_binding_names(&region.lapse_body, out);
            }
            body::BodyStmt::After(after) => {
                if let Some(alias) = &after.alias {
                    out.insert(alias.clone());
                }
                collect_all_binding_names(&after.body, out);
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    if let Some(binding) = &branch.binding {
                        out.insert(binding.clone());
                    }
                    collect_all_binding_names(&branch.body, out);
                }
            }
            // `redact … as <out>` introduces the projected binding `out`.
            body::BodyStmt::Redact { binding, .. } => {
                out.insert(binding.clone());
            }
            body::BodyStmt::Record(_)
            | body::BodyStmt::Done { .. }
            | body::BodyStmt::Terminal(_)
            | body::BodyStmt::Milestone { .. }
            | body::BodyStmt::Cancel { .. } => {}
        }
    }
}

/// A `source`'s `emit <signal>` must name a declared `signal` — the ingestion
/// mirror of the rule-side "reacts to undeclared signal" check on `when <signal>`.
/// Only dotted names are typed signal declarations (a bare name is a class/fact,
/// consistent with the reaction check). Without this a source silently admits a
/// signal fact no rule can react to (rules may only react to declared signals),
/// so ingested data is dropped with no diagnostic — this lifts the guarantee to
/// static `whip check`, symmetric with the clock/file/http source runtime that
/// admits `emit_signal`.
fn validate_source_emit_signal_declared(
    source: &SourceDecl,
    declared_signals: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let signal = &source.emit.signal;
    if signal.contains('.') && !declared_signals.contains(signal) {
        let suggestion = match closest_name(signal, declared_signals.iter()) {
            Some(candidate) => {
                format!("did you mean `{candidate}`? otherwise declare `signal {signal} {{ ... }}`")
            }
            None => format!("declare `signal {signal} {{ ... }}` so rules can react to it"),
        };
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: source.emit.signal_span,
            message: format!(
                "source `{}` emits undeclared signal `{}`",
                source.name.name, signal
            ),
            suggestion: Some(suggestion),
        });
    }

    // The emit fields map the source's observation record onto the signal
    // payload by name. Each `<field> <observe>.<obsfield>` must read a real
    // observation field for this source's kind, else it silently maps null at
    // runtime. The observation schemas below MUST mirror the records built in
    // the CLI source resolvers (`resolve_due_{clock,file,http}_sources`): add a
    // field there → add it here. Unknown providers have no known schema, so
    // their emit fields are not checked (avoids false positives).
    let observation_fields: Option<&[&str]> = match source.provider.name.as_str() {
        "clock" => Some(&[
            "scheduled_at",
            "observed_at",
            "occurrence_id",
            "missed_count",
            "schedule_name",
        ]),
        // `file` observes lines in `path` mode and (path, content-hash)
        // occurrences in `watch` mode (spec/std-ingress.md I2a; content
        // READING stays std.files).
        "file" if source.watch.is_some() => Some(&["path", "content_hash", "watch"]),
        "file" => Some(&["line", "line_index", "path"]),
        "http" => Some(&["item", "item_index", "url"]),
        _ => None,
    };
    // `dedup` reads the same observation record the emit mapping reads: an
    // unknown field would make the admission key silently null at runtime.
    if let (Some(fields), Some(SourceValue::Path { segments, .. })) =
        (observation_fields, &source.dedup)
    {
        if let [field] = segments.as_slice() {
            if !fields.contains(&field.name.as_str()) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: field.span,
                    message: format!(
                        "source `{}` `dedup` reads `{}.{}`, but a `{}` source's observation has no field `{}`",
                        source.name.name,
                        source.observe_binding.name,
                        field.name,
                        source.provider.name,
                        field.name
                    ),
                    suggestion: Some(format!(
                        "available observation fields: {}",
                        fields.join(", ")
                    )),
                });
            }
        }
    }
    if let Some(fields) = observation_fields {
        let observe = &source.observe_binding.name;
        for emit_field in &source.emit.fields {
            let SourceValue::Path {
                binding,
                segments,
                span,
            } = &emit_field.value
            else {
                continue;
            };
            if &binding.name != observe {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: *span,
                    message: format!(
                        "source `{}` emit reads unknown binding `{}`",
                        source.name.name, binding.name
                    ),
                    suggestion: Some(format!(
                        "the source's observation binding is `{observe}` (declared by `observe as {observe}`)"
                    )),
                });
                continue;
            }
            if let Some(obs_field) = segments.first() {
                if !fields.contains(&obs_field.name.as_str()) {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: obs_field.span,
                        message: format!(
                            "source `{}` emit reads `{}.{}`, but a `{}` source's observation has no field `{}`",
                            source.name.name, observe, obs_field.name, source.provider.name, obs_field.name
                        ),
                        suggestion: Some(format!(
                            "available observation fields: {}",
                            fields.join(", ")
                        )),
                    });
                }
            }
        }
    }
}

/// `emit signal <name> to <target>` requires `<name>` to be a declared `signal`
/// — the declaration is the typed payload contract at the emit site, symmetric
/// with the reaction-side "reacts to undeclared signal" check on `when <signal>`
/// (spec/event-ingress.md, "Directed injection"). Without this, an emit of an
/// undeclared signal only fails at runtime when the effect input is built
/// (`whipplescript_kernel::rule_lowering`, "emit signal of undeclared signal");
/// this lifts the same guarantee to static `whip check`. Recurses into
/// `after`/`case`/`branch`/`handler` bodies so a nested emit is covered too.
fn validate_emit_signal_declarations(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    declared_signals: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => {
                if let body::BodyEffectKind::Notify { event, .. } = &effect.kind {
                    if !declared_signals.contains(event) {
                        diagnostics.push(Diagnostic {
                            related: Vec::new(),
                            span: effect.span,
                            message: format!(
                                "rule `{}` emits undeclared signal `{event}`",
                                rule.name.name
                            ),
                            suggestion: Some(format!(
                                "declare `signal {event} {{ ... }}` so the emitted payload is typed and admissible, \
                                 or check the signal name"
                            )),
                        });
                    }
                }
            }
            body::BodyStmt::After(after) => {
                validate_emit_signal_declarations(rule, &after.body, declared_signals, diagnostics)
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    validate_emit_signal_declarations(
                        rule,
                        &branch.body,
                        declared_signals,
                        diagnostics,
                    );
                }
            }
            _ => {}
        }
    }
}

/// Flags dangling roots in the field payloads of body-AST effects that the
/// line-based validators don't reach: `emit`/`notify` (`Notify`), `file item
/// into` (`TrackerFile`), and ledger `append` (`LedgerAppend`). Uses the parsed
/// AST and the same root check as the record/coerce/tell/invoke validators.
fn validate_effect_field_roots(
    rule: &RuleDecl,
    statements: &[body::BodyStmt],
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for statement in statements {
        match statement {
            body::BodyStmt::Effect(effect) => match &effect.kind {
                body::BodyEffectKind::Notify {
                    target_expr,
                    event,
                    from,
                    fields,
                } => {
                    if let Some(from) = from {
                        check_operand_root(
                            rule,
                            &format!("emit `{event}` from"),
                            from,
                            known_roots,
                            diagnostics,
                        );
                    }
                    check_operand_root(
                        rule,
                        &format!("emit `{event}` target"),
                        target_expr,
                        known_roots,
                        diagnostics,
                    );
                    check_field_value_roots(
                        rule,
                        &format!("emit `{event}`"),
                        fields,
                        known_roots,
                        diagnostics,
                    );
                }
                body::BodyEffectKind::TrackerFile { queue, fields } => {
                    check_field_value_roots(
                        rule,
                        &format!("file into `{queue}`"),
                        fields,
                        known_roots,
                        diagnostics,
                    );
                }
                body::BodyEffectKind::TrackerFinish { item, fields } => {
                    check_operand_root(rule, "finish item", item, known_roots, diagnostics);
                    check_field_value_roots(rule, "finish", fields, known_roots, diagnostics);
                }
                body::BodyEffectKind::LedgerAppend { ledger, fields, .. } => {
                    check_field_value_roots(
                        rule,
                        &format!("append to `{ledger}`"),
                        fields,
                        known_roots,
                        diagnostics,
                    );
                }
                body::BodyEffectKind::LeaseAcquire {
                    resource, key_expr, ..
                } => {
                    check_operand_root(
                        rule,
                        &format!("acquire `{resource}` key"),
                        key_expr,
                        known_roots,
                        diagnostics,
                    );
                }
                body::BodyEffectKind::CounterConsume {
                    counter,
                    key_expr,
                    amount_expr,
                } => {
                    check_operand_root(
                        rule,
                        &format!("consume `{counter}` key"),
                        key_expr,
                        known_roots,
                        diagnostics,
                    );
                    check_operand_root(
                        rule,
                        &format!("consume `{counter}` amount"),
                        amount_expr,
                        known_roots,
                        diagnostics,
                    );
                }
                _ => {}
            },
            body::BodyStmt::After(after) => {
                validate_effect_field_roots(rule, &after.body, known_roots, diagnostics)
            }
            body::BodyStmt::Case(case) => {
                for branch in &case.branches {
                    validate_effect_field_roots(rule, &branch.body, known_roots, diagnostics);
                }
            }
            _ => {}
        }
    }
}

/// The single source of truth for value-position root validation: returns the
/// dangling root of a single-path value expression — a `root.field…` access whose
/// root is neither a known binding nor a recognized special root — or `None`.
/// Bare atoms (agents, enum variants, literals) have no path and are ignored; the
/// `"`-guard skips values whose "path" was mis-extracted from inside a string
/// literal. Used by every value-position validator (record/terminal/coerce/tell/
/// invoke/effect payloads/operands).
fn dangling_value_root(value: &str, known_roots: &BTreeSet<String>) -> Option<String> {
    let (root, path) = expression_path(value)?;
    if !path.is_empty()
        && !value.contains('"')
        && !known_roots.contains(&root)
        && !SPECIAL_VALUE_ROOTS.contains(&root.as_str())
    {
        Some(root)
    } else {
        None
    }
}

/// Flags a dangling root in a single effect-operand expression (e.g. an
/// `emit ... to <target>` target, a lease/counter `for <key>` key). Same check
/// as the field/record validators.
fn check_operand_root(
    rule: &RuleDecl,
    context: &str,
    operand: &str,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if let Some(root) = dangling_value_root(operand, known_roots) {
        diagnostics.push(Diagnostic { related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "rule `{}` has unknown binding `{root}` in {context} `{operand}`",
                rule.name.name
            ),
            suggestion: Some(
                "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                    .to_owned(),
            ),
        });
    }
}

fn check_field_value_roots(
    rule: &RuleDecl,
    context: &str,
    fields: &[body::FieldAssign],
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for field in fields {
        match &field.value {
            body::FieldValue::Expr { source, .. } => {
                if let Some(root) = dangling_value_root(source, known_roots) {
                    diagnostics.push(Diagnostic { related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "rule `{}` has unknown binding `{root}` in {context} field `{}`",
                            rule.name.name, field.name
                        ),
                        suggestion: Some(
                            "reference a binding from a `when ... as name` clause, an effect `as` binding, or a `case` pattern"
                                .to_owned(),
                        ),
                    });
                }
            }
            body::FieldValue::Nested { fields, .. } => {
                check_field_value_roots(rule, context, fields, known_roots, diagnostics)
            }
            body::FieldValue::Shorthand => {}
        }
    }
}

/// The complete set of value-position binding roots for a rule: `when` bindings
/// plus every binding the body introduces, collected from the parsed AST.
fn known_roots_for_rule(rule: &RuleDecl) -> BTreeSet<String> {
    let mut roots: BTreeSet<String> = binding_types_for_rule(rule).into_keys().collect();
    let (body_ast, _) = body::parse_rule_body(&rule.body.text, rule.body.span.start);
    collect_all_binding_names(&body_ast.statements, &mut roots);
    roots
}

fn validate_record_blocks(
    rule: &RuleDecl,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    known_roots: &BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for (schema, from_binding, body) in record_blocks(&rule.body.text) {
        // A token where a field NAME was expected is a value the author wrote
        // that nothing consumes. The splitter skips it silently, so
        // `record Out { title  "hello" }` compiled clean and recorded the
        // shorthand's value instead of the literal — a different value than the
        // source says, with no diagnostic anywhere.
        for stray in body::stray_value_tokens(&body) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "rule `{}` has a value with no field name in `record {schema}`: `{stray}`",
                    rule.name.name
                ),
                suggestion: Some(format!(
                    "give it a field name (`<field> {stray}`), or remove it"
                )),
            });
        }
        for assignment in collect_field_assignments(&body) {
            let (field, value) = match assignment {
                RecordFieldAssignment::Value { field, value } => (field, value),
                RecordFieldAssignment::Shorthand { field } => {
                    let value = from_binding
                        .as_ref()
                        .map(|binding| format!("{binding}.{field}"))
                        .unwrap_or_else(|| field.clone());
                    (field, value)
                }
            };
            let line = format!("{field} {value}");
            validate_record_field(
                rule,
                &line,
                &schema,
                semantic,
                binding_types,
                known_roots,
                diagnostics,
            );
        }
    }
}

fn record_blocks(body: &str) -> Vec<(String, Option<String>, String)> {
    let mut blocks = Vec::new();
    let lines = body.lines().collect::<Vec<_>>();
    let mut index = 0usize;
    while index < lines.len() {
        let trimmed = lines[index].trim();
        let Some((schema, from_binding)) = parse_record_start(trimmed) else {
            index += 1;
            continue;
        };
        // Single-line record `record X { f y }`: opens and closes on one line
        // (brace_delta 0), so the multi-line loop below never collects its fields,
        // leaving them unvalidated. Extract the inner content directly.
        if brace_delta(trimmed) == 0 && trimmed.contains('{') {
            if let (Some(open), Some(close)) = (trimmed.find('{'), trimmed.rfind('}')) {
                if close > open {
                    blocks.push((
                        schema,
                        from_binding,
                        trimmed[open + 1..close].trim().to_owned(),
                    ));
                }
            }
            index += 1;
            continue;
        }
        let mut depth = brace_delta(trimmed);
        let mut record_lines = Vec::new();
        index += 1;
        while index < lines.len() && depth > 0 {
            let line = lines[index];
            let before = depth;
            depth += brace_delta(line);
            if !(before == 1 && depth == 0 && line.trim() == "}") {
                record_lines.push(line.to_owned());
            }
            index += 1;
        }
        blocks.push((schema, from_binding, record_lines.join("\n")));
    }
    blocks
}

fn workflow_terminal_blocks(body: &str) -> Vec<(String, String, String)> {
    let mut blocks = Vec::new();
    let lines = body.lines().collect::<Vec<_>>();
    let mut index = 0usize;
    while index < lines.len() {
        let trimmed = lines[index].trim();
        let terminal = trimmed
            .strip_prefix("complete ")
            .map(|rest| ("complete", rest))
            .or_else(|| trimmed.strip_prefix("fail ").map(|rest| ("fail", rest)));
        let Some((action, rest)) = terminal else {
            index += 1;
            continue;
        };
        let Some(name) = rest.split('{').next().and_then(|header| {
            let mut parts = header.split_whitespace();
            match (parts.next(), parts.next()) {
                (Some(name), None) => Some(name.to_owned()),
                _ => None,
            }
        }) else {
            index += 1;
            continue;
        };
        let mut depth = brace_delta(trimmed);
        let mut terminal_lines = Vec::new();
        if depth == 0 && trimmed.contains('{') {
            // Single-line block: `complete <name> { <fields> }` opens and closes
            // on this line, so its inner content never reaches the multi-line loop
            // below. Capture the content between the braces as the block body.
            if let (Some(open), Some(close)) = (trimmed.find('{'), trimmed.rfind('}')) {
                if close > open {
                    let inner = trimmed[open + 1..close].trim();
                    if !inner.is_empty() {
                        terminal_lines.push(inner.to_owned());
                    }
                }
            }
            index += 1;
        } else {
            index += 1;
            while index < lines.len() && depth > 0 {
                let line = lines[index];
                let before = depth;
                depth += brace_delta(line);
                if !(before == 1 && depth == 0 && line.trim() == "}") {
                    terminal_lines.push(line.to_owned());
                }
                index += 1;
            }
        }
        blocks.push((action.to_owned(), name, terminal_lines.join("\n")));
    }
    blocks
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum RecordFieldAssignment {
    Value { field: String, value: String },
    Shorthand { field: String },
}

fn collect_field_assignments(body: &str) -> Vec<RecordFieldAssignment> {
    // Token-level splitting (R5): structure comes from tokens, never line
    // breaks, so a single-line multi-field payload
    // (`complete result { first "a" second "b" }`) collects every field —
    // the same splitter the kernel and table rows already use.
    body::split_field_assignments(body)
        .into_iter()
        .map(|assignment| match assignment.value {
            Some(value) => RecordFieldAssignment::Value {
                field: assignment.name,
                value,
            },
            None => RecordFieldAssignment::Shorthand {
                field: assignment.name,
            },
        })
        .collect()
}

fn expression_path(expr: &str) -> Option<(String, Vec<String>)> {
    let mut paths = dotted_paths(expr);
    if paths.len() != 1 {
        return None;
    }
    Some(paths.remove(0))
}

fn validate_literal_assignment(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    field_ty: &TypeSyntax,
    expr: &str,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(literal) = parse_literal_expr(expr) else {
        return;
    };

    match field_ty {
        TypeSyntax::Primitive { name, .. } => {
            validate_primitive_literal(rule, record_schema, field, name, &literal, diagnostics)
        }
        TypeSyntax::LiteralString { value, .. } => {
            if literal != LiteralExpr::String(value.as_str()) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "field `{record_schema}.{field}` expects literal string `{value}`"
                    ),
                    suggestion: Some(format!("record `{field} {value:?}`")),
                });
            }
        }
        TypeSyntax::Ref { name } => {
            validate_enum_literal(
                rule,
                record_schema,
                field,
                &name.name,
                &literal,
                semantic,
                diagnostics,
            );
        }
        TypeSyntax::Union { variants, .. } => {
            validate_union_literal(rule, record_schema, field, variants, &literal, diagnostics);
        }
        TypeSyntax::AgentRef { agents, .. } => {
            validate_agent_ref_literal(rule, record_schema, field, agents, &literal, diagnostics);
        }
        TypeSyntax::Optional { inner, .. } => {
            if literal != LiteralExpr::Null {
                validate_literal_assignment(
                    rule,
                    record_schema,
                    field,
                    inner,
                    expr,
                    semantic,
                    diagnostics,
                );
            }
        }
        TypeSyntax::Array { .. } | TypeSyntax::Map { .. } => {}
    }
}

#[allow(clippy::too_many_arguments)]
fn validate_expected_assignment(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    field_ty: &TypeSyntax,
    expr: &str,
    semantic: &SemanticContext,
    binding_types: &BTreeMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !(expr.trim_start().starts_with('{') || expr.trim_start().starts_with('[')) {
        return;
    }
    validate_expr_source_against_type(
        rule,
        record_schema,
        field,
        field_ty,
        expr,
        semantic,
        &ExprScope::from_bindings(binding_types),
        diagnostics,
    );
}

#[allow(clippy::too_many_arguments)]
fn validate_expr_source_against_type(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    expected_ty: &TypeSyntax,
    expr: &str,
    semantic: &SemanticContext,
    scope: &ExprScope,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match expected_ty {
        TypeSyntax::Map { inner, .. } => {
            let parsed = match parse_expression(expr) {
                Ok(Expr::Object(fields)) => fields,
                Ok(_) => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!("field `{record_schema}.{field}` expects a map literal"),
                        suggestion: Some(format!("record `{field} {{ key value }}`")),
                    });
                    return;
                }
                Err(message) => {
                    diagnostics.push(Diagnostic {
                        related: Vec::new(),
                        span: rule.body.span,
                        message: format!(
                            "field `{record_schema}.{field}` expects a map literal: {message}"
                        ),
                        suggestion: Some(format!("record `{field} {{ key value }}`")),
                    });
                    return;
                }
            };
            for map_field in &parsed {
                validate_expr_against_type(
                    rule,
                    record_schema,
                    field,
                    inner,
                    &map_field.value,
                    semantic,
                    scope,
                    diagnostics,
                );
            }
        }
        TypeSyntax::Array { inner, .. } => match parse_expression(expr) {
            Ok(Expr::Array(items)) => {
                for item in items {
                    validate_expr_against_type(
                        rule,
                        record_schema,
                        field,
                        inner,
                        &item,
                        semantic,
                        scope,
                        diagnostics,
                    );
                }
            }
            Ok(expr) => validate_inferred_assignment_type(
                rule,
                record_schema,
                field,
                expected_ty,
                &expr,
                semantic,
                scope,
                diagnostics,
            ),
            Err(message) => {
                push_invalid_assignment_expr(rule, record_schema, field, message, diagnostics)
            }
        },
        TypeSyntax::Optional { inner, .. } => {
            if expr.trim() != "null" {
                validate_expr_source_against_type(
                    rule,
                    record_schema,
                    field,
                    inner,
                    expr,
                    semantic,
                    scope,
                    diagnostics,
                );
            }
        }
        TypeSyntax::Ref { name } if semantic.schemas.class_exists(&name.name) => {
            let parsed = match parse_expression(expr) {
                Ok(Expr::Object(fields)) => fields,
                Ok(expr) => {
                    validate_inferred_assignment_type(
                        rule,
                        record_schema,
                        field,
                        expected_ty,
                        &expr,
                        semantic,
                        scope,
                        diagnostics,
                    );
                    return;
                }
                Err(message) => {
                    push_invalid_assignment_expr(rule, record_schema, field, message, diagnostics);
                    return;
                }
            };
            validate_object_literal_fields(
                rule,
                record_schema,
                field,
                &name.name,
                &parsed,
                semantic,
                scope,
                diagnostics,
            );
        }
        _ => match parse_expression(expr) {
            Ok(expr) => validate_inferred_assignment_type(
                rule,
                record_schema,
                field,
                expected_ty,
                &expr,
                semantic,
                scope,
                diagnostics,
            ),
            Err(message) => {
                push_invalid_assignment_expr(rule, record_schema, field, message, diagnostics)
            }
        },
    }
}

#[allow(clippy::too_many_arguments)]
fn validate_expr_against_type(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    expected_ty: &TypeSyntax,
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match expr {
        Expr::Array(items) if matches!(expected_ty, TypeSyntax::Array { .. }) => {
            if let TypeSyntax::Array { inner, .. } = expected_ty {
                for item in items {
                    validate_expr_against_type(
                        rule,
                        record_schema,
                        field,
                        inner,
                        item,
                        semantic,
                        scope,
                        diagnostics,
                    );
                }
            }
        }
        Expr::Object(fields) => match expected_ty {
            TypeSyntax::Map { inner, .. } => {
                for field in fields {
                    validate_expr_against_type(
                        rule,
                        record_schema,
                        field.key.as_str(),
                        inner,
                        &field.value,
                        semantic,
                        scope,
                        diagnostics,
                    );
                }
            }
            TypeSyntax::Ref { name } if semantic.schemas.class_exists(&name.name) => {
                validate_object_literal_fields(
                    rule,
                    record_schema,
                    field,
                    &name.name,
                    fields,
                    semantic,
                    scope,
                    diagnostics,
                );
            }
            _ => validate_inferred_assignment_type(
                rule,
                record_schema,
                field,
                expected_ty,
                expr,
                semantic,
                scope,
                diagnostics,
            ),
        },
        _ => validate_inferred_assignment_type(
            rule,
            record_schema,
            field,
            expected_ty,
            expr,
            semantic,
            scope,
            diagnostics,
        ),
    }
}

fn push_invalid_assignment_expr(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    message: String,
    diagnostics: &mut Vec<Diagnostic>,
) {
    diagnostics.push(Diagnostic {
        related: Vec::new(),
        span: rule.body.span,
        message: format!(
            "rule `{}` has invalid expression for field `{record_schema}.{field}`: {message}",
            rule.name.name
        ),
        suggestion: Some(
            "use array literals or expected-schema object literals for collection fields"
                .to_owned(),
        ),
    });
}

#[allow(clippy::too_many_arguments)]
fn validate_object_literal_fields(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    object_schema: &str,
    object_fields: &[ExprObjectField],
    semantic: &SemanticContext,
    scope: &ExprScope,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(schema_fields) = semantic.schemas.classes.get(object_schema) else {
        return;
    };
    let mut seen = BTreeSet::new();
    for object_field in object_fields {
        if !seen.insert(object_field.key.clone()) {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "field `{record_schema}.{field}` repeats object field `{}`",
                    object_field.key
                ),
                suggestion: Some("remove the duplicate object field".to_owned()),
            });
            continue;
        }
        let Some(field_ty) = schema_fields.get(&object_field.key) else {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!(
                    "class `{object_schema}` has no field `{}`",
                    object_field.key
                ),
                suggestion: Some(format!(
                    "add `{}` to `class {object_schema}` or use an existing field",
                    object_field.key
                )),
            });
            continue;
        };
        validate_expr_against_type(
            rule,
            object_schema,
            &object_field.key,
            field_ty,
            &object_field.value,
            semantic,
            scope,
            diagnostics,
        );
    }
    for (required, ty) in schema_fields {
        if seen.contains(required) || matches!(ty, TypeSyntax::Optional { .. }) {
            continue;
        }
        diagnostics.push(Diagnostic { related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "field `{record_schema}.{field}` is missing required object field `{object_schema}.{required}`"
            ),
            suggestion: Some(format!("add `{required}` to the `{field}` object literal")),
        });
    }
}

#[allow(clippy::too_many_arguments)]
fn validate_inferred_assignment_type(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    expected_ty: &TypeSyntax,
    expr: &Expr,
    semantic: &SemanticContext,
    scope: &ExprScope,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let literal = expr_literal_as_literal_expr(expr);
    if let Some(literal) = literal {
        validate_literal_against_type(
            rule,
            record_schema,
            field,
            expected_ty,
            &literal,
            semantic,
            diagnostics,
        );
        return;
    }

    let context = ExprValidationContext::rule(rule);
    let mut local_diagnostics = Vec::new();
    let actual_ty = infer_expr_type(expr, semantic, scope, &context, &mut local_diagnostics);
    diagnostics.extend(local_diagnostics);
    let expected_expr_ty = expr_type_from_type_syntax(expected_ty, semantic);
    if !types_comparable(&actual_ty, &expected_expr_ty) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "field `{record_schema}.{field}` receives incompatible expression type"
            ),
            suggestion: Some(format!(
                "record a value compatible with `{}`",
                expected_ty.to_source()
            )),
        });
    }
}

fn validate_literal_against_type(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    field_ty: &TypeSyntax,
    literal: &LiteralExpr<'_>,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    match field_ty {
        TypeSyntax::Primitive { name, .. } => {
            validate_primitive_literal(rule, record_schema, field, name, literal, diagnostics)
        }
        TypeSyntax::LiteralString { value, .. } => {
            if literal != &LiteralExpr::String(value.as_str()) {
                diagnostics.push(Diagnostic {
                    related: Vec::new(),
                    span: rule.body.span,
                    message: format!(
                        "field `{record_schema}.{field}` expects literal string `{value}`"
                    ),
                    suggestion: Some(format!("record `{field} {value:?}`")),
                });
            }
        }
        TypeSyntax::Ref { name } => {
            validate_enum_literal(
                rule,
                record_schema,
                field,
                &name.name,
                literal,
                semantic,
                diagnostics,
            );
        }
        TypeSyntax::Union { variants, .. } => {
            validate_union_literal(rule, record_schema, field, variants, literal, diagnostics);
        }
        TypeSyntax::AgentRef { agents, .. } => {
            validate_agent_ref_literal(rule, record_schema, field, agents, literal, diagnostics);
        }
        TypeSyntax::Optional { inner, .. } => {
            if literal != &LiteralExpr::Null {
                validate_literal_against_type(
                    rule,
                    record_schema,
                    field,
                    inner,
                    literal,
                    semantic,
                    diagnostics,
                );
            }
        }
        TypeSyntax::Array { .. } | TypeSyntax::Map { .. } => {}
    }
}

fn expr_literal_as_literal_expr(expr: &Expr) -> Option<LiteralExpr<'_>> {
    match expr {
        Expr::Literal(ExprLiteral::String(value)) => Some(LiteralExpr::String(value)),
        Expr::Literal(ExprLiteral::Number(value)) => Some(LiteralExpr::Number(value)),
        Expr::Literal(ExprLiteral::Bool(_)) => Some(LiteralExpr::Bool),
        Expr::Literal(ExprLiteral::Null) => Some(LiteralExpr::Null),
        Expr::Literal(ExprLiteral::Ident(value)) => Some(LiteralExpr::Ident(value)),
        _ => None,
    }
}

fn validate_agent_ref_literal(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    agents: &[Ident],
    literal: &LiteralExpr<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let allowed = agents
        .iter()
        .map(|agent| agent.name.as_str())
        .collect::<Vec<_>>();
    if let LiteralExpr::String(value) = literal {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "field `{record_schema}.{field}` expects an AgentRef value, not string `{value}`"
            ),
            suggestion: Some(format!(
                "use an unquoted declared agent name: {}",
                allowed.join(", ")
            )),
        });
        return;
    }
    let LiteralExpr::Ident(value) = literal else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` expects an AgentRef value"),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
        return;
    };
    if !allowed.contains(value) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` cannot reference agent `{value}`"),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
    }
}

fn parse_literal_expr(expr: &str) -> Option<LiteralExpr<'_>> {
    let expr = expr.trim().trim_end_matches(',');
    if let Some(value) = expr
        .strip_prefix('"')
        .and_then(|rest| rest.strip_suffix('"'))
    {
        return Some(LiteralExpr::String(value));
    }
    if expr.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
        && expr.chars().any(|ch| ch.is_ascii_digit())
    {
        return Some(LiteralExpr::Number(expr));
    }
    match expr {
        "true" => Some(LiteralExpr::Bool),
        "false" => Some(LiteralExpr::Bool),
        "null" => Some(LiteralExpr::Null),
        value if value.chars().all(|ch| ch.is_alphanumeric() || ch == '_') => {
            Some(LiteralExpr::Ident(value))
        }
        _ => None,
    }
}

struct ExprParser<'a> {
    source: &'a str,
    tokens: Vec<ExprToken>,
    pos: usize,
    depth: usize,
}

/// Recursion-depth ceiling for the guard-expression grammar. Every level of
/// `(`/`[`/`{` nesting and every prefix `!`/`not` descends through
/// `parse_unary`, so bounding it there stops a deeply-nested expression in a
/// workflow file from overflowing the stack and aborting the process — a
/// normal `Err` diagnostic is returned instead. Far above any real expression.
const MAX_EXPR_DEPTH: usize = 256;

#[derive(Clone, Debug, Eq, PartialEq)]
struct ExprToken {
    kind: ExprTokenKind,
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum ExprTokenKind {
    Ident(String),
    String(String),
    Number(String),
    Symbol(char),
    Op(&'static str),
}

impl<'a> ExprParser<'a> {
    fn new(source: &'a str) -> Self {
        Self {
            source,
            tokens: lex_expr(source),
            pos: 0,
            depth: 0,
        }
    }

    fn parse(mut self) -> Result<Expr, String> {
        let expr = self.parse_or()?;
        if self.peek().is_some() {
            return Err(format!(
                "unexpected token in expression `{}`",
                self.source.trim()
            ));
        }
        Ok(expr)
    }

    fn parse_or(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_and()?;
        while self.consume_op("||") || self.consume_ident("or") {
            let right = self.parse_and()?;
            expr = Expr::Binary {
                op: BinaryOp::Or,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }
        Ok(expr)
    }

    fn parse_and(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_comparison()?;
        while self.consume_op("&&") || self.consume_ident("and") {
            let right = self.parse_comparison()?;
            expr = Expr::Binary {
                op: BinaryOp::And,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }
        Ok(expr)
    }

    fn parse_comparison(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_additive()?;
        loop {
            let op = if self.consume_op("==") {
                Some(BinaryOp::Eq)
            } else if self.consume_op("!=") {
                Some(BinaryOp::Ne)
            } else if self.consume_op("<=") {
                Some(BinaryOp::Le)
            } else if self.consume_op(">=") {
                Some(BinaryOp::Ge)
            } else if self.consume_symbol('<') {
                Some(BinaryOp::Lt)
            } else if self.consume_symbol('>') {
                Some(BinaryOp::Gt)
            } else if self.consume_ident("not") {
                if !self.consume_ident("in") {
                    return Err("expected `in` after `not`".to_owned());
                }
                Some(BinaryOp::NotIn)
            } else if self.consume_ident("in") {
                Some(BinaryOp::In)
            } else {
                None
            };
            let Some(op) = op else {
                return Ok(expr);
            };
            let right = self.parse_additive()?;
            expr = Expr::Binary {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }
    }

    fn parse_additive(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_multiplicative()?;
        loop {
            let op = if self.consume_symbol('+') {
                Some(BinaryOp::Add)
            } else if self.consume_symbol('-') {
                Some(BinaryOp::Sub)
            } else {
                None
            };
            let Some(op) = op else {
                return Ok(expr);
            };
            let right = self.parse_multiplicative()?;
            expr = Expr::Binary {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }
    }

    fn parse_multiplicative(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_unary()?;
        loop {
            let op = if self.consume_symbol('*') {
                Some(BinaryOp::Mul)
            } else if self.consume_symbol('/') {
                Some(BinaryOp::Div)
            } else {
                None
            };
            let Some(op) = op else {
                return Ok(expr);
            };
            let right = self.parse_unary()?;
            expr = Expr::Binary {
                op,
                left: Box::new(expr),
                right: Box::new(right),
            };
        }
    }

    fn parse_unary(&mut self) -> Result<Expr, String> {
        // Depth guard (every nesting level descends through here): return a
        // diagnostic rather than recurse the native stack to a crash.
        self.depth += 1;
        if self.depth > MAX_EXPR_DEPTH {
            self.depth -= 1;
            return Err(format!(
                "expression in `{}` is nested too deeply (limit {MAX_EXPR_DEPTH})",
                self.source.trim()
            ));
        }
        let result = self.parse_unary_inner();
        self.depth -= 1;
        result
    }

    fn parse_unary_inner(&mut self) -> Result<Expr, String> {
        if self.consume_symbol('!') {
            return Ok(Expr::Unary {
                op: UnaryOp::Not,
                expr: Box::new(self.parse_unary()?),
            });
        }
        // Prefix `not` binds looser than comparisons so `not x in y`
        // reads as `not (x in y)`; binary `not in` is handled by
        // parse_comparison before this prefix form is reached.
        if self.consume_ident("not") {
            return Ok(Expr::Unary {
                op: UnaryOp::Not,
                expr: Box::new(self.parse_comparison()?),
            });
        }
        self.parse_postfix()
    }

    fn parse_postfix(&mut self) -> Result<Expr, String> {
        let mut expr = self.parse_primary()?;
        loop {
            if self.consume_symbol('[') {
                let key = self.parse_or()?;
                self.expect_symbol(']')?;
                expr = Expr::Index {
                    target: Box::new(expr),
                    key: Box::new(key),
                };
                continue;
            }
            return Ok(expr);
        }
    }

    fn parse_primary(&mut self) -> Result<Expr, String> {
        if self.consume_symbol('(') {
            let expr = self.parse_or()?;
            self.expect_symbol(')')?;
            return Ok(expr);
        }
        if self.consume_symbol('[') {
            let mut items = Vec::new();
            if self.consume_symbol(']') {
                return Ok(Expr::Array(items));
            }
            loop {
                items.push(self.parse_or()?);
                if self.consume_symbol(']') {
                    break;
                }
                self.expect_symbol(',')?;
            }
            return Ok(Expr::Array(items));
        }
        if self.consume_symbol('{') {
            let mut fields = Vec::new();
            if self.consume_symbol('}') {
                return Ok(Expr::Object(fields));
            }
            loop {
                let key = match self.advance().map(|token| token.kind.clone()) {
                    Some(ExprTokenKind::Ident(value) | ExprTokenKind::String(value)) => value,
                    _ => return Err("expected object field name".to_owned()),
                };
                let value = self.parse_or()?;
                fields.push(ExprObjectField { key, value });
                if self.consume_symbol('}') {
                    break;
                }
                let _ = self.consume_symbol(',');
            }
            return Ok(Expr::Object(fields));
        }
        match self.advance().map(|token| token.kind.clone()) {
            Some(ExprTokenKind::String(value)) => Ok(Expr::Literal(ExprLiteral::String(value))),
            Some(ExprTokenKind::Number(value)) => Ok(Expr::Literal(ExprLiteral::Number(value))),
            Some(ExprTokenKind::Ident(value)) if value == "true" => {
                Ok(Expr::Literal(ExprLiteral::Bool(true)))
            }
            Some(ExprTokenKind::Ident(value)) if value == "false" => {
                Ok(Expr::Literal(ExprLiteral::Bool(false)))
            }
            Some(ExprTokenKind::Ident(value)) if value == "null" => {
                Ok(Expr::Literal(ExprLiteral::Null))
            }
            Some(ExprTokenKind::Ident(value)) if value == "exists" && !self.at_symbol('(') => {
                let arg = match self.parse_postfix()? {
                    Expr::Literal(ExprLiteral::Ident(path)) => Expr::Path(vec![path]),
                    expr => expr,
                };
                Ok(Expr::Call {
                    name: value,
                    args: vec![arg],
                })
            }
            Some(ExprTokenKind::Ident(value))
                if matches!(value.as_str(), "count" | "exists" | "empty")
                    && self.at_symbol('(') =>
            {
                self.expect_symbol('(')?;
                if let Some(query) = self.try_parse_query()? {
                    self.expect_symbol(')')?;
                    Ok(Expr::Call {
                        name: value,
                        args: vec![query],
                    })
                } else {
                    let mut args = Vec::new();
                    if self.consume_symbol(')') {
                        return Ok(Expr::Call { name: value, args });
                    }
                    loop {
                        args.push(self.parse_or()?);
                        if self.consume_symbol(')') {
                            break;
                        }
                        self.expect_symbol(',')?;
                    }
                    Ok(Expr::Call { name: value, args })
                }
            }
            Some(ExprTokenKind::Ident(value)) => {
                let mut path = vec![value];
                while self.consume_symbol('.') {
                    let Some(ExprTokenKind::Ident(field)) =
                        self.advance().map(|token| token.kind.clone())
                    else {
                        return Err("expected field name after `.`".to_owned());
                    };
                    path.push(field);
                }
                if path.len() == 1 {
                    Ok(Expr::Literal(ExprLiteral::Ident(path.remove(0))))
                } else {
                    Ok(Expr::Path(path))
                }
            }
            _ => Err(format!("expected expression in `{}`", self.source.trim())),
        }
    }

    fn try_parse_query(&mut self) -> Result<Option<Expr>, String> {
        let checkpoint = self.pos;
        let kind = if self.consume_ident("effect") {
            QueryKind::Effect
        } else if matches!(
            self.peek().map(|token| &token.kind),
            Some(ExprTokenKind::Ident(value)) if value.chars().next().is_some_and(char::is_uppercase)
        ) {
            QueryKind::Fact
        } else {
            return Ok(None);
        };
        let mut head = Vec::new();
        while let Some(token) = self.peek() {
            if self.at_symbol(')') || self.at_ident("where") {
                break;
            }
            head.push(self.token_text(token));
            self.pos += 1;
        }
        if head.is_empty() {
            self.pos = checkpoint;
            return Ok(None);
        }
        let guard = if self.consume_ident("where") {
            Some(Box::new(self.parse_or()?))
        } else {
            None
        };
        Ok(Some(Expr::Query {
            kind,
            head: join_query_head(&head),
            guard,
        }))
    }

    fn token_text(&self, token: &ExprToken) -> String {
        match &token.kind {
            ExprTokenKind::Ident(value) | ExprTokenKind::Number(value) => value.clone(),
            ExprTokenKind::String(value) => format!("{value:?}"),
            ExprTokenKind::Symbol(value) => value.to_string(),
            ExprTokenKind::Op(value) => value.to_string(),
        }
    }

    fn peek(&self) -> Option<&ExprToken> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<&ExprToken> {
        let token = self.tokens.get(self.pos)?;
        self.pos += 1;
        Some(token)
    }

    fn at_symbol(&self, symbol: char) -> bool {
        matches!(
            self.peek().map(|token| &token.kind),
            Some(ExprTokenKind::Symbol(value)) if *value == symbol
        )
    }

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

    fn expect_symbol(&mut self, symbol: char) -> Result<(), String> {
        if self.consume_symbol(symbol) {
            Ok(())
        } else {
            Err(format!("expected `{symbol}`"))
        }
    }

    fn at_ident(&self, ident: &str) -> bool {
        matches!(
            self.peek().map(|token| &token.kind),
            Some(ExprTokenKind::Ident(value)) if value == ident
        )
    }

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

    fn consume_op(&mut self, op: &'static str) -> bool {
        if matches!(
            self.peek().map(|token| &token.kind),
            Some(ExprTokenKind::Op(value)) if *value == op
        ) {
            self.pos += 1;
            true
        } else {
            false
        }
    }
}

fn join_query_head(tokens: &[String]) -> String {
    let mut head = String::new();
    for token in tokens {
        if token == "." {
            head.push('.');
        } else if head.ends_with('.') || head.is_empty() {
            head.push_str(token);
        } else {
            head.push(' ');
            head.push_str(token);
        }
    }
    head
}

fn lex_expr(source: &str) -> Vec<ExprToken> {
    let bytes = source.as_bytes();
    let mut tokens = Vec::new();
    let mut index = 0usize;
    while index < bytes.len() {
        let byte = bytes[index];
        if byte.is_ascii_whitespace() {
            index += 1;
            continue;
        }
        if is_ident_start(byte) {
            let start = index;
            index += 1;
            while index < bytes.len() && is_ident_continue(bytes[index]) {
                index += 1;
            }
            tokens.push(ExprToken {
                kind: ExprTokenKind::Ident(source[start..index].to_owned()),
            });
            continue;
        }
        if byte.is_ascii_digit() {
            let start = index;
            index += 1;
            while index < bytes.len() && (bytes[index].is_ascii_digit() || bytes[index] == b'.') {
                index += 1;
            }
            tokens.push(ExprToken {
                kind: ExprTokenKind::Number(source[start..index].to_owned()),
            });
            continue;
        }
        if byte == b'"' {
            let start = index + 1;
            index += 1;
            while index < bytes.len() && bytes[index] != b'"' {
                index += 1;
            }
            let value = source[start..index.min(bytes.len())].to_owned();
            index = (index + 1).min(bytes.len());
            tokens.push(ExprToken {
                kind: ExprTokenKind::String(value),
            });
            continue;
        }
        let rest = &source[index..];
        if rest.starts_with("&&") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op("&&"),
            });
            index += 2;
        } else if rest.starts_with("||") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op("||"),
            });
            index += 2;
        } else if rest.starts_with("==") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op("=="),
            });
            index += 2;
        } else if rest.starts_with("!=") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op("!="),
            });
            index += 2;
        } else if rest.starts_with("<=") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op("<="),
            });
            index += 2;
        } else if rest.starts_with(">=") {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Op(">="),
            });
            index += 2;
        } else {
            tokens.push(ExprToken {
                kind: ExprTokenKind::Symbol(byte as char),
            });
            index += 1;
        }
    }
    tokens
}

fn validate_primitive_literal(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    primitive: &str,
    literal: &LiteralExpr<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    // A `secret` admits no literal at all: a credential is never a value in
    // source (DR-0053 §5). The generic "record a compatible value" suggestion
    // below would be exactly the wrong advice here.
    if primitive == "secret" {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!(
                "field `{record_schema}.{field}` is `secret`: secrets have no literal form"
            ),
            suggestion: Some(
                "reference a declared credential; material lives with the custodian, never in \
                 source"
                    .to_owned(),
            ),
        });
        return;
    }
    let valid = matches!(
        (primitive, literal),
        ("string", LiteralExpr::String(_))
            | ("string", LiteralExpr::Ident(_))
            | ("int", LiteralExpr::Number(_))
            | ("float", LiteralExpr::Number(_))
            | ("bool", LiteralExpr::Bool)
            | ("null", LiteralExpr::Null)
            | ("duration", LiteralExpr::String(_))
            | ("time", LiteralExpr::String(_))
    );
    if !valid {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` expects `{primitive}`"),
            suggestion: Some(format!("record a value compatible with `{primitive}`")),
        });
        return;
    }
    match (primitive, literal) {
        ("duration", LiteralExpr::String(value)) if parse_duration_seconds(value).is_none() => {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!("field `{record_schema}.{field}` has invalid duration literal"),
                suggestion: Some("use an ISO-8601 duration such as `\"PT30M\"`".to_owned()),
            });
        }
        ("time", LiteralExpr::String(value)) if parse_time_epoch_seconds(value).is_none() => {
            diagnostics.push(Diagnostic {
                related: Vec::new(),
                span: rule.body.span,
                message: format!("field `{record_schema}.{field}` has invalid time literal"),
                suggestion: Some(
                    "use an RFC3339 timestamp such as `\"2026-05-29T10:00:00Z\"`".to_owned(),
                ),
            });
        }
        _ => {}
    }
}

fn validate_enum_literal(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    schema: &str,
    literal: &LiteralExpr<'_>,
    semantic: &SemanticContext,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(variants) = semantic.schemas.enums.get(schema) else {
        return;
    };
    let LiteralExpr::Ident(variant) = literal else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` expects enum `{schema}`"),
            suggestion: Some(format!(
                "use one of: {}",
                variants.iter().cloned().collect::<Vec<_>>().join(", ")
            )),
        });
        return;
    };
    if !variants.contains(*variant) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("enum `{schema}` has no variant `{variant}`"),
            suggestion: Some(format!(
                "use one of: {}",
                variants.iter().cloned().collect::<Vec<_>>().join(", ")
            )),
        });
    }
}

fn validate_union_literal(
    rule: &RuleDecl,
    record_schema: &str,
    field: &str,
    variants: &[TypeSyntax],
    literal: &LiteralExpr<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let allowed = variants
        .iter()
        .filter_map(|variant| match variant {
            TypeSyntax::LiteralString { value, .. } => Some(value.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>();
    if allowed.is_empty() {
        return;
    }
    let LiteralExpr::String(value) = literal else {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` expects one of its literal variants"),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
        return;
    };
    if !allowed.contains(value) {
        diagnostics.push(Diagnostic {
            related: Vec::new(),
            span: rule.body.span,
            message: format!("field `{record_schema}.{field}` cannot be `{value}`"),
            suggestion: Some(format!("use one of: {}", allowed.join(", "))),
        });
    }
}

fn parse_effect_line(line: &str) -> Option<(IrEffectKind, Option<String>)> {
    let kind = if line.starts_with("tell ") {
        IrEffectKind::AgentTell
    } else if line.starts_with("coerce ") || line.starts_with("prompt ") {
        IrEffectKind::SchemaCoerce
    } else if line.starts_with("claim ") {
        IrEffectKind::TrackerClaim
    } else if line.starts_with("call ")
        || line.starts_with("recall ")
        || line.starts_with("learn ")
        || line.starts_with("curate ")
        || line.starts_with("promote ")
        || line.starts_with("undo ")
        || line.starts_with("transport ")
    {
        IrEffectKind::CapabilityCall
    } else if line.starts_with("emit ") {
        IrEffectKind::EventEmit
    } else if line.starts_with("invoke ") {
        IrEffectKind::WorkflowInvoke
    } else if line.starts_with("read ") {
        IrEffectKind::FileRead
    } else if line.starts_with("write ") {
        IrEffectKind::FileWrite
    } else if line.starts_with("import ") {
        IrEffectKind::FileImport
    } else if line.starts_with("export ") {
        IrEffectKind::FileExport
    } else if line.starts_with("acquire ") {
        IrEffectKind::LeaseAcquire
    } else if line.starts_with("renew ") {
        IrEffectKind::LeaseRenew
    } else if line.starts_with("append ") {
        IrEffectKind::LedgerAppend
    } else if line.starts_with("consume ") && line.contains(" for ") {
        // The counter verb (`consume <counter> for <key> …`); the bare
        // `consume <binding>` alias was removed, and `done` never reaches
        // this fn as an effect line.
        IrEffectKind::CounterConsume
    } else {
        return None;
    };

    Some((kind, binding_after_as(line)))
}

fn parse_consume_line(line: &str) -> Option<String> {
    // `done <binding>` consumes the matched fact. The bare `consume` alias for
    // `done` was removed; `consume <counter> for ...` is the distinct counter
    // verb (multi-word, so it never satisfies the identifier check below).
    let binding = line
        .trim()
        .trim_end_matches(';')
        .strip_prefix("done ")?
        .split("->")
        .next()
        .unwrap_or_default()
        .trim();
    let mut chars = binding.chars();
    let first = chars.next()?;
    if !(first.is_ascii_alphabetic() || first == '_') {
        return None;
    }
    chars
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
        .then(|| binding.to_owned())
}

fn binding_after_multiline_string_end(line: &str) -> Option<String> {
    line.strip_prefix("\"\"\"")
        .and_then(|rest| rest.trim().strip_prefix("as "))
        .and_then(|rest| rest.split_whitespace().next())
        .map(|binding| binding.trim_matches(|ch: char| !ch.is_alphanumeric() && ch != '_'))
        .filter(|binding| !binding.is_empty())
        .map(str::to_owned)
}

fn validate_rule_prompt_content_type_annotation(
    rule: &RuleDecl,
    line: &str,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if !(line.starts_with("tell ") || line.starts_with("coerce ")) {
        return;
    }
    let Some(annotation) = malformed_prompt_content_type_annotation(line) else {
        return;
    };
    diagnostics.push(Diagnostic {
        related: Vec::new(),
        span: rule.body.span,
        message: format!(
            "rule `{}` has malformed multiline prompt content type `{annotation}`",
            rule.name.name
        ),
        suggestion: Some(
            "write a supported token such as `\"\"\"markdown` or put prompt text on the next line"
                .to_owned(),
        ),
    });
}

fn validate_coerce_prompt_content_type_annotations(
    coerce: &CoerceDecl,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for line in coerce.body.text.lines().map(str::trim) {
        if !line.starts_with("prompt ") {
            continue;
        }
        let Some(annotation) = malformed_prompt_content_type_annotation(line) else {
            continue;
        };
        diagnostics.push(Diagnostic { related: Vec::new(),
            span: coerce.body.span,
            message: format!(
                "coerce `{}` has malformed multiline prompt content type `{annotation}`",
                coerce.name.name
            ),
            suggestion: Some(
                "write a supported token such as `\"\"\"markdown` or put prompt text on the next line"
                    .to_owned(),
            ),
        });
    }
}

fn malformed_prompt_content_type_annotation(line: &str) -> Option<String> {
    let (_, tail) = line.split_once("\"\"\"")?;
    let candidate = tail.trim();
    if candidate.is_empty() || candidate.contains("\"\"\"") {
        return None;
    }
    let mut parts = candidate.split_whitespace();
    let first = parts.next()?;
    let has_extra_text = parts.next().is_some();
    let first_is_supported = is_supported_prompt_content_type(first);
    let first_is_annotation_shaped = first_is_supported || first.contains('/');
    if has_extra_text && first_is_annotation_shaped {
        return Some(candidate.to_owned());
    }
    if first.contains('/') && !first_is_supported {
        return Some(first.to_owned());
    }
    None
}

fn is_supported_prompt_content_type(candidate: &str) -> bool {
    if !is_prompt_content_type_token(candidate) {
        return false;
    }
    let normalized = candidate.to_ascii_lowercase();
    normalized.contains('/')
        || matches!(
            normalized.as_str(),
            "markdown" | "json" | "text" | "plain" | "html" | "xml" | "yaml" | "yml"
        )
}

fn is_prompt_content_type_token(candidate: &str) -> bool {
    let mut chars = candidate.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    first.is_ascii_alphanumeric()
        && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '+' | '-' | '_'))
}

pub(crate) fn binding_after_as(line: &str) -> Option<String> {
    let mut tokens = line.split_whitespace();
    while let Some(token) = tokens.next() {
        if token == "as" {
            return tokens
                .next()
                .map(|binding| binding.trim_matches(|ch: char| !ch.is_alphanumeric() && ch != '_'))
                .filter(|binding| !binding.is_empty())
                .map(str::to_owned);
        }
    }
    None
}

fn parse_after_line(line: &str) -> Option<(String, DependencyPredicate)> {
    let rest = line.strip_prefix("after ")?;
    if rest.contains("=>") {
        return None;
    }
    let before_body = rest.split('{').next().unwrap_or(rest).trim();
    let mut parts = before_body.split_whitespace();
    let binding = parts.next()?.to_owned();
    let predicate = match parts.next()? {
        "succeeds" => DependencyPredicate::Succeeds,
        "fails" => DependencyPredicate::Fails,
        // `times out` / `cancelled` react only to that specific non-success
        // terminal status (spec/expression-kernel.md), mirroring succeeds/fails.
        "cancelled" => DependencyPredicate::Cancelled,
        "times" => {
            if parts.next()? != "out" {
                return None;
            }
            DependencyPredicate::TimedOut
        }
        // Coordination outcomes (spec/coordination.md) are completion-valued;
        // the arm dispatch happens on the outcome variant at lowering.
        "completes" | "held" | "contended" | "ok" | "over" | "promoted" | "conflicted"
        | "applied" | "stranded" => DependencyPredicate::Completes,
        // `after p reaches "<name>" [as m]` (Family C): consume the quoted
        // milestone name (which may contain whitespace — token-splitting used
        // to reject multi-word names); the IR predicate is completion-shaped
        // (runtime gating keys on the milestone-specific `reached` fact).
        "reaches" => {
            let rest = before_body.trim().strip_prefix(&binding)?.trim_start();
            let after_kw = rest.strip_prefix("reaches")?.trim_start();
            let quoted = after_kw.strip_prefix('"')?;
            let close = quoted.find('"')?;
            let tail = &quoted[close + 1..];
            let mut tail_parts = tail.split_whitespace();
            match (tail_parts.next(), tail_parts.next(), tail_parts.next()) {
                (None, None, None) => {}
                (Some("as"), Some(alias), None) if is_identifier(alias) => {}
                _ => return None,
            }
            return Some((binding, DependencyPredicate::Completes));
        }
        _ => return None,
    };
    match (parts.next(), parts.next(), parts.next()) {
        (None, None, None) => {}
        (Some("as"), Some(alias), None) if is_identifier(alias) => {}
        _ => return None,
    }
    Some((binding, predicate))
}

pub(crate) fn is_identifier(value: &str) -> bool {
    let mut chars = value.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == '_')
        && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}

pub(crate) fn push_line(snapshot: &mut String, line: impl AsRef<str>) {
    snapshot.push_str(line.as_ref());
    snapshot.push('\n');
}

pub(crate) fn stable_hash(value: &str) -> String {
    // SHA-256 truncated to 128 bits (the FNV-collision hardening swap):
    // source_hash/ir_hash are program-version identity — colliding them
    // aliases two program revisions. Report-schema digest patterns and the
    // Python validator mirrors must stay in lockstep with this width.
    use sha2::Digest;
    let digest = sha2::Sha256::digest(value.as_bytes());
    let mut hex = String::with_capacity(32);
    for byte in &digest[..16] {
        hex.push_str(&format!("{byte:02x}"));
    }
    hex
}

pub fn parse_duration_seconds(value: &str) -> Option<f64> {
    let value = value.strip_prefix('P')?;
    let mut rest = value;
    let mut seconds = 0.0;
    let mut consumed = false;
    let mut in_time = false;

    while !rest.is_empty() {
        if let Some(next) = rest.strip_prefix('T') {
            if in_time {
                return None;
            }
            in_time = true;
            rest = next;
            continue;
        }

        let number_len = rest
            .char_indices()
            .take_while(|(_, ch)| ch.is_ascii_digit() || *ch == '.')
            .map(|(index, ch)| index + ch.len_utf8())
            .last()?;
        let number = rest[..number_len].parse::<f64>().ok()?;
        if !number.is_finite() {
            return None;
        }
        let unit = rest[number_len..].chars().next()?;
        rest = &rest[number_len + unit.len_utf8()..];
        let multiplier = match (in_time, unit) {
            (false, 'D') => 86_400.0,
            (true, 'H') => 3_600.0,
            (true, 'M') => 60.0,
            (true, 'S') => 1.0,
            _ => return None,
        };
        seconds += number * multiplier;
        consumed = true;
    }

    consumed.then_some(seconds)
}

pub fn parse_time_epoch_seconds(value: &str) -> Option<f64> {
    if value.len() < 20 {
        return None;
    }
    let year = parse_fixed_i32(value, 0, 4)?;
    require_byte(value, 4, b'-')?;
    let month = parse_fixed_u32(value, 5, 2)?;
    require_byte(value, 7, b'-')?;
    let day = parse_fixed_u32(value, 8, 2)?;
    require_byte(value, 10, b'T')?;
    let hour = parse_fixed_u32(value, 11, 2)?;
    require_byte(value, 13, b':')?;
    let minute = parse_fixed_u32(value, 14, 2)?;
    require_byte(value, 16, b':')?;
    let second = parse_fixed_u32(value, 17, 2)?;
    let mut offset_start = 19;
    let mut fractional_second = 0.0;
    if value.as_bytes().get(offset_start).copied() == Some(b'.') {
        let fraction_start = offset_start + 1;
        let fraction_len = value[fraction_start..]
            .char_indices()
            .take_while(|(_, ch)| ch.is_ascii_digit())
            .map(|(index, ch)| index + ch.len_utf8())
            .last()?;
        let fraction = &value[fraction_start..fraction_start + fraction_len];
        let scale = 10_f64.powi(i32::try_from(fraction.len()).ok()?);
        fractional_second = fraction.parse::<f64>().ok()? / scale;
        offset_start = fraction_start + fraction_len;
    }
    if !(1..=12).contains(&month)
        || !(1..=days_in_month(year, month)).contains(&day)
        || hour > 23
        || minute > 59
        || second > 60
    {
        return None;
    }

    let offset_seconds = match value.as_bytes().get(offset_start).copied()? {
        b'Z' if value.len() == offset_start + 1 => 0,
        b'+' | b'-' if value.len() == offset_start + 6 => {
            let sign = if value.as_bytes()[offset_start] == b'+' {
                1
            } else {
                -1
            };
            let offset_hour = parse_fixed_i32(value, offset_start + 1, 2)?;
            require_byte(value, offset_start + 3, b':')?;
            let offset_minute = parse_fixed_i32(value, offset_start + 4, 2)?;
            if offset_hour > 23 || offset_minute > 59 {
                return None;
            }
            sign * (offset_hour * 3_600 + offset_minute * 60)
        }
        _ => return None,
    };

    let days = days_from_civil(year, month, day);
    let local_seconds = days * 86_400 + i64::from(hour * 3_600 + minute * 60 + second.min(59));
    Some((local_seconds - i64::from(offset_seconds)) as f64 + fractional_second)
}

fn parse_fixed_i32(value: &str, start: usize, len: usize) -> Option<i32> {
    value.get(start..start + len)?.parse::<i32>().ok()
}

fn parse_fixed_u32(value: &str, start: usize, len: usize) -> Option<u32> {
    value.get(start..start + len)?.parse::<u32>().ok()
}

fn require_byte(value: &str, index: usize, expected: u8) -> Option<()> {
    (value.as_bytes().get(index).copied()? == expected).then_some(())
}

fn days_in_month(year: i32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if is_leap_year(year) => 29,
        2 => 28,
        _ => 0,
    }
}

fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
    let year = year - i32::from(month <= 2);
    let era = if year >= 0 { year } else { year - 399 } / 400;
    let year_of_era = year - era * 400;
    let month = month as i32;
    let day = day as i32;
    let day_of_year = (153 * (month + if month > 2 { -3 } else { 9 }) + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    i64::from(era * 146_097 + day_of_era - 719_468)
}

/// Flat-prepend body emitter used where the output feeds IR construction (e.g.
/// a table's synthetic rule body, whose `body_hash` is part of program identity).
/// Kept byte-for-byte stable so the lowered IR / snapshots do not move; the
/// idempotent re-indenter for human formatting is [`format_block_body`].
fn push_block_body(body: &str, formatted: &mut String) {
    if body.is_empty() {
        return;
    }
    for line in body.lines() {
        if line.trim().is_empty() {
            formatted.push('\n');
        } else {
            push_line(formatted, format!("  {}", line.trim_end()));
        }
    }
}

/// Net bracket-depth change for one line, ignoring brackets inside strings.
/// Returns `(delta, opens_unclosed_triple)`: a `true` second element means the
/// line starts a `"""..."""` that does not close on the same line, so following
/// lines are string content. ASCII markers only — UTF-8 string bytes can't
/// false-match.
fn scan_braces(line: &str) -> (i32, bool) {
    let bytes = line.as_bytes();
    let mut index = 0;
    let mut delta = 0i32;
    let mut in_string = false;
    while index < bytes.len() {
        if in_string {
            match bytes[index] {
                b'\\' => index += 1,
                b'"' => in_string = false,
                _ => {}
            }
            index += 1;
            continue;
        }
        if line[index..].starts_with("\"\"\"") {
            match line[index + 3..].find("\"\"\"") {
                Some(offset) => index += 3 + offset + 3,
                None => return (delta, true),
            }
            continue;
        }
        match bytes[index] {
            b'"' => in_string = true,
            b'{' | b'[' | b'(' => delta += 1,
            b'}' | b']' | b')' => delta -= 1,
            _ => {}
        }
        index += 1;
    }
    (delta, false)
}

impl TypeSyntax {
    fn to_source(&self) -> String {
        match self {
            Self::Primitive { name, .. } => name.clone(),
            Self::LiteralString { value, .. } => format!("{value:?}"),
            Self::Ref { name } => name.name.clone(),
            Self::AgentRef { agents, .. } => {
                let agents = agents
                    .iter()
                    .map(|agent| agent.name.as_str())
                    .collect::<Vec<_>>()
                    .join(" | ");
                format!("AgentRef<{agents}>")
            }
            Self::Optional { inner, .. } => format!("{}?", inner.to_source()),
            Self::Array { inner, .. } => format!("{}[]", inner.to_source()),
            Self::Map { inner, .. } => format!("map<{}>", inner.to_source()),
            Self::Union { variants, .. } => variants
                .iter()
                .map(Self::to_source)
                .collect::<Vec<_>>()
                .join(" | "),
        }
    }
}

#[cfg(test)]
#[path = "lib_tests/tests.rs"]
mod tests;