oxdock-parser 0.40.0-alpha

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

use std::collections::HashSet;
use std::fmt;

use crate::ast::{
    Arg, ArgPart, ArithOp, Command, CompareOp, Expr, GuardExpr, IoBinding, IoStream, MathOp,
    ModuleTable, PipeTarget, Step, Value, WorkspaceTarget,
};
use crate::command::{
    ArgSpec, ArgType, CommandMeta, Example, FlagSpec, FlagValueType, IoDirection, Stream,
    split_assignment,
};
use crate::constants::{KEYWORD_EXPORT, KEYWORD_IMPORT};
use crate::error::{ParseError, ParseResult, SpanContext};
use indoc::indoc;

// ── Helpers ────────────────────────────────────────────────────────────────

// Value-parsing helpers (`strip_surrounding_quotes`,
// `split_assignment`, `parse_duration`, `format_duration`) live in
// `crate::command` beside the `ArgType` validators that call them.

/// Reserved words that can never name a `REMOTE` target: the workspace
/// roots plus the block keyword itself. Shared with CLI inventory
/// validation so charset rules cannot drift between parser and host.
pub const REMOTE_RESERVED_WORDS: &[&str] = &["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM", "REMOTE"];

/// Validate a `REMOTE` target name: start alnum, then alnum, `_`, or
/// `-`, max 64 chars. Safe in CLI flags, log lines, tarball names, and
/// muxio stream labels without quoting.
pub fn is_valid_remote_target(target: &str) -> bool {
    if target.is_empty() || target.len() > 64 {
        return false;
    }
    if REMOTE_RESERVED_WORDS.contains(&target) {
        return false;
    }
    let mut chars = target.chars();
    match chars.next() {
        Some(first) if first.is_ascii_alphanumeric() => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Join free-text tail arguments into one value. Single args pass through
/// untouched (preserving `Arg::Expr`); all-`String` tails join exactly like the
/// historical `join_args`; tails containing expressions become `Arg::Parts`
/// with single-space separators so `$x` is never silently dropped.
fn join_value(args: Vec<Arg>, cmd_name: &str) -> ParseResult<Arg> {
    if args.is_empty() {
        return Err(ParseError::validation(
            cmd_name,
            format!("{cmd_name} requires at least one argument"),
            &SpanContext::line_only(0),
        ));
    }
    if args.len() == 1 {
        return Ok(args.into_iter().next().unwrap());
    }
    if args.iter().all(|a| matches!(a, Arg::String(..))) {
        return Ok(Arg::String(
            args.iter()
                .map(|a| a.as_str())
                .collect::<Vec<_>>()
                .join(" "),
            false,
        ));
    }
    let mut parts = Vec::new();
    for (index, arg) in args.into_iter().enumerate() {
        if index > 0 {
            parts.push(ArgPart::Text(" ".to_string(), false));
        }
        match arg {
            Arg::String(text, quoted) => parts.push(ArgPart::Text(text, quoted)),
            Arg::Expr(expr) => parts.push(ArgPart::Expr(expr)),
            Arg::Parts(inner) => parts.extend(inner),
        }
    }
    Ok(Arg::Parts(parts))
}

/// Canonical `lower_command` entry for direct callers holding one pre-joined
/// `KEY=value` token. Script parsing never reaches this : the grammar splits
/// assignments on raw spans first (see `lower_env_command` in parser.rs).
pub fn lower_env_assignment(args: Vec<Arg>) -> ParseResult<StepKind> {
    let arg = args.into_iter().next().ok_or_else(|| {
        ParseError::validation(
            "ENV",
            "ENV requires KEY=value".to_string(),
            &SpanContext::line_only(0),
        )
    })?;
    let Some((key, value)) = split_assignment(arg.as_str())
        .map_err(|e| ParseError::validation("ENV", e.to_string(), &SpanContext::line_only(0)))?
    else {
        return Err(ParseError::validation(
            "ENV",
            "ENV requires KEY=value format".to_string(),
            &SpanContext::line_only(0),
        ));
    };
    Ok(StepKind::Env { key, value })
}

/// Collapse a grammar-classified assignment for commands that take no
/// assignments (`RUN`, `COPY`, ...): canonical `key=<rendered value>` text.
/// Runtime semantics survive intact : `{{ }}` templates stay textual for
/// `expand_string`, and `RUN`'s own post-pass expands bare `$var`.
pub(crate) fn canonical_assignment_arg(key: &str, value: &Arg) -> Arg {
    Arg::String(format!("{key}={}", value.render()), false)
}

/// Render an [`AssertTarget`] for `Display`: stream markers print bare
/// (`stdout` reparses to the marker); values print like other args.
fn fmt_assert_target(target: &AssertTarget) -> String {
    match target {
        AssertTarget::Value(arg) => fmt_value(arg, quote_msg),
        _ => target.render(),
    }
}

/// Render one `Arg` for `Display`: expressions print raw (`$x` must never be
/// quoted or reparsing would literalize them); mixed values print raw unless
/// they hold instruction-boundary characters (`;`, `}`, linebreaks), which
/// force quoting for reparseability.
fn fmt_value(arg: &Arg, quote: fn(&str) -> String) -> String {
    match arg {
        Arg::Expr(_) => arg.render(),
        Arg::String(text, _) => quote(text),
        Arg::Parts(_) => {
            let rendered = arg.render();
            if rendered.contains(';')
                || rendered.contains('}')
                || rendered.contains('\n')
                || rendered.contains('\r')
            {
                quote(&rendered)
            } else {
                rendered
            }
        }
    }
}

fn quote_dsl_string(s: &str) -> String {
    // Single quoting core for Display output: backslash and quote
    // escapes only. The `quote_*`/`fmt_*` helpers below differ in *when*
    // a value needs quoting, never in *how*. No brace or control
    // handling: the parser passes literal contents verbatim, so Display
    // round-trips without them (unlike `escape_dsl_string` in `literal`,
    // which inverts runtime `expand_string` and must also
    // escape `{{` triples and controls).
    // Multi-line values render as `"""` blocks on their own lines at
    // column zero, so lowering recovers the bytes exactly: the leading
    // newline strips once, the empty closing baseline contributes no
    // common prefix, and the trailing newline strips once. Quote-holding
    // values stay double-quoted with `\"` escapes: blocks admit raw
    // quotes for the string grammar, but no Rust token stream can carry
    // them (the lexer ends the literal at every raw `"`), so block
    // rendering would shred on the token pathway while escaping keeps
    // both pathways agreeing. Blank-only and carriage-return values
    // keep the legacy raw double-quoted spelling instead: block
    // lowering would normalize them away.
    if s.contains('\n') && !s.contains('"') && !s.contains('\r') && !s.trim().is_empty() {
        let escaped = escape_block_text(s);
        return format!("\"\"\"\n{escaped}\n\"\"\"");
    }
    format!("\"{}\"", escape_inline_text(s))
}

/// Escape text for double-quoted rendering so a render cycle adds no
/// layer: recognized escapes pass through verbatim (the parser keeps
/// them verbatim and both lexers accept them), while the delimiter and
/// anything neither lexer takes raw gets escaped.
fn escape_inline_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => {
                // Recognized pairs emit atomically: reprocessing the
                // trailing quote through the `"` arm above would grow
                // the pair a second backslash.
                if matches!(
                    chars.peek(),
                    Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
                ) {
                    out.push('\\');
                    out.push(chars.next().unwrap_or('\\'));
                } else {
                    out.push_str("\\\\");
                }
            }
            _ => out.push(c),
        }
    }
    out
}

/// Escape block payloads: the delimiter triple always escapes first,
/// and a backslash survives raw only where both lexers take it
/// (recognized escapes, including the ones just introduced; a real
/// newline or `{` after it would break Rust lexing, so those double
/// like everything else unrecognized).
fn escape_block_text(s: &str) -> String {
    let preescaped = s.replace("\"\"\"", "\\\"\\\"\\\"");
    let mut out = String::with_capacity(preescaped.len());
    let mut chars = preescaped.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        let keep = matches!(
            chars.peek(),
            Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
        );
        out.push('\\');
        if !keep {
            out.push('\\');
        }
    }
    out
}

fn quote_arg(s: &str) -> String {
    let is_safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        && !s.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '/' || c == '.')
        && !crate::Command::is_statement_keyword(s);
    if is_safe && !s.is_empty() {
        s.to_string()
    } else {
        quote_dsl_string(s)
    }
}

fn quote_msg(s: &str) -> String {
    let safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        && !s.starts_with(|c: char| c.is_ascii_digit())
        && !crate::Command::is_statement_keyword(s);
    if safe && !s.is_empty() {
        s.to_string()
    } else {
        quote_dsl_string(s)
    }
}

fn quote_run(s: &str) -> String {
    if s.is_empty() || s.chars().any(|c| c == ';' || c == '\n') || s.contains("//") {
        return quote_dsl_string(s);
    }
    s.split(' ')
        .map(|w| {
            if w.starts_with(|c: char| c.is_ascii_digit())
                || w.starts_with(['/', '.', '-', ':', '='])
            {
                quote_dsl_string(w)
            } else {
                w.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Render one exec-form (`RUN [...]`) argv element for `Display`:
/// string literals print JSON-quoted; typed expressions (`$var`,
/// `F()`, ints, bools, nested lists) print raw via `render` so
/// reparsing yields the same typed element; mixed values print raw
/// unless they hold instruction-boundary characters.
fn fmt_exec_arg(arg: &Arg) -> String {
    match arg {
        Arg::String(text, _) => quote_dsl_string(text),
        Arg::Expr(_) => arg.render(),
        Arg::Parts(_) => {
            let rendered = arg.render();
            if rendered.contains(';')
                || rendered.contains('}')
                || rendered.contains('\n')
                || rendered.contains('\r')
            {
                quote_dsl_string(&rendered)
            } else {
                rendered
            }
        }
    }
}

/// Render an [`Arg`] for `Display`: the quoted flag drives quoting (not
/// content sniffing : digit-leading values like `10s` or `0` must stay
/// bare to reparse with the same flag).
fn fmt_raw_arg(arg: &Arg) -> String {
    match arg {
        Arg::String(s, true) => quote_dsl_string(s),
        _ => arg.render(),
    }
}

fn fmt_io(b: &IoBinding) -> String {
    let s = match b.stream {
        IoStream::Stdin => "stdin".to_string(),
        IoStream::Stdout => "stdout".to_string(),
        IoStream::Stderr => "stderr".to_string(),
        IoStream::Tty => "tty".to_string(),
        IoStream::Rows(rows) => format!("rows={rows}"),
        IoStream::Cols(cols) => format!("cols={cols}"),
    };
    match &b.pipe {
        Some(PipeTarget::Var(v)) => format!("{}=${}", s, v),
        None => s,
    }
}

// ── declare_commands! ──────────────────────────────────────────────────────

// Keywords parsed by PEG rules rather than plain-command lowering (`WITH_IO`,
// `AWAIT`, ...). When a line starts with one of these but fails to parse as
// such, lowering falls through here : report a committed syntax error instead
// of an unknown command.
pub(crate) fn is_known_command(name: &str) -> bool {
    if name == "ELSE" {
        return true;
    }
    all_metadata().iter().any(|meta| meta.name == name)
}

pub(crate) fn invalid_syntax_error(name: &str, raw_args: &[Arg]) -> ParseError {
    let received = raw_args
        .iter()
        .map(Arg::render)
        .collect::<Vec<_>>()
        .join(" ");
    let got = if received.is_empty() {
        "nothing".to_string()
    } else {
        format!("`{received}`")
    };
    let found = if received.is_empty() {
        None
    } else {
        Some(received.clone())
    };
    let expected = all_metadata()
        .iter()
        .find(|meta| meta.name == name)
        .map(|meta| vec![meta.syntax.to_string()])
        .unwrap_or_default();
    let ctx = SpanContext::line_only(0);
    match structural_hint(name, &received) {
        Some(hint) => ParseError::invalid_syntax(
            name,
            format!("invalid syntax for command {name}: {hint}"),
            found,
            expected,
            Some(hint),
            &ctx,
        ),
        None => ParseError::invalid_syntax(
            name,
            format!("invalid syntax for command {name}: got {got}."),
            found,
            expected,
            None,
            &ctx,
        ),
    }
}

fn unknown_command_error(name: &str, raw_args: &[Arg]) -> ParseError {
    let received = raw_args
        .iter()
        .map(Arg::render)
        .collect::<Vec<_>>()
        .join(" ");
    let hint = structural_hint(name, &received).or_else(|| case_hint(name));
    let ctx = SpanContext::line_only(0);
    match hint {
        Some(hint) => ParseError::unknown_command(
            name,
            format!("unknown command: {name}\n{hint}"),
            Some(hint),
            &ctx,
        ),
        None => ParseError::unknown_command(name, format!("unknown command: {name}"), None, &ctx),
    }
}

/// Single decision function for the lowering fallback: keyword led lines
/// (structural statements, `ELSE`, every registered command) are committed
/// syntax errors, never unknown commands. Only truly unknown names fall
/// through to `unknown_command_error`. Callers enrich the result with the
/// token span via `ParseError::with_span`.
pub(crate) fn classify(name: &str, raw_args: &[Arg]) -> ParseError {
    if is_known_command(name) {
        invalid_syntax_error(name, raw_args)
    } else {
        unknown_command_error(name, raw_args)
    }
}

fn structural_hint(name: &str, received: &str) -> Option<String> {
    let got = if received.is_empty() {
        "nothing".to_string()
    } else {
        format!("`{received}`")
    };
    match name {
        "WITH_IO" => Some(with_io_hint(&got, received)),
        "AWAIT" => Some(format!(
            "AWAIT waits for a background task variable, e.g. `LET $t: HANDLE<VOID> = ASYNC ECHO hi` then `AWAIT $t`; got {got}."
        )),
        "CANCEL" => Some(format!(
            "CANCEL stops a background task variable, e.g. `CANCEL $t` (from `LET $t: HANDLE<VOID> = ASYNC ...`); got {got}."
        )),
        "ASYNC" => Some(format!(
            "ASYNC runs a command in the background, e.g. `ASYNC RUN ...`, `ASYNC {{ ... }}`, or `LET $t: HANDLE<T> = ASYNC ...`; got {got}."
        )),
        "FOR" => Some(format!(
            "FOR loops need `FOR $item: TYPE IN <expr> {{ ... }}` (or `FOR $key: STRING, $value: TYPE IN <expr> {{ ... }}`); got {got}."
        )),
        "IF" => Some(format!(
            "IF needs a condition and a block, e.g. `IF true {{ ECHO yes }}`; got {got}."
        )),
        "ELSE" => Some(format!(
            "ELSE must directly follow an `IF ... {{ ... }}` block, e.g. `IF true {{ ECHO yes }} ELSE {{ ECHO no }}`; got {got}."
        )),
        "LET" => Some(format!(
            "LET assigns a variable, e.g. `LET $name: STRING = <expr>`, `LET $t: HANDLE<T> = ASYNC ...`, `LET $out: STRING = <command>` (capture), `LET $out: STRING = AWAIT $t`, or `LET $var: TYPE = {{ ... }}` (inline block); got {got}."
        )),
        "SET" => Some(
            "`SET` is not a keyword; mutate a declared variable with `$var = <expr>`, e.g. `$count = 2`.".to_string(),
        ),
        "TIMEOUT" => Some(format!(
            "TIMEOUT needs a duration and a command or block, e.g. `TIMEOUT 30s RUN ...`; got {got}."
        )),
        "REMOTE" => Some(format!(
            "REMOTE needs a target and a braced block, e.g. `REMOTE prod [$version, env:DEPLOY_ENV] {{ ... }}`; got {got}."
        )),
        "FUNC" => Some(format!(
            "FUNC defines a function, e.g. `FUNC GREET($name: STRING): STRING {{ RETURN $name }}`; got {got}."
        )),
        "RETURN" => Some(format!(
            "RETURN ends the nearest function, ASYNC task, or inline LET block with a value, e.g. `RETURN $x`; got {got}."
        )),
        "WHILE" => Some(format!(
            "WHILE needs a Bool condition and a block, e.g. `WHILE !$done {{ ... }}`; got {got}."
        )),
        "BREAK" => Some(
            "`BREAK` exits the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
        ),
        "CONTINUE" => Some(
            "`CONTINUE` skips to the next iteration of the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
        ),
        "INHERIT_ENV" => Some(format!(
            "INHERIT_ENV takes a key list, e.g. `INHERIT_ENV [HOME, PATH]`; got {got}."
        )),
        name if name == KEYWORD_IMPORT => Some(format!(
            "IMPORT brings module functions into bare-call scope, e.g. `IMPORT [STD]` or `IMPORT [STD, MOCK]`; file imports take a quoted path with a mandatory alias, e.g. `IMPORT [\"./lib.oxdock\" AS LIB]`, and brackets mix both across lines, e.g. `IMPORT [STD, \"a.oxdock\" AS A]`; got {got}."
        )),
        name if name == KEYWORD_EXPORT => Some(
            "EXPORT marks script FUNCs and qualified host functions as tools, e.g. `EXPORT FOO`, `EXPORT [FOO, STD::INT]`."
                .to_string(),
        ),
        _ => None,
    }
}

/// Diagnose a `WITH_IO` line that failed to parse: most often a malformed
/// binding list (bindings are bare streams, `<stream>=$var`, bare `tty`,
/// or `rows`/`cols` dimensions).
fn with_io_hint(got: &str, received: &str) -> String {
    const SYNTAX: &str =
        "WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`";
    const BINDINGS: &str = "bindings are `stdin`, `stdout`, `stderr`, or `<stream>=$var` with a PIPE-typed variable (e.g. `[stdout=$p]`, `[stdin=$p]`); `tty` is a bare flag for RUN steps, with `rows = <int>` / `cols = <int>` geometry (e.g. `[tty, rows=40, cols=100]`)";
    if let Some(after_open) = received.strip_prefix('[') {
        match after_open.split_once(']') {
            None => {
                return format!("{SYNTAX}: missing closing `]` in the binding list; got {got}.");
            }
            Some((bindings, _)) => {
                for part in bindings.split(',') {
                    let part = part.trim();
                    if part.is_empty() {
                        continue;
                    }
                    let (stream, binding) = match part.split_once('=') {
                        Some((stream, binding)) => (stream.trim(), Some(binding.trim())),
                        None => (part, None),
                    };
                    if matches!(stream, "rows" | "cols") {
                        let valid = binding.is_some_and(|value| {
                            value
                                .parse::<u64>()
                                .is_ok_and(|dim| (1..=u64::from(u16::MAX)).contains(&dim))
                        });
                        if !valid {
                            return format!(
                                "{SYNTAX}: invalid geometry `{part}`; `rows`/`cols` need a positive integer 1-65535 (e.g. `rows=40`) and require `tty`; got {got}."
                            );
                        }
                        continue;
                    }
                    if stream == "tty" {
                        if binding.is_some() {
                            return format!(
                                "{SYNTAX}: invalid binding `{part}`; `tty` is a bare flag (geometry rides `rows`/`cols`, e.g. `[tty, rows=40]`); got {got}."
                            );
                        }
                        continue;
                    }
                    if !matches!(stream, "stdin" | "stdout" | "stderr") {
                        return format!(
                            "{SYNTAX}: invalid stream `{stream}`; expected `stdin`, `stdout`, `stderr`, or `tty`; got {got}."
                        );
                    }
                    let valid = match binding {
                        None => true,
                        Some(value) => value.strip_prefix('$').is_some_and(|var| {
                            !var.trim().is_empty()
                                && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                        }),
                    };
                    if !valid {
                        return format!(
                            "{SYNTAX}: invalid binding `{part}`; {BINDINGS}; got {got}."
                        );
                    }
                }
            }
        }
    }
    format!("{SYNTAX}; got {got}. {BINDINGS}.")
}

/// `echo hi` is almost certainly `ECHO hi`: commands are uppercase.
fn case_hint(name: &str) -> Option<String> {
    let upper = name.to_ascii_uppercase();
    if upper != name
        && all_metadata()
            .iter()
            .any(|meta| meta.name == upper.as_str())
    {
        return Some(format!("did you mean `{upper}`? commands are uppercase."));
    }
    None
}

macro_rules! declare_commands {
    (
        structural [
            $( $sname:ident $( { $( $sfname:ident : $sftype:ty ),* $(,)? } )? ),* $(,)?
        ]

        $(
            $cmd_ident:ident => [
                name: $name:expr,
                variant: $vname:ident $( { $( $vfname:ident : $vftype:ty ),* $(,)? } )? $( ( $( $ttuple:ty ),* $(,)? ) )?,
                syntax: $syntax:expr,
                summary: $summary:expr,
                description: $desc:expr,
                args: $args:expr,
                flags: $flags:expr,
                default_output: $out:expr,
                examples: $examples:expr,
                lower: $lower:expr,
            ]
        ),* $(,)?
    ) => {
        #[derive(Debug, Clone, PartialEq)]
        pub enum StepKind {
            $( $vname $( { $( $vfname : $vftype ),* } )? $( ( $( $ttuple ),* ) )?, )*
            $( $sname $( { $( $sfname : $sftype ),* } )?, )*
        }

        pub fn lower_command(name: &str, raw_args: Vec<Arg>) -> ParseResult<StepKind> {
            match name {
                $(
                    s if s == $name => {
                        let meta = CommandMeta {
                            name: $name, syntax: $syntax, summary: $summary,
                            description: $desc, args: $args, flags: $flags,
                            default_output: $out, examples: $examples,
                            in_index: true,
                        };
                        let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
                        crate::command::validate_positionals_against_meta(
                            s,
                            &meta.args,
                            &positional,
                        )?;
                        let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
                        lower_fn(flags, positional)
                    }
                )*
                _ => {
                    Err(classify(name, &raw_args))
                }
            }
        }

        pub fn all_metadata() -> Vec<CommandMeta> {
            let mut out = vec![
                $( CommandMeta {
                    name: $name, syntax: $syntax, summary: $summary,
                    description: $desc, args: $args, flags: $flags,
                    default_output: $out, examples: $examples,
                    in_index: true,
                }, )*
            ];
            // Structural statements are registered separately (see
            // all_structural_metadata) but documented through the same
            // pipeline so oxdock-render never drifts from the parser.
            out.extend(all_structural_metadata());
            out
        }
    };
}

/// Generate both raw-string fragment walkers from one match:
/// helper and closure names arrive as macro arguments (so every
/// reference shares the invocation's syntax context), types are
/// fixed per method, and the arm list rides as one trailing brace
/// group (no repetition, so no follow-token ambiguity). A new
/// string-carrying variant fails compilation at both expansion
/// sites until it is added here, and the two walkers can never
/// disagree about what counts as template text.
macro_rules! define_raw_string_walkers {
    ($f:ident, $wa:ident, $wo:ident, $wt:ident, { $($arms:tt)* }) => {
        /// Visit every immediate raw string fragment (literal argument text
        /// and mixed-value text fragments). Typed expressions are NOT
        /// visited here. Boxed sub-kinds and bodies are NOT descended, same
        /// as [`walk_exprs`](Self::walk_exprs): the caller recurses through
        /// [`walk_child_kinds`](Self::walk_child_kinds) or the checker's own
        /// body walk. Exhaustive for the same reason: a new string-carrying
        /// variant must appear here or env-template checking misses it.
        pub fn walk_raw_strings(&self, $f: &mut impl FnMut(&str)) {
            // One `Arg`: literal text and mixed-text fragments; typed expressions are skipped.
            fn $wa(arg: &Arg, $f: &mut impl FnMut(&str)) {
                match arg {
                    Arg::String(text, _) => $f(text),
                    Arg::Expr(_) => {}
                    Arg::Parts(parts) => {
                        for part in parts {
                            if let ArgPart::Text(text, _) = part {
                                $f(text);
                            }
                        }
                    }
                }
            }
            // An optional `Arg`, when present.
            fn $wo(arg: &Option<Arg>, $f: &mut impl FnMut(&str)) {
                if let Some(arg) = arg {
                    $wa(arg, $f);
                }
            }
            // An assertion target holding a value.
            fn $wt(target: &AssertTarget, $f: &mut impl FnMut(&str)) {
                if let AssertTarget::Value(arg) = target {
                    $wa(arg, $f);
                }
            }
            match self {
                $($arms)*
            }
        }
        /// Mutable twin of [`walk_raw_strings`](Self::walk_raw_strings):
        /// same fragments, same non-descending boundary. The parse-time
        /// placeholder qualifier runs through this; the static env check
        /// runs through the shared twin, so both agree fragment for fragment.
        pub fn walk_raw_strings_mut(&mut self, $f: &mut impl FnMut(&mut String)) {
            // One `Arg`: literal text and mixed-text fragments; typed expressions are skipped.
            fn $wa(arg: &mut Arg, $f: &mut impl FnMut(&mut String)) {
                match arg {
                    Arg::String(text, _) => $f(text),
                    Arg::Expr(_) => {}
                    Arg::Parts(parts) => {
                        for part in parts {
                            if let ArgPart::Text(text, _) = part {
                                $f(text);
                            }
                        }
                    }
                }
            }
            // An optional `Arg`, when present.
            fn $wo(arg: &mut Option<Arg>, $f: &mut impl FnMut(&mut String)) {
                if let Some(arg) = arg {
                    $wa(arg, $f);
                }
            }
            // An assertion target holding a value.
            fn $wt(target: &mut AssertTarget, $f: &mut impl FnMut(&mut String)) {
                if let AssertTarget::Value(arg) = target {
                    $wa(arg, $f);
                }
            }
            match self {
                $($arms)*
            }
        }
    };
}

// Generate both expression walkers from one match:
/// helper and closure names arrive as macro arguments (so every
/// reference shares the invocation's syntax context), types are
/// fixed per method, and the arm list rides as one trailing brace
/// group (no repetition, so no follow-token ambiguity). A new
/// expression-carrying variant fails compilation at both expansion
/// sites until it is added here, and the two walkers can never
/// disagree about what counts as an immediate child expression.
macro_rules! define_expr_walkers {
    ($f:ident, $wa:ident, $wo:ident, $wt:ident, { $($arms:tt)* }) => {
        /// Visit every immediate child expression (arguments, conditions,
        /// durations, initializers). Boxed sub-kinds and bodies are NOT
        /// descended: pair with [`walk_child_kinds`](Self::walk_child_kinds)
        /// or use [`walk_step_exprs`](Self::walk_step_exprs) for the full
        /// tree. Exhaustive: a new variant fails compilation here, so AST
        /// passes built on this visitor can never silently miss a command.
        pub fn walk_exprs(&self, $f: &mut impl FnMut(&Expr)) {
            // One `Arg`: the typed expressions inside; literal text is skipped.
            fn $wa(arg: &Arg, $f: &mut impl FnMut(&Expr)) {
                match arg {
                    Arg::Expr(expr) => $f(expr),
                    Arg::Parts(parts) => {
                        for part in parts {
                            if let ArgPart::Expr(expr) = part {
                                $f(expr);
                            }
                        }
                    }
                    Arg::String(..) => {}
                }
            }
            // An optional `Arg`, when present.
            fn $wo(arg: &Option<Arg>, $f: &mut impl FnMut(&Expr)) {
                if let Some(arg) = arg {
                    $wa(arg, $f);
                }
            }
            // An assertion target holding a value.
            fn $wt(target: &AssertTarget, $f: &mut impl FnMut(&Expr)) {
                if let AssertTarget::Value(arg) = target {
                    $wa(arg, $f);
                }
            }
            match self {
                $($arms)*
            }
        }
        /// Mutable twin of [`walk_exprs`](Self::walk_exprs): visits every
        /// immediate child expression mutably. Bodies are NOT descended,
        /// matching the immutable boundary: the parse-time placeholder
        /// qualifier recurses per statement with its own frames.
        /// Exhaustive for the same reason: new expression carriers fail
        /// compilation here.
        pub fn walk_exprs_mut(&mut self, $f: &mut impl FnMut(&mut Expr)) {
            // One `Arg`: the typed expressions inside; literal text is skipped.
            fn $wa(arg: &mut Arg, $f: &mut impl FnMut(&mut Expr)) {
                match arg {
                    Arg::Expr(expr) => $f(expr),
                    Arg::Parts(parts) => {
                        for part in parts {
                            if let ArgPart::Expr(expr) = part {
                                $f(expr);
                            }
                        }
                    }
                    Arg::String(..) => {}
                }
            }
            // An optional `Arg`, when present.
            fn $wo(arg: &mut Option<Arg>, $f: &mut impl FnMut(&mut Expr)) {
                if let Some(arg) = arg {
                    $wa(arg, $f);
                }
            }
            // An assertion target holding a value.
            fn $wt(target: &mut AssertTarget, $f: &mut impl FnMut(&mut Expr)) {
                if let AssertTarget::Value(arg) = target {
                    $wa(arg, $f);
                }
            }
            match self {
                $($arms)*
            }
        }
    };
}

impl StepKind {
    define_expr_walkers!(f, walk_arg, walk_opt, walk_target, {
            StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
            StepKind::Return { expr, .. } => f(expr),
            StepKind::Call { args, .. } => {
                for arg in args {
                    f(arg);
                }
            }
            StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => {}
            StepKind::For { in_expr, .. } => f(in_expr),
            StepKind::If { cond, else_ifs, .. } => {
                f(cond);
                for (cond, _) in else_ifs {
                    f(cond);
                }
            }
            StepKind::While { cond, .. } => f(cond),
            StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
                walk_arg(duration, f);
            }
            StepKind::Workdir(arg)
            | StepKind::Echo(arg)
            | StepKind::Run(arg)
            | StepKind::Mkdir(arg)
            | StepKind::Exit(arg) => walk_arg(arg, f),
            StepKind::Env { value, .. } => walk_arg(value, f),
            StepKind::Copy { from, to, .. }
            | StepKind::Symlink { from, to, .. }
            | StepKind::Archive {
                src: from, dst: to, ..
            }
            | StepKind::Install { from, to } => {
                walk_arg(from, f);
                walk_arg(to, f);
            }
            StepKind::SetExecutable { path } => walk_arg(path, f),
            StepKind::Unarchive {
                src,
                dst,
                max_bytes,
            } => {
                walk_arg(src, f);
                walk_arg(dst, f);
                walk_opt(max_bytes, f);
            }
            StepKind::CopyGit { rev, from, to, .. } => {
                walk_arg(rev, f);
                walk_arg(from, f);
                walk_arg(to, f);
            }
            StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
            StepKind::Remove { path, .. } => walk_arg(path, f),
            StepKind::Prompt {
                message, default, ..
            } => {
                walk_arg(message, f);
                walk_opt(default, f);
            }
            StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
                walk_arg(path, f);
                walk_opt(contents, f);
            }
            StepKind::AppendLine { path, contents } => {
                walk_arg(path, f);
                walk_arg(contents, f);
            }
            StepKind::Expand { path, overrides } => {
                walk_opt(path, f);
                for (_, value) in overrides {
                    walk_arg(value, f);
                }
            }
            StepKind::AssertEq {
                actual, expected, ..
            }
            | StepKind::AssertNe {
                actual, expected, ..
            } => {
                walk_target(actual, f);
                walk_opt(expected, f);
            }
            StepKind::AssertContains { haystack, needle } => {
                walk_target(haystack, f);
                walk_arg(needle, f);
            }
            StepKind::ListAppend { item, .. } => walk_arg(item, f),
            StepKind::RunExec { argv } => {
                for arg in argv {
                    walk_arg(arg, f);
                }
            }
            StepKind::WithIo { .. }
            | StepKind::WithIoBlock { .. }
            | StepKind::TypeAlias { .. }
            | StepKind::Workspace(_)
            | StepKind::InheritEnv { .. }
            | StepKind::Isolated { .. }
            | StepKind::IsolatedInheritEnv { .. }
            | StepKind::ReadLine { .. }
            | StepKind::AssignCapture { .. }
            | StepKind::AwaitCapture { .. }
            | StepKind::AsyncBlock { .. }
            | StepKind::AssignAsync { .. }
            | StepKind::Await { .. }
            | StepKind::Cancel { .. }
            | StepKind::RemoteBlock { .. }
            | StepKind::FuncDef { .. }
            | StepKind::Break
            | StepKind::Continue => {}
    });

    define_raw_string_walkers!(f, walk_arg, walk_opt, walk_target, {
        StepKind::Assign { .. }
                | StepKind::Set { .. }
                | StepKind::Call { .. }
                | StepKind::Return { .. }
                | StepKind::For { .. }
                | StepKind::If { .. }
                | StepKind::While { .. } => {}
                StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
                    walk_arg(duration, f);
                }
                StepKind::Workdir(arg)
                | StepKind::Echo(arg)
                | StepKind::Run(arg)
                | StepKind::Mkdir(arg)
                | StepKind::Exit(arg) => walk_arg(arg, f),
                StepKind::Env { value, .. } => walk_arg(value, f),
                StepKind::Copy { from, to, .. }
                | StepKind::Symlink { from, to, .. }
                | StepKind::Archive {
                    src: from, dst: to, ..
                }
                | StepKind::Install { from, to } => {
                    walk_arg(from, f);
                    walk_arg(to, f);
                }
                StepKind::SetExecutable { path } => walk_arg(path, f),
                StepKind::Unarchive {
                    src,
                    dst,
                    max_bytes,
                } => {
                    walk_arg(src, f);
                    walk_arg(dst, f);
                    walk_opt(max_bytes, f);
                }
                StepKind::CopyGit { rev, from, to, .. } => {
                    walk_arg(rev, f);
                    walk_arg(from, f);
                    walk_arg(to, f);
                }
                StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
                StepKind::Remove { path, .. } => walk_arg(path, f),
                StepKind::Prompt {
                    message, default, ..
                } => {
                    walk_arg(message, f);
                    walk_opt(default, f);
                }
                StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
                    walk_arg(path, f);
                    walk_opt(contents, f);
                }
                StepKind::AppendLine { path, contents } => {
                    walk_arg(path, f);
                    walk_arg(contents, f);
                }
                StepKind::Expand { path, overrides } => {
                    walk_opt(path, f);
                    for (_, value) in overrides {
                        walk_arg(value, f);
                    }
                }
                StepKind::AssertEq {
                    actual, expected, ..
                }
                | StepKind::AssertNe {
                    actual, expected, ..
                } => {
                    walk_target(actual, f);
                    walk_opt(expected, f);
                }
                StepKind::AssertContains { haystack, needle } => {
                    walk_target(haystack, f);
                    walk_arg(needle, f);
                }
                StepKind::ListAppend { item, .. } => walk_arg(item, f),
                StepKind::RunExec { argv } => {
                    for arg in argv {
                        walk_arg(arg, f);
                    }
                }
                StepKind::WithIo { .. }
                | StepKind::WithIoBlock { .. }
                | StepKind::TypeAlias { .. }
                | StepKind::Workspace(_)
                | StepKind::ImportFile { .. }
                | StepKind::ImportFuncs { .. }
                | StepKind::InheritEnv { .. }
                | StepKind::Isolated { .. }
                | StepKind::IsolatedInheritEnv { .. }
                | StepKind::ReadLine { .. }
                | StepKind::AssignCapture { .. }
                | StepKind::AwaitCapture { .. }
                | StepKind::AsyncBlock { .. }
                | StepKind::AssignAsync { .. }
                | StepKind::Await { .. }
                | StepKind::Cancel { .. }
                | StepKind::RemoteBlock { .. }
                | StepKind::FuncDef { .. }
                | StepKind::Break
                | StepKind::Continue => {}
    });

    /// Visit every immediate child kind: boxed sub-commands and the kinds
    /// of every body step. Exhaustive like [`walk_exprs`](Self::walk_exprs):
    /// new block shapes fail compilation here.
    pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
        fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
            for step in body {
                f(&step.kind);
            }
        }
        match self {
            StepKind::WithIo { cmd, .. } => f(cmd),
            StepKind::AssignCapture { cmd, .. } => f(cmd),
            StepKind::For { body, .. }
            | StepKind::While { body, .. }
            | StepKind::FuncDef { body, .. }
            | StepKind::Timeout { body, .. }
            | StepKind::Isolated { body }
            | StepKind::AssignAsync { body, .. }
            | StepKind::AsyncBlock { body }
            | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
            StepKind::If {
                then_body,
                else_ifs,
                else_body,
                ..
            } => {
                walk_body(then_body, f);
                for (_, body) in else_ifs {
                    walk_body(body, f);
                }
                if let Some(body) = else_body {
                    walk_body(body, f);
                }
            }
            StepKind::InheritEnv { .. }
            | StepKind::IsolatedInheritEnv { .. }
            | StepKind::TypeAlias { .. }
            | StepKind::Workdir(_)
            | StepKind::Workspace(_)
            | StepKind::Env { .. }
            | StepKind::Echo(_)
            | StepKind::Run(_)
            | StepKind::RunExec { .. }
            | StepKind::Copy { .. }
            | StepKind::CopyGit { .. }
            | StepKind::Symlink { .. }
            | StepKind::Archive { .. }
            | StepKind::Unarchive { .. }
            | StepKind::Install { .. }
            | StepKind::SetExecutable { .. }
            | StepKind::Mkdir(_)
            | StepKind::Ls(_)
            | StepKind::Read(_)
            | StepKind::ReadLine { .. }
            | StepKind::Prompt { .. }
            | StepKind::Write { .. }
            | StepKind::Append { .. }
            | StepKind::AppendLine { .. }
            | StepKind::Remove { .. }
            | StepKind::Expand { .. }
            | StepKind::AssertEq { .. }
            | StepKind::AssertNe { .. }
            | StepKind::AssertContains { .. }
            | StepKind::Exit(_)
            | StepKind::WithIoBlock { .. }
            | StepKind::Assign { .. }
            | StepKind::Set { .. }
            | StepKind::AwaitCapture { .. }
            | StepKind::Await { .. }
            | StepKind::Cancel { .. }
            | StepKind::Sleep { .. }
            | StepKind::ListAppend { .. }
            | StepKind::Call { .. }
            | StepKind::ImportFile { .. }
            | StepKind::ImportFuncs { .. }
            | StepKind::Return { .. }
            | StepKind::Break
            | StepKind::Continue => {}
        }
    }

    /// Visit every descendant expression in the full subtree: immediate
    /// expressions (deep via [`Expr::walk`](crate::ast::Expr::walk)) plus
    /// every nested body and boxed sub-command. The single traversal every
    /// AST inspection pass should use.
    pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
        self.walk_exprs(&mut |expr| expr.walk(f));
        self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
    }
}

/// First-argument target for `ASSERT_EQ` / `ASSERT_CONTAINS`.
///
/// Values (`Arg`) evaluate in memory and never touch disk. The `Stdout`
/// and `Stderr` markers observe stream buffers. Pipes are asserted through
/// plain variables: a `$var` holding a `PIPE` peeks its backend bytes at
/// runtime, so no pipe marker variant exists. Bare `stdout` / `stderr`
/// spellings lower to markers; quoted spellings stay literal string
/// values, so quoting remains interchangeable everywhere.
#[derive(Debug, Clone, PartialEq)]
pub enum AssertTarget {
    Value(Arg),
    Stdout,
    Stderr,
}

impl AssertTarget {
    pub fn render(&self) -> String {
        match self {
            AssertTarget::Value(arg) => arg.render(),
            AssertTarget::Stdout => "stdout".to_string(),
            AssertTarget::Stderr => "stderr".to_string(),
        }
    }
}

/// Lower the first positional of `ASSERT_EQ` / `ASSERT_CONTAINS`.
///
/// `Arg::Expr` (variables, key-paths, calls) is always a value : a `$var`
/// holding a `PIPE` peeks its backend bytes at runtime. Bare (unquoted)
/// `stdout` / `stderr` spellings become stream markers; every other
/// spelling, quoted or not, stays a literal value. In particular a `$var`
/// holding a path never reads disk, and quoted `"stdout"` names the
/// seven-character string, not the stream.
fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
    match arg {
        Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
        Arg::String(text, quoted) if !quoted => match text.as_str() {
            "stdout" => Ok(AssertTarget::Stdout),
            "stderr" => Ok(AssertTarget::Stderr),
            _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
                text, false,
            )))),
        },
        other => Ok(AssertTarget::Value(lower_assert_operand(other))),
    }
}

/// Give bare (unquoted, template-free) assertion operands the same typing
/// they carry in expression positions, so `ASSERT_EQ $status 200` compares
/// `Int(200)` rather than the string `"200"`. Signed integers (`-5` in
/// first position), decimals (`3.5`), and `true`/`false` all convert;
/// everything else, including quoted strings, stays a string. Note a
/// grammar property, not a limitation of this helper: `$x -5` in argument
/// position parses as subtraction (`expr_add_sub`), so negative expected
/// values must be bound first (`LET $e: INT = 0 - 5`).
fn lower_assert_operand(arg: Arg) -> Arg {
    match arg {
        Arg::String(text, false) => {
            // Separators strip only when well-formed, so `1_000_000`
            // types as Int while `1__0` keeps its literal reading,
            // exactly like expression position. The original text
            // survives below for the string case.
            let clean = crate::command::strip_digit_separators(&text);
            if let Ok(i) = clean.parse::<i64>() {
                Arg::Expr(Expr::Literal(Value::int(i)))
            } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
                Arg::Expr(Expr::Literal(Value::float(
                    clean.parse::<f64>().unwrap_or(f64::NAN),
                )))
            } else if text == "true" {
                Arg::Expr(Expr::Literal(Value::bool(true)))
            } else if text == "false" {
                Arg::Expr(Expr::Literal(Value::bool(false)))
            } else {
                Arg::String(text, false)
            }
        }
        other => other,
    }
}

/// Shared positional lowering for `ASSERT_EQ`/`ASSERT_NE`: one actual plus
/// an optional expected, with `--hash` carrying the expectation in the
/// flag. Combining `--hash` with a positional expected is rejected so a
/// stray value cannot silently vanish. `verb` names the command for errors.
fn lower_equality_args(
    verb: &str,
    flags: Vec<(String, Arg)>,
    args: Vec<Arg>,
) -> ParseResult<(Option<String>, AssertTarget, Option<Arg>)> {
    let hash = flags
        .iter()
        .find(|(k, _)| k == "hash")
        .map(|(_, v)| v.as_str().to_string());
    let mut it = args.into_iter();
    let actual = lower_assert_target(it.next().ok_or_else(|| {
        ParseError::validation(
            verb,
            format!("{verb} requires a value"),
            &SpanContext::line_only(0),
        )
    })?)?;
    let remaining: Vec<Arg> = it.map(lower_assert_operand).collect::<Vec<Arg>>();
    let expected = if remaining.is_empty() {
        if hash.is_some() {
            None
        } else {
            return Err(ParseError::validation(
                verb,
                format!("{verb} requires an expected value"),
                &SpanContext::line_only(0),
            ));
        }
    } else {
        if hash.is_some() {
            return Err(ParseError::validation(
                verb,
                format!("{verb} --hash cannot be combined with an expected value"),
                &SpanContext::line_only(0),
            ));
        }
        Some(join_value(remaining, verb)?)
    };
    Ok((hash, actual, expected))
}

declare_commands! {
    structural [
        WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
        WithIoBlock { bindings: Vec<IoBinding> },
        TypeAlias { name: String, target: String },
        For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
        If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
        Assign { var: String, decl_type: String, expr: Expr },
        Set { var: String, expr: Expr },
        AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
        AwaitCapture { out_var: String, out_type: String, task_var: String },
        AsyncBlock { body: Vec<Step> },
        AssignAsync { var: String, decl_type: String, body: Vec<Step> },
        Await { var: String },
        Cancel { var: String },
        Timeout { duration: Arg, body: Vec<Step> },
        Isolated { body: Vec<Step> },
        IsolatedInheritEnv { keys: Vec<String> },
        RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
        RunExec { argv: Vec<Arg> },
        FuncDef { name: String, params: Vec<(String, String, bool)>, return_type: String, is_async: bool, body: Vec<Step>, docs: Option<(String, String)> },
        Call { name: String, args: Vec<Expr> },
        Return { expr: Box<Expr>, is_bare: bool },
        ImportFile { path: String, alias: String },
        ImportFuncs {
            path: String,
            alias: Option<String>,
            func_names: Vec<String>,
            type_names: Vec<String>,
        },
        While { cond: Box<Expr>, body: Vec<Step> },
        Break,
        Continue,
    ]

    Workdir => [
        name: "WORKDIR",
        variant: Workdir(Arg),
        syntax: "WORKDIR <path>",
        summary: "Change the working directory.",
        description: indoc! {r#"
            Sets the current working directory.

            Relative paths resolve against the current directory; `/` resets to
            the workspace root. Paths cannot escape the workspace.
        "#},
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
            # Later relative paths resolve under the new directory.
            WORKDIR project/src
            WRITE generated.txt generated-under-workdir

            LET $body: STRING = READ generated.txt
            ASSERT_EQ $body "generated-under-workdir"
        "#} },             Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
            # The block reverts to the starting directory on exit.
            LET $outside: STRING = CWD
            MKDIR project

            [bool:true] {
                WORKDIR project
                WRITE inner.txt inner
            }

            LET $back: STRING = CWD
            ASSERT_EQ $back $outside
            LET $body: STRING = READ project/inner.txt
            ASSERT_EQ $body "inner"
        "#} } ],
        lower: |_flags, args| {
            let path = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKDIR", "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Workdir(path))
        },
    ],

    Workspace => [
        name: "WORKSPACE",
        variant: Workspace(WorkspaceTarget),
        syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
        summary: "Switch workspace roots.",
        description: indoc! {r#"
            Switches the workspace root. The selection reverts at scope
            exit like `WORKDIR`.

            - `SNAPSHOT`: the materialized build snapshot (the default).
              One session-shared directory: every selection resolves to
              it, in any block.
            - `LOCAL`: the local workspace directory.
            - `CACHE`: a persistent per-project directory shared across
              runs, never evicted. It lives under the OS user cache
              (`OXDOCK_CACHE_DIR` pins an exact directory);
              `WORKSPACE CACHE --local` keeps it in
              `<project>/.cache/workspace` instead.
            - `SYSTEM`: full filesystem access. Scripts using it are not
              hermetic.
        "#},
        args: &[ ArgSpec { name: "target", arg_type: ArgType::OneOf(&["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM"]), description: "Target root", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[ FlagSpec { name: "local", long: "--local", value_type: FlagValueType::Flag, required: false, description: "Use the project-local cache directory instead of the OS user cache (CACHE only)" } ],
        default_output: None,
        examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
            IMPORT [STD]
            WORKSPACE LOCAL

            LET $t: STRING = PATH_TYPE(".")
            ASSERT_EQ $t "dir"
        "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
            [bool:true] {
                WORKSPACE CACHE
                WRITE cached.txt cached-content
            }

            COPY --from-workspace CACHE cached.txt restored.txt
            LET $body: STRING = READ restored.txt
            ASSERT_EQ $body "cached-content"
        "#} } ],
        lower: |flags, args| {
            let local = flags.iter().any(|(k, _)| k == "local");
            let target = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKSPACE", "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
            match target.as_str() {
                "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation("WORKSPACE", "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
                "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
                "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
                "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
                "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
                other => Err(ParseError::validation("WORKSPACE", format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
            }
        },
    ],

    Env => [
        name: "ENV",
        variant: Env { key: String, value: Arg },
        syntax: "ENV KEY=value",
        summary: "Set an environment variable.",
        description: indoc! {r#"
            Inserts or updates an env var.

            The value uses the unified string-value rules shared by every command:
            `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
            evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
            words join with single spaces, and the first `=` splits key from value
            (`KEY=a=b` stores `a=b`).

            A `$var` inside larger text stays literal — write `{{ $var }}` to
            interpolate there.
        "#},
        args: &[ ArgSpec { name: "assignment", arg_type: ArgType::String, description: "KEY=value pair; the value resolves as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[
            Example { name: "set env", fence_meta: None, code: indoc! {r#"
                ENV APP_MODE=production
                LET $mode: STRING = env:APP_MODE
                ASSERT_EQ $mode "production"
            "#} },
            Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
                # Quotes keep the space: SET_FORTH stores `outer scope`.
                ENV SET_FORTH="outer scope"
                WRITE out.txt "{{ env:SET_FORTH }}"

                LET $body: STRING = READ out.txt
                ASSERT_EQ $body "outer scope"
            "#} },
            Example { name: "variable value", fence_meta: None, code: indoc! {r#"
                # A lone $var evaluates, like ECHO $var.
                LET $who: STRING = "Alice"
                ENV GREETING=$who
                WRITE out.txt "{{ env:GREETING }}"

                LET $body: STRING = READ out.txt
                ASSERT_EQ $body "Alice"
            "#} },
            Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
                # A bare variable, a quoted literal, and a template all
                # store plain strings through the same value rules.
                LET $x: STRING = "Ada"
                ENV A=$x
                ENV B="hello world"
                ENV C="{{ $x }} concatenated"
                WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"

                LET $body: STRING = READ check.txt
                ASSERT_EQ $body "Ada|hello world|Ada concatenated"
            "#} },
            Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
                # ENV inside a braced block reverts when the block exits
                ENV MODE=production

                [bool:true] {
                    ENV MODE=staging
                    WRITE inner.txt "{{ env:MODE }}"
                }

                WRITE outer.txt "{{ env:MODE }}"

                LET $inner_body: STRING = READ inner.txt
                ASSERT_EQ $inner_body "staging"

                LET $outer_body: STRING = READ outer.txt
                ASSERT_EQ $outer_body "production"
            "#} },
            Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
                # A shell command reads its own environment, with
                # per-platform spelling: quoted "$VAR" passes the parser
                # through untouched on Unix ...
                ENV PROXY_PORT=23791

                [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"

                # ... while cmd expands %VAR% on Windows.
                [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%

                ASSERT_CONTAINS $o "23791"
            "#} },
        ],
        lower: |_flags, args| lower_env_assignment(args),
    ],

    InheritEnv => [
        name: "INHERIT_ENV",
        variant: InheritEnv { keys: Vec<String> },
        syntax: "INHERIT_ENV [<key>, ...]",
        summary: "Inherit env vars from host.",
        description: indoc! {r#"
            Declares which host environment variables to inherit into the script.

            Must appear before any other commands. Several directives may
            appear so platform-specific names ride explicit guards
            (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
            line runs only when its guard passes.

            Sandbox defaults need no declaration: loader bindings,
            terminal defaults, the host lookup path, and the user's
            profile locations seed automatically. See OxDock
            Environment Variable Contracts for the exact list, which grows with the
            engine.

            Secrets and tool config stay opt-in here: a token or a
            `CARGO_HOME` override arrives only through this directive.
        "#},
        args: &[ ArgSpec { name: "keys", arg_type: ArgType::Rest(&ArgType::String), description: "Host variables to inherit", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
            [family:unix] INHERIT_ENV [HOME]
            LET $path: STRING = env:PATH
            [family:unix] ASSERT_CONTAINS $path ":"
            [family:windows] ASSERT_CONTAINS $path ";"
        "#} } ],
        lower: |_flags, args| {
            let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
            Ok(StepKind::InheritEnv { keys })
        },
    ],

    Echo => [
        name: "ECHO",
        variant: Echo(Arg),
        syntax: "ECHO <message>",
        summary: "Print to stdout.",
        description: "Outputs message to stdout.",
        args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: Some(Stream::Stdout),
        examples: &[
            Example { name: "echo", fence_meta: None, code: indoc! {r#"
                ECHO build-complete
                ASSERT_CONTAINS stdout "build-complete"
            "#} },
            Example { name: "variables", fence_meta: None, code: indoc! {r#"
                # {{ }} interpolates inside text; a lone $var evaluates on its own.
                LET $x: STRING = "World"
                ECHO "braced:{{ $x }}"
                ECHO $x
                ASSERT_EQ stdout "braced:World\nWorld\n"
            "#} },
            Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
                # `{{ env:KEY }}` reads the script environment; a bare name
                # resolves a DSL variable instead. Spelling rules:
                # `script_env:` is always case-sensitive; `env:` is
                # case-sensitive too, except on Windows where it matches
                # case-insensitively. Every read must be declared first:
                # KEY here comes from the ENV below.
                ENV USER=OxDock
                LET $WHO: STRING = "Ada"
                ECHO "Hello {{ env:USER }}! Hi {{ WHO }}! Again {{ script_env:USER }}!"
                ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada! Again OxDock!"
            "#} },
            Example { name: "undeclared env read fails", fence_meta: Some("expect_error:\"env:OXDOCK_DOC_NO_SUCH_KEY\""), code: indoc! {r#"
                # No declaration anywhere: the whole-closure static gate
                # rejects the read before the first step runs. (The
                # error names the variable: undeclared environment
                # variable `env:OXDOCK_DOC_NO_SUCH_KEY`.)
                ECHO "Hello {{ env:OXDOCK_DOC_NO_SUCH_KEY }}!"
            "#} },
        ],
        lower: |_flags, args| Ok(StepKind::Echo(join_value(args, "ECHO")?)),
    ],

    Run => [
        name: "RUN",
        variant: Run(Arg),
        syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
        summary: "Execute shell command or direct executable.",
        description: indoc! {r#"
            Shell form (`RUN <command...>`) runs the joined command string in the
            batch shell (`sh -c` / `cmd /C`). Never the operator's login
            shell: login shells re-pollute scrubbed children from system
            profiles and break script portability, so step execution is
            pinned to POSIX `sh` (interactive `oxdock --shell` still uses
            `$SHELL`).

            Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
            with no shell, so there is no shell expansion, globbing, redirection,
            or pipes; use it for portable commands.

            Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
            both forms.
        "#},
        args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
            # Spawned children resolve through the seeded host PATH:
            # closed child env is the default, not ambient inherit.
            RUN echo hello

            # Captured runs prove the output, not just the exit status.
            LET $o: STRING = RUN echo hello
            ASSERT_CONTAINS $o "hello"
        "#}         }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
            # No shell: `>` stays a literal argument, so no file is created.
            # Toolchain spawns bridge the host home explicitly: rustup
            # shims resolve toolchains through the host home.
            IMPORT [STD]
            [family:unix] INHERIT_ENV [HOME]
            [family:windows] INHERIT_ENV [USERPROFILE]
            RUN ["cargo", "--version", ">", "x.txt"]
            ASSERT_CONTAINS stdout "cargo"

            LET $t: STRING = PATH_TYPE("x.txt")
            ASSERT_EQ $t "absent"
        "#} } ],
        lower: |_flags, args| match args.as_slice() {
            [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
                Err(ParseError::validation("RUN", "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
            }
            [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
                argv: elems.iter().cloned().map(Arg::Expr).collect(),
            }),
            _ => Ok(StepKind::Run(join_value(args, "RUN")?)),
        },
    ],

    Copy => [
        name: "COPY",
        variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
        syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
        summary: "Copy file into workspace.",
        description: "Copies from host (the source is never moved or modified). Docker destination semantics: a file copied onto a directory (an existing one, or a trailing-slash spell like `out/`) is duplicated inside it under its own basename; a directory source duplicates its contents into the destination; any other destination path is created holding the copied bytes.",
        args: &[
            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Copy from the given workspace root instead of the build context" }, FlagSpec { name: "from_host", long: "--from-host", value_type: FlagValueType::Flag, required: false, description: "Fetch from the host workspace into the guest (REMOTE bodies only)" }, FlagSpec { name: "to_host", long: "--to-host", value_type: FlagValueType::Flag, required: false, description: "Push from the guest workspace back to the host (REMOTE bodies only)" } ],
        default_output: None,
        examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
            # Copy to a new name, then read back.
            WRITE src.txt content
            COPY src.txt dst.txt

            LET $body: STRING = READ dst.txt
            ASSERT_EQ $body "content"
        "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
            # Same name, different contents per root: only LOCAL has ws-content.
            WRITE shared.txt from-snapshot
            WORKSPACE LOCAL
            WRITE shared.txt ws-content

            WORKSPACE SNAPSHOT
            COPY --from-workspace LOCAL shared.txt ws-copy.txt

            LET $body: STRING = READ ws-copy.txt
            ASSERT_EQ $body "ws-content"
        "#} } ],
        lower: |flags, args| {
            let from_workspace = flags
                .iter()
                .find(|(k, _)| k == "from_workspace")
                .map(|(_, v)| match v.as_str() {
                    "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
                    "LOCAL" => Ok(WorkspaceTarget::Local),
                    "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
                    "SYSTEM" => Ok(WorkspaceTarget::System),
                    other => Err(ParseError::validation("COPY", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
                })
                .transpose()?;
            let mut it = args.into_iter();
            let from = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
            let to = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
            let from_host = flags.iter().any(|(k, _)| k == "from_host");
            let to_host = flags.iter().any(|(k, _)| k == "to_host");
            if from_host && to_host {
                return Err(ParseError::validation("COPY", "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
            }
            Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
        },
    ],

    CopyGit => [
        name: "COPY_GIT",
        variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
        syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
        summary: "Copy from git revision.",
        description: "Checkout and copy.",
        args: &[
            ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
        default_output: None,
        examples: &[ Example { name: "git copy missing source errors", fence_meta: Some("expect_error:\"COPY source missing\""), code: indoc! {r#"COPY_GIT HEAD src.txt dst.txt"#} } ],
        lower: |flags, args| {
            let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
            let mut it = args.into_iter();
            let rev = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
            let from = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
            let to = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::CopyGit { rev, from, to, include_dirty })
        },
    ],

    Symlink => [
        name: "SYMLINK",
        variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
        syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
        summary: "Create symlink.",
        description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
        args: &[
            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Symlink from the given workspace root instead of the build context" } ],
        default_output: None,
        examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
            # A symlink reads like its target.
            WRITE original.txt content
            SYMLINK original.txt link.txt

            LET $body: STRING = READ link.txt
            ASSERT_EQ $body "content"
        "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
            # Same name, different contents per root: only LOCAL has ws-content.
            WRITE shared.txt from-snapshot
            WORKSPACE LOCAL
            WRITE shared.txt ws-content

            WORKSPACE SNAPSHOT
            SYMLINK --from-workspace LOCAL shared.txt ws-link.txt

            LET $body: STRING = READ ws-link.txt
            ASSERT_EQ $body "ws-content"
        "#} } ],
        lower: |flags, args| {
            let from_workspace = flags
                .iter()
                .find(|(k, _)| k == "from_workspace")
                .map(|(_, v)| match v.as_str() {
                    "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
                    "LOCAL" => Ok(WorkspaceTarget::Local),
                    "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
                    "SYSTEM" => Ok(WorkspaceTarget::System),
                    other => Err(ParseError::validation("SYMLINK", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
                })
                .transpose()?;
            let mut it = args.into_iter();
            let from = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
            let to = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Symlink { from_workspace, from, to })
        },
    ],

    Mkdir => [
        name: "MKDIR",
        variant: Mkdir(Arg),
        syntax: "MKDIR <path>",
        summary: "Create directory.",
        description: "Creates dir with parents.",
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
            IMPORT [STD]
            MKDIR deeply/nested/tree

            LET $t: STRING = PATH_TYPE("deeply/nested/tree")
            ASSERT_EQ $t "dir"
        "#} } ],
        lower: |_flags, args| Ok(StepKind::Mkdir(args.into_iter().next().ok_or_else(|| ParseError::validation("MKDIR", "MKDIR requires a path".to_string(), &SpanContext::line_only(0)))?)),
    ],

    Install => [
        name: "INSTALL",
        variant: Install { from: Arg, to: Arg },
        syntax: "INSTALL <source> <dest>",
        summary: "Atomically install a verified binary as executable.",
        description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
        args: &[
            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
            # Place a verified binary with executable mode.
            IMPORT [STD]
            WRITE src.bin payload
            INSTALL src.bin dst-bin/tool

            LET $t: STRING = PATH_TYPE("dst-bin/tool")
            ASSERT_EQ $t "file"
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let from = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
            let to = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Install { from, to })
        },
    ],

    SetExecutable => [
        name: "SET_EXECUTABLE",
        variant: SetExecutable { path: Arg },
        syntax: "SET_EXECUTABLE <path>",
        summary: "Mark a file executable.",
        description: "Sets the executable bit on an existing file without moving it. Owner rwx on Unix, bit no-op elsewhere, so the same script runs on every platform; a missing path fails everywhere. `INSTALL` stages, marks, and renames in one atomic step; this command only flips the bit where the file already lives.",
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File to mark executable", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "set-executable", fence_meta: Some("roots:unified"), code: indoc! {r#"
            # Mark a rendered script executable in place.
            IMPORT [STD]
            WRITE tool.sh "echo hi"
            SET_EXECUTABLE tool.sh

            LET $t: STRING = PATH_TYPE("tool.sh")
            ASSERT_EQ $t "file"
        "#} } ],
        lower: |_flags, args| Ok(StepKind::SetExecutable { path: args.into_iter().next().ok_or_else(|| ParseError::validation("SET_EXECUTABLE", "SET_EXECUTABLE requires a path".to_string(), &SpanContext::line_only(0)))? }),
    ],

    Archive => [
        name: "ARCHIVE",
        variant: Archive { src: Arg, dst: Arg, raw: bool },
        syntax: "ARCHIVE [--raw] <src> <dst>",
        summary: "Pack a file or directory into a tarball.",
        description: indoc! {r#"
            Packs a file or directory into a tarball, gzip-compressed by
            default (`--raw` writes an uncompressed tar instead).

            A lone file packs as a single top-level entry under its
            basename; a directory recurses, preserving empty dirs. Source
            modes ride in the headers on Unix, so system `tar` restores
            them elsewhere. Symlink sources refuse: archives cross trust
            boundaries, so links never resolve into member bytes. Hashing
            stays with `HASH_SHA256`, which reads the finished archive
            like any other file.
        "#},
        args: &[
            ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
        default_output: None,
        examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
            # Stage a small tree to pack.
            WRITE bundle/app.txt bundled-payload
            WRITE bundle/nested/deep.txt deep-payload

            # ARCHIVE packs it gzip-compressed by default.
            ARCHIVE bundle bundle.tar.gz

            # UNARCHIVE restores the tree under the destination.
            UNARCHIVE bundle.tar.gz restored

            # The payloads arrive byte-identical.
            LET $body: STRING = READ restored/app.txt
            ASSERT_EQ $body "bundled-payload"

            LET $deep: STRING = READ restored/nested/deep.txt
            ASSERT_EQ $deep "deep-payload"
        "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
            # A lone file packs as a single top-level entry.
            WRITE tool.bin tool-payload

            # Raw archives skip gzip and stay readable by any tar.
            ARCHIVE --raw tool.bin tool.tar
            UNARCHIVE tool.tar tool-out

            # The entry lands under its basename.
            LET $body: STRING = READ tool-out/tool.bin
            ASSERT_EQ $body "tool-payload"
        "#} } ],
        lower: |flags, args| {
            let raw = flags.iter().any(|(k, _)| k == "raw");
            let mut it = args.into_iter();
            let src = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
            let dst = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Archive { src, dst, raw })
        },
    ],

    Unarchive => [
        name: "UNARCHIVE",
        variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
        syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
        summary: "Unpack a tarball into a directory.",
        description: indoc! {r#"
            Unpacks a tarball under the destination directory, creating
            it first. Gzip and raw (`ARCHIVE --raw`) tarballs
            self-identify by magic bytes, so no flag is needed.

            Member bytes meter against a 1 GiB default expansion cap
            across the whole archive: a decompression bomb trips it
            instead of filling the disk, and `--max-bytes` moves the
            ceiling either way (plain integer bytes). The tripped member
            stays truncated on disk while the step fails loudly.

            Symlink and special members refuse naming the entry, and
            absolute or escaping paths fail closed before any byte
            lands: the member sanitizer plus the destination join check
            form two independent walls. Unix modes recorded in the
            headers restore on unpack; other platforms land default
            modes (confer executability with `INSTALL` there).
        "#},
        args: &[
            ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "max_bytes", long: "--max-bytes", value_type: FlagValueType::String, required: false, description: "Cap total unpacked member bytes: bare digits are bytes (`1_000_000` grouping allowed), suffixes B/KB/MB/GB/TB (decimal) and KIB/MIB/GIB/TIB (binary), any case, one optional space before the unit (defaults to 1 GiB)" } ],
        default_output: None,
        examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
            # Pack a note, then restore it under a fresh destination.
            WRITE pack/note.txt packed-note
            ARCHIVE pack pack.tar.gz
            UNARCHIVE pack.tar.gz unpacked

            LET $body: STRING = READ unpacked/note.txt
            ASSERT_EQ $body "packed-note"
        "#}         }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
            # Small payloads clear even a tight ceiling.
            WRITE pack/note.txt packed-note
            ARCHIVE pack pack.tar.gz
            UNARCHIVE pack.tar.gz capped --max-bytes 100KB

            LET $body: STRING = READ capped/note.txt
            ASSERT_EQ $body "packed-note"
        "#} } ],
        lower: |flags, args| {
            let mut it = args.into_iter();
            let src = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
            let dst = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
            let max_bytes = flags
                .into_iter()
                .find_map(|(k, v)| (k == "max_bytes").then_some(v));
            // Static literals fail fast at parse; templates and
            // variables defer to the runtime resolver, which enforces
            // the same shape on the resolved value.
            if let Some(Arg::String(text, _)) = max_bytes.as_ref()
                && !text.contains("{{")
                && let Err(e) = crate::command::parse_byte_count(text)
            {
                return Err(ParseError::validation(
                    "UNARCHIVE",
                    format!("UNARCHIVE --max-bytes {e:#}"),
                    &SpanContext::line_only(0),
                ));
            }
            Ok(StepKind::Unarchive { src, dst, max_bytes })
        },
    ],

    Ls => [
        name: "LS",
        variant: Ls(Option<Arg>),
        syntax: "LS [<path>]",
        summary: "List directory.",
        description: "Lists entries.",
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
        flags: &[],
        default_output: Some(Stream::Stdout),
        examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
            MKDIR inventory
            WRITE inventory/a.txt a
            LS inventory
            ASSERT_CONTAINS stdout "a.txt"
        "#} } ],
        lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
    ],

    Read => [
        name: "READ",
        variant: Read(Option<Arg>),
        syntax: "READ [<path>]",
        summary: "Read file to stdout.",
        description: "Outputs file contents.",
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
        flags: &[],
        default_output: Some(Stream::Stdout),
        examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
            WRITE note.txt "hello"
            READ note.txt

            LET $body: STRING = READ note.txt
            ASSERT_EQ $body "hello"
        "#} } ],
        lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
    ],

    ReadLine => [
        name: "READ_LINE",
        variant: ReadLine { var: String },
        syntax: "READ_LINE $var",
        summary: "Read one line from stdin into a variable.",
        description: indoc! {r#"
            Reads bytes until newline without waiting for EOF, leaving the pipe open.

            Trailing newline is stripped (shell-read parity). On premature EOF
            assigns accumulated bytes and returns.
        "#},
        args: &[ ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the line binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
            # The trailing newline is stripped: the variable holds exactly `first`.
            LET $lines: PIPE
            WITH_IO [stdout=$lines] ECHO "first"
            WITH_IO [stdin=$lines] READ_LINE $reply
            ASSERT_EQ $reply "first"
        "#} } ],
        lower: |_flags, args| {
            let arg = args.into_iter().next().ok_or_else(|| ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
            let var = match arg {
                Arg::Expr(Expr::Var(name)) => name,
                // Quoted "$var" keeps its sigil through the generic string
                // path; templates defer untouched exactly as before.
                Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
                other => return Err(ParseError::validation("READ_LINE", format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
            };
            if var.is_empty() {
                return Err(ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
            }
            Ok(StepKind::ReadLine { var })
        },
    ],

    Prompt => [
        name: "PROMPT",
        variant: Prompt { var: String, message: Arg, default: Option<Arg> },
        syntax: "PROMPT $var <message> [<default>]",
        summary: "Prompt on the terminal into a variable.",
        description: indoc! {r#"
            Prints `{message} [{default}]: ` (or `{message}: ` with no
            default) to stderr and reads one line from the terminal.

            Empty input yields the default when one is given, else an
            empty string. EOF aborts loudly. Non-TTY stdin never reads:
            a default binds with a stderr note, while no default bails.
        "#},
        args: &[
            ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the answer binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
            ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
            # A redirected stdin can never answer: without a default the
            # prompt fails instead of hanging or reading piped stdin.
            LET $p: PIPE
            WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
            let var = match var_arg {
                Arg::Expr(Expr::Var(name)) => name,
                Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
                other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
            };
            if var.is_empty() {
                return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
            }
            let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
            let default = it.next();
            Ok(StepKind::Prompt { var, message, default })
        },
    ],

    Write => [
        name: "WRITE",
        variant: Write { path: Arg, contents: Option<Arg> },
        syntax: "WRITE <path> [<contents>]",
        summary: "Write to file.",
        description: "Writes contents. Bytes land exactly as given: no line-ending translation happens on any platform (LF stays LF, even on Windows), so the same script produces identical files everywhere.",
        args: &[
            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
            WRITE output.txt hello-world
            LET $body: STRING = READ output.txt
            ASSERT_EQ $body "hello-world"
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
            let remaining: Vec<Arg> = it.collect();
            let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
            Ok(StepKind::Write { path, contents })
        },
    ],

    Append => [
        name: "APPEND",
        variant: Append { path: Arg, contents: Option<Arg> },
        syntax: "APPEND <path> [<contents>]",
        summary: "Append to file.",
        description: "Appends contents with no separator and no line ending: bytes concatenate exactly, so `APPEND` never terminates the line (use `APPEND_LINE` for that). Bytes land exactly as given: no line-ending translation happens on any platform (LF stays LF, even on Windows), so the same script produces identical files everywhere.",
        args: &[
            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
            WRITE log.txt line1
            APPEND log.txt line2

            # No separator or newline is added: the bytes concatenate
            # exactly, so this asserts the unterminated form.
            LET $all: STRING = READ log.txt
            ASSERT_EQ $all "line1line2"
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
            let remaining: Vec<Arg> = it.collect();
            let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
            Ok(StepKind::Append { path, contents })
        },
    ],

    AppendLine => [
        name: "APPEND_LINE",
        variant: AppendLine { path: Arg, contents: Arg },
        syntax: "APPEND_LINE <path> <contents>",
        summary: "Append one line to a file.",
        description: "Appends contents plus exactly one trailing LF newline (`\\n`, never the platform newline), so callers never spell the terminator by hand and output bytes stay identical on every OS. Contents are required: unlike APPEND there is no stdin form, a line is a complete value, not a stream.",
        args: &[
            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Line content (the newline is added)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "append-line", fence_meta: None, code: indoc! {r#"
            WRITE log.txt line1
            APPEND_LINE log.txt line2
            APPEND_LINE log.txt line3

            # Each APPEND_LINE terminates its own write.
            LET $all: STRING = READ log.txt
            ASSERT_EQ $all "line1line2\nline3\n"
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let path = it.next().ok_or_else(|| ParseError::validation("APPEND_LINE", "APPEND_LINE requires a path".to_string(), &SpanContext::line_only(0)))?;
            let remaining: Vec<Arg> = it.collect();
            let contents = join_value(remaining, "APPEND_LINE")?;
            Ok(StepKind::AppendLine { path, contents })
        },
    ],

    Remove => [
        name: "REMOVE",
        variant: Remove { path: Arg, recursive: bool },
        syntax: "REMOVE [--recursive] <path>",
        summary: "Remove a file, symlink, or directory.",
        description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
        default_output: None,
        examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
            # WRITE then REMOVE leaves nothing behind.
            IMPORT [STD]
            WRITE scratch.txt content

            # Assert original file is written
            LET $o: STRING = PATH_TYPE("scratch.txt")
            ASSERT_EQ $o "file"

            REMOVE scratch.txt

            # Assert file has been removed
            LET $t: STRING = PATH_TYPE("scratch.txt")
            ASSERT_EQ $t "absent"
        "#} } ],
        lower: |flags, args| {
            let recursive = flags.iter().any(|(k, _)| k == "recursive");
            let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Remove { path, recursive })
        },
    ],

    Expand => [
        name: "EXPAND",
        variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
        syntax: "EXPAND [<path>] [<KEY=val> ...]",
        summary: "Expand a template file (or stdin) to stdout.",
        description: indoc! {r#"
            A template is any text file — or piped stdin when no path is given —
            containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
            and prints the result to stdout.

            Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
            command; `{{ env:NAME }}` reads an override, falling back to the
            environment; `{{ $var }}` reads a script variable (dotted paths allowed).
            A missing key is an error, never a silent empty.

            Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
            with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
            literals as arguments. A bare `{{ NAME(args) }}` resolves exactly
            like a statement-position call: `IMPORT [MODULE]` brings the names
            into scope, unimported names fail naming the fix, ambiguity fails
            closed. Arguments check against the registered
            signature, so wrong arity or mistyped values fail at the call;
            unknown names fail listing the known functions. Only pure
            functions resolve here: stateful, script-defined, and pipe-backed
            entries fail naming themselves, since placeholder evaluation
            carries no step context. The same calls resolve in ordinary
            strings, so both paths agree.

            Substitution runs in a single pass. `EXPAND` is not recursive and does not
            expand nested placeholders: a value that itself contains `{{ ... }}` is
            inserted verbatim and never expanded again.

            A bare `$var` argument is a template path; `KEY=val` arguments are
            overrides whose values follow the unified string-value rules (same as
            `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
            `{{ ... }}` interpolates).

            NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
            (`\{{ ... }}`) when writing a template file for a later `EXPAND`.

            With no path, the template arrives on stdin through a pipe. When piping
            from a shell, single-quote the template (`echo '{{ $x }}'`): double
            quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
            placeholder and errors.
        "#},
        args: &[
            ArgSpec { name: "path", arg_type: ArgType::Path, description: "Template file to expand; omit to expand stdin", io: IoDirection::Read, index: 0, required: false, fallback_stream: None },
            ArgSpec { name: "overrides", arg_type: ArgType::Rest(&ArgType::String), description: "Template overrides shadowing that key (unified string values)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
        ],
        flags: &[],
        default_output: Some(Stream::Stdout),
        examples: &[
            Example { name: "expand", fence_meta: None, code: indoc! {r#"
                # Placeholders read overrides first, then the environment.
                ENV NAME="Alice"
                WRITE template.md "Hello {{ env:NAME }}!"
                EXPAND template.md

                ASSERT_CONTAINS stdout "Hello Alice!"
            "#} },
            Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
                # WRITE would interpolate {{ }} right away, so escape it.
                # The file must literally contain {{ env:NAME }} for EXPAND.
                WRITE template.md "Hello \{{ env:NAME }}!"
                EXPAND template.md NAME="Alice Smith"

                ASSERT_CONTAINS stdout "Hello Alice Smith!"
            "#} },
            Example { name: "variable override", fence_meta: None, code: indoc! {r#"
                # Same escaping: keep the placeholder literal until EXPAND.
                # A lone $who evaluates, like ECHO $who.
                LET $who: STRING = "Bob"
                WRITE template.md "Hi \{{ env:WHO }}!"
                EXPAND template.md WHO=$who

                ASSERT_CONTAINS stdout "Hi Bob!"
            "#} },
            Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
                # A bare variable and a template-with-tail expand identically.
                LET $x: STRING = "Ada"
                WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
                EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"

                ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
            "#} },
            Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
                # No path: the template arrives on stdin through a pipe.
                LET $tpl: PIPE
                WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
                WITH_IO [stdin=$tpl] EXPAND NAME=Alice

                ASSERT_CONTAINS stdout "Hello Alice!"
            "#} },
            Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
                # KEY=val overrides shadow env for that EXPAND only.
                # They never update the environment itself.
                ENV NAME="Alice"
                WRITE template.md "Hi \{{ env:NAME }}!"

                EXPAND template.md NAME="Bob"
                ASSERT_CONTAINS stdout "Hi Bob!"

                EXPAND template.md
                ASSERT_CONTAINS stdout "Hi Alice!"
            "#} },
            Example { name: "function call", fence_meta: None, code: indoc! {r#"
                # Pure registry functions run inside placeholders.
                # WRITE would interpolate {{ }} right away, so escape it.
                IMPORT [STD]
                WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"

                EXPAND template.md
                ASSERT_CONTAINS stdout "Count: 2!"
            "#} },
            Example { name: "bare override", fence_meta: None, code: indoc! {r#"
                # A bare name reads a KEY=val override with no prefix.
                WRITE template.md "Hi \{{ NAME }}!"

                EXPAND template.md NAME=Ada
                ASSERT_CONTAINS stdout "Hi Ada!"
            "#} },
            Example { name: "variable placeholder", fence_meta: None, code: indoc! {r#"
                # `{{ $var }}` placeholders read script variables, dotted
                # paths included. Escape at WRITE so EXPAND sees it.
                LET $u: MAP<name: STRING> = {name: "Bo"}
                WRITE template.md "Hi \{{ $u.name }}!"

                EXPAND template.md
                ASSERT_CONTAINS stdout "Hi Bo!"
            "#} },
            Example { name: "missing key fails", fence_meta: Some("expect_error:\"missing required step override argument\""), code: indoc! {r#"
                # A missing key is an error, never a silent empty.
                WRITE template.md "Hi \{{ NAME }}!"

                EXPAND template.md
            "#} },
        ],
        lower: |_flags, args| {
            let mut path = None;
            let mut overrides = Vec::new();
            for arg in args {
                let text = arg.as_str();
                if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
                    overrides.push((key, value));
                } else if path.is_none() { path = Some(arg); }
                else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
            }
            Ok(StepKind::Expand { path, overrides })
        },
    ],

    AssertEq => [
        name: Command::AssertEq.as_str(),
        variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
        syntax: Command::AssertEq.syntax(),
        summary: "Assert strict equality.",
        description: indoc! {r#"
            Compares two evaluated values with typed equality (no coercion:
            `INT(42)` never equals `STRING("42")`), aborting the pipeline
            with a step-numbered error showing expected vs actual otherwise.

            Both sides are values: `$var`, literals, templates, and calls
            evaluate in memory and never touch disk. Read files explicitly
            first (`LET $text: STRING = READ "out.txt"`, then
            `ASSERT_EQ $text ...`).
            Bare `stdout` / `stderr` observe stream buffers; a `$var`
            holding a `PIPE` observes its backend bytes. `--hash` compares
            the SHA-256 of a string, pipe, or captured-stdout actual
            instead of the raw bytes (`stderr` is unsupported).
        "#},
        args: &[
            ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
        default_output: None,
        examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
            LET $status: INT = 200
            ASSERT_EQ $status 200
        "#} },
        Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
            WRITE payload.bin stable-content
            LET $body: STRING = READ payload.bin
            ASSERT_EQ $body "stable-content"
        "#} },
        Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
            # --hash compares the SHA-256 digest instead of raw bytes.
            WRITE payload.bin stable-content
            LET $body: STRING = READ payload.bin
            ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
        "#} } ],
        lower: |flags, args| {
            let (hash, actual, expected) = lower_equality_args(Command::AssertEq.as_str(), flags, args)?;
            Ok(StepKind::AssertEq { hash, actual, expected })
        },
    ],

    AssertNe => [
        name: Command::AssertNe.as_str(),
        variant: AssertNe { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
        syntax: Command::AssertNe.syntax(),
        summary: "Assert strict inequality.",
        description: indoc! {r#"
            Compares two evaluated values with typed inequality (no coercion:
            `INT(42)` never equals `STRING("42")`), aborting the pipeline
            with a step-numbered error showing expected vs actual when they
            are equal; differing values pass silently.

            Both sides are values: `$var`, literals, templates, and calls
            evaluate in memory and never touch disk. Read files explicitly
            first (`LET $text: STRING = READ "out.txt"`, then
            `ASSERT_NE $text ...`).
            Bare `stdout` / `stderr` observe stream buffers; a `$var`
            holding a `PIPE` observes its backend bytes. `--hash` compares
            the SHA-256 of a string, pipe, or captured-stdout actual
            instead of the raw bytes (`stderr` is unsupported); the digest
            must differ from the given hash.
        "#},
        args: &[
            ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Value the actual must differ from (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
        ],
        flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
        default_output: None,
        examples: &[ Example { name: "assert ne", fence_meta: None, code: indoc! {r#"
            LET $status: INT = 200
            ASSERT_NE $status 404
        "#} },
        Example { name: "assert ne file", fence_meta: None, code: indoc! {r#"
            WRITE payload.bin stable-content
            LET $body: STRING = READ payload.bin
            ASSERT_NE $body "other-content"
        "#} },
        Example { name: "assert ne hash", fence_meta: None, code: indoc! {r#"
            # --hash compares the SHA-256 digest instead of raw bytes.
            WRITE payload.bin stable-content
            LET $body: STRING = READ payload.bin
            ASSERT_NE --hash 0000000000000000000000000000000000000000000000000000000000000000 $body
        "#} } ],
        lower: |flags, args| {
            let (hash, actual, expected) = lower_equality_args(Command::AssertNe.as_str(), flags, args)?;
            Ok(StepKind::AssertNe { hash, actual, expected })
        },
    ],

    AssertContains => [
        name: Command::AssertContains.as_str(),
        variant: AssertContains { haystack: AssertTarget, needle: Arg },
        syntax: Command::AssertContains.syntax(),
        summary: "Assert containment.",
        description: indoc! {r#"
            Checks containment and aborts the pipeline with a step-numbered
            error otherwise: substring for strings, element match for lists,
            key presence for maps, substring over stream and pipe buffers.

            Like `ASSERT_EQ`, both sides are values read without implicit
            I/O; read files explicitly first
            (`LET $text: STRING = READ "cfg.txt"`).
            Bare `stdout` / `stderr` observe stream buffers; a `$var`
            holding a `PIPE` observes its backend bytes.
        "#},
        args: &[
            ArgSpec { name: "haystack", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
            ECHO build-complete
            ASSERT_CONTAINS stdout "build-complete"
        "#} } ],
        lower: |flags, args| {
            let _ = flags;
            let mut it = args.into_iter();
            let haystack = lower_assert_target(it.next().ok_or_else(|| ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a value", Command::AssertContains.as_str()), &SpanContext::line_only(0)))?)?;
            let remaining: Vec<Arg> = it
                .map(lower_assert_operand)
                .collect::<Vec<Arg>>();
            if remaining.is_empty() {
                return Err(ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a needle", Command::AssertContains.as_str()), &SpanContext::line_only(0)))
            }
            let needle = join_value(remaining, Command::AssertContains.as_str())?;
            Ok(StepKind::AssertContains { haystack, needle })
        },
    ],

    Exit => [
        name: "EXIT",
        variant: Exit(Arg),
        syntax: "EXIT <code>",
        summary: "Exit pipeline.",
        description: indoc! {r#"
            Stops the pipeline immediately with an `EXIT requested with code <code>`
            error; steps after it never run, at any nesting depth.

            Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
            anonymous background tasks are killed synchronously, and files written
            before the EXIT persist.

            The code reaches the OS: the CLI exits with `<code>` clamped to
            0..=255, and a guest EXIT relays through `REMOTE` the same way.
        "#},
        args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
        lower: |_flags, args| {
            // Static literals were already Int-checked by the central
            // validator; dynamics resolve (and validate) at runtime.
            let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
            Ok(StepKind::Exit(code))
        },
    ],

    Sleep => [
        name: "SLEEP",
        variant: Sleep { duration: Arg },
        syntax: "SLEEP <duration>",
        summary: "Pause execution for a duration.",
        description: indoc! {r#"
            Parks the step for the duration (e.g. 500ms, 10s, 2m).

            Cooperative: checks for cancellation so an enclosing TIMEOUT or task
            teardown interrupts the sleep. Cross-platform alternative to shell sleep
            for testing time boundaries.
        "#},
        args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
        flags: &[],
        default_output: None,
        examples: &[
            Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
            Example {
                name: "sleep variable duration",
                fence_meta: None,
                code: indoc! {r#"
                # Durations resolve at runtime, so variables work too:
                # quoted or bare, both bind the same string.
                LET $pause: STRING = "100ms"
                SLEEP $pause

                LET $bare: STRING = 100ms
                SLEEP $bare
            "#},
            },
        ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let raw = it
                .next()
                .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
            if it.next().is_some() {
                return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
            }
            // Static literals were Duration-checked by the central
            // validator; dynamics ($var, templates) resolve at runtime.
            Ok(StepKind::Sleep { duration: raw })
        },
    ],

    ListAppend => [
        name: "LIST_APPEND",
        variant: ListAppend { list: String, item: Arg },
        syntax: "LIST_APPEND $list <item>",
        summary: "Append an item to a LIST variable in place.",
        description: indoc! {r#"
            Appends the item to the LIST variable in place.

            When the binding holds the only reference the push runs in
            amortized constant time. Aliased buffers detach first, so
            other holders keep their contents.
        "#},
        args: &[
            ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
            ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
        ],
        flags: &[],
        default_output: None,
        examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
            # Appends accumulate in order.
            LET $items: LIST<STRING> = []
            LIST_APPEND $items "first"
            LIST_APPEND $items "second"

            LET $want: LIST<STRING> = ["first", "second"]
            ASSERT_EQ $items $want
        "#} } ],
        lower: |_flags, args| {
            let mut it = args.into_iter();
            let raw_list = it
                .next()
                .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
            let list = match raw_list {
                Arg::Expr(Expr::Var(name)) => name,
                Arg::String(s, _) => s.trim_start_matches('$').to_string(),
                other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
            };
            if list.is_empty() {
                return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
            }
            let item = it
                .next()
                .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires an item to append (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
            if it.next().is_some() {
                return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
            }
            Ok(StepKind::ListAppend { list, item })
        },
    ],
}

// ── Structural metadata ──────────────────────────────────────────────────
// Single source of truth for structural-statement documentation (TIMEOUT,
// ASYNC, AWAIT, WITH_IO, IF, FOR, ...). These constructs are parsed by PEG
// rules rather than `declare_commands!`, so their reference docs live here
// instead of `crates/docs-gen/src/command_ref.rs` : adding a structural
// StepKind without registering it here fails `structural_metadata_covers_all_structural_kinds`
// below, and oxdock-render renders these entries dynamically (no hardcoded copy).
pub fn all_structural_metadata() -> Vec<CommandMeta> {
    vec![
        CommandMeta {
            in_index: true,
            name: "WITH_IO",
            syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
            summary: "Reroute standard streams.",
            description: indoc! {r#"
                Reroutes the standard streams of the next command or, in block form,
                of every enclosed command.

                Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
                variable (`stdout=$p`, `stdin=$p`), resolved from the variable
                when the step runs. Both stdout and stderr pipes capture output
                the same way. Declare the handle first with `LET $p: PIPE`.

                A `RUN` step can opt into a pseudo-terminal with the bare `tty`
                flag instead of a new command: `WITH_IO [tty] RUN [...]`
                spawns the child under a pty sized from the host terminal
                when it names none (24x80 fallback off-terminal;
                `rows = <int>` / `cols = <int>` override each side).
                Unnamed sides track the host window while the step runs
                (signal-driven on Unix, polled where no window signal
                exists); explicit sides stay pinned.

                The master carries the child's interleaved stdout and stderr
                as one stream, so it routes exclusively to `stdout` (step
                capture or a `stdout = $p` pipe): `stderr` bindings alongside
                `tty` are rejected, and `tty` outside a `RUN` step is
                rejected. Pty-backed descriptors never promote to OS
                kernel pipes, even inside `ASYNC` single-`RUN` bodies.

                `stdin = $p` feeds the master; bare `[tty]`
                with a real terminal stdin feeds host keys the same
                way (raw, transparent) and stays closed headless. Host
                interrupt keys reach the child instead of cancelling the
                step, so bind a step `TIMEOUT` for a guaranteed exit.

                Expect pty translation in assertions:
                newlines arrive as carriage return plus newline, and prompts
                echo input. On Windows, lone line feeds in fed input expand
                to carriage-return line feeds for console submission, so
                portable scripts need no per-platform line endings.

                An input pipe that EOFs contributes a
                terminal-echoed end-of-transmission marker on some
                platforms: prefer `ASSERT_CONTAINS` over byte-exact
                assertions on fed sessions.

                Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
                producer can finish before the consumer starts.

                If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
                not, the pipe is a zero copy OS kernel pipe instead: pair it with a
                consumer that runs while the producer is alive, since output past the
                64 KiB kernel buffer stalls until drained. That promotion never crosses
                a function boundary: pipes created, bound, or passed by variable inside FUNC
                bodies are always script pipes, even when the surrounding task would
                otherwise promote.

                A second producer or consumer on a live handle is an explicit
                error. A handle bound as output can later feed another
                command's `stdin`, connecting commands without touching the
                terminal. Binding `stdout` and `stderr` to the same live
                handle fails deterministically. Merge streams in shell
                via `2>&1` instead.

                Nested blocks stack defaults; inline bindings override inherited ones for
                their command only; closing a block restores previous wiring.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "with_io block",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $log: PIPE
                WITH_IO [stdout=$log] {
                  ECHO first
                  ECHO second
                }
                WITH_IO [stdin=$log] WRITE captured.txt

                # The piped bytes landed in the file.
                LET $body: STRING = READ captured.txt
                ASSERT_CONTAINS $body "first"
                ASSERT_CONTAINS $body "second"
            "#},
                },
                Example {
                    name: "variable pipe binding",
                    fence_meta: None,
                    code: indoc! {r#"
                # Declare the pipe first: `LET $p: PIPE` mints a fresh
                # backend without touching a stream. A plain string here
                # would be a TypeMismatch.
                LET $p: PIPE
                WITH_IO [stdout=$p] ECHO hello
                WITH_IO [stdin=$p] READ_LINE $line
                ASSERT_EQ $line "hello"
            "#},
                },
                Example {
                    name: "pty terminal binding",
                    fence_meta: None,
                    code: indoc! {r#"
                # A RUN step under bare `tty` sees a terminal: newlines
                # arrive translated, so assert with CONTAINS, never EQ.
                LET $p: PIPE
                WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
                WITH_IO [stdin=$p] READ_LINE $line
                ASSERT_CONTAINS $line "hello-tty"
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "FOR",
            syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
            summary: "Iterate over a list or map.",
            description: indoc! {r#"
                The loop variable receives each element (lists) or value (maps); with
                two variables, the first receives the key.

                Loop variables are declared with explicit types and scoped per iteration;
                they do not leak outward. The body may be a braced block
                or a single-line `{ ... }` command.

                `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
                `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
                empty when nothing matches, and rejects `..` escapes.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "for loop",
                    fence_meta: None,
                    code: indoc! {r#"
                # Each element binds in turn; the loop body sees every one.
                LET $items: LIST<STRING> = ["a", "b"]
                FOR $item: STRING IN $items {
                  ECHO $item
                }
                ASSERT_CONTAINS stdout "a"
                ASSERT_CONTAINS stdout "b"

                # Key and value bind together for maps.
                LET $map: MAP<x: INT> = {"x": 1}
                FOR $k: STRING, $v: INT IN $map {
                  ECHO "{{ $k }}={{ $v }}"
                }
                ASSERT_CONTAINS stdout "x=1"
            "#},
                },
                Example {
                    name: "expand every match",
                    fence_meta: None,
                    code: indoc! {r#"
                # Single-line body; $x is a template path, WHO an override.
                IMPORT [STD]
                WRITE a.txt "hi \{{ env:WHO }}!"
                FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }

                ASSERT_CONTAINS stdout "hi World!"
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "IF",
            syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
            summary: "Conditional execution.",
            description: indoc! {r#"
                The condition is evaluated as a boolean expression.

                Prefix `!` negates (`IF !false`); `&&` binds tighter than
                `||`, and both short-circuit, so `IF true || $missing`
                never evaluates the right side. Only Bool values are
                accepted as conditions.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "if else",
                    fence_meta: None,
                    code: indoc! {r#"
                IMPORT [STD]

                # True branch runs; the false branch is skipped.
                IF true {
                  WRITE yes.txt taken
                } ELSE {
                  WRITE yes.txt skipped
                }

                # ELSE IF selects the first true branch.
                IF false {
                  WRITE skipped.txt no
                } ELSE IF true {
                  WRITE fallback.txt taken
                }

                # !false evaluates to true, so this branch runs.
                IF !false {
                  WRITE negated.txt taken
                }

                LET $yes_body: STRING = READ yes.txt
                LET $fallback_body: STRING = READ fallback.txt
                LET $negated_body: STRING = READ negated.txt
                ASSERT_EQ $yes_body "taken"
                ASSERT_EQ $fallback_body "taken"
                ASSERT_EQ $negated_body "taken"
                LET $t: STRING = PATH_TYPE("skipped.txt")
                ASSERT_EQ $t "absent"
            "#},
                },
                Example {
                    name: "logical condition combination",
                    fence_meta: None,
                    code: indoc! {r#"
                IMPORT [STD]
                LET $role: STRING = "admin"
                LET $level: INT = 3

                # || is true when either side holds; && needs both.
                IF $role == "owner" || $level >= 5 {
                    WRITE unexpected.txt no
                } ELSE {
                    WRITE fallback.txt or-false
                }

                LET $fb: STRING = READ fallback.txt
                ASSERT_EQ $fb "or-false"
                LET $t1: STRING = PATH_TYPE("unexpected.txt")
                ASSERT_EQ $t1 "absent"

                IF $role == "admin" || $level >= 5 {
                    WRITE chosen.txt or-true
                }

                LET $ch: STRING = READ chosen.txt
                ASSERT_EQ $ch "or-true"

                IF $role == "admin" && $level >= 5 {
                    WRITE unexpected-too.txt no
                } ELSE {
                    WRITE and.txt and-false
                }

                LET $an: STRING = READ and.txt
                ASSERT_EQ $an "and-false"
                LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
                ASSERT_EQ $t2 "absent"
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "LET",
            syntax: "LET $var: TYPE = <expr> | LET $p: PIPE | LET $var: TYPE = ASYNC { <commands> } | LET $var: TYPE = <command> | LET $var: TYPE = AWAIT $task | LET $var: TYPE = { <commands> }",
            summary: "Bind script-local variables.",
            description: indoc! {r#"
                Declares a script-local variable with an explicit type (STRING, INT,
                FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
                in the same scope frame is a redeclaration error; mutate with
                `$var = <expr>`.

                Variables are usable in templates (`{{ $var }}`), guards, and
                expressions. With `ASYNC`, spawns a background task and stores its
                handle (see ASYNC). The `$` sigil on the name is mandatory.

                No hoisting: a variable exists only after its LET runs, in
                execution order. Reading `$var` before its LET (or after the
                block that declared it exits) fails with
                `undefined variable $var`. Scopes are a stack of frames and
                resolution walks innermost outward, so nothing pre-declares
                names. Function bodies read outer variables through the same
                walk, but their own LETs never leak out (see FUNC).

                The right-hand side is always an expression — literals, lists, maps,
                arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
                parentheses), comparisons (`< <= > >=` binding tighter than
                `== !=`), logical `&&` (tighter) and `||` with short-circuit,
                `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
                `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
                `{{ ... }}` template; interpolation happens in string values,
                not here.
                The one exception is pipes: `LET $p: PIPE` with no `=`
                and no initializer mints a fresh anonymous backend,
                lazily materialized at first binding, so two declarations
                never share a channel.

                Numbers are numeric literals: `42` binds `INT`, `3.14` binds
                `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
                so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
                Division by zero, overflow, and non-finite results are errors.
                Both numeric sides compare numerically (`1 == 1.0` is true);
                otherwise `==`/`!=` compare rendered strings and ordering on
                non-numerics is a Type Error. Constant subtrees fold at parse
                time and dynamic arithmetic compiles to flat RPN with
                identical semantics.

                Float equality is exact with no epsilon. Floats store decimals
                in binary, so a value is exact only when its reduced fraction
                has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
                (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
                repeat forever in binary (like 1/3 in decimal) and truncate,
                so `0.1 + 0.2 == 0.3` is false (the sum is
                `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
                .125, .625, .875 are exact; .1, .2, .3 and similar are
                approximations. Bound approximations instead of comparing
                them: `IF $sum > 0.299999 && $sum < 0.300001`.

                Comparisons do not chain: `a < b < c` is a parse error, not
                `(a < b) < c`. Chaining would compare a `BOOL` against a
                number (a runtime Type Error in C-style parsing) or evaluate
                the middle term twice (Python-style chaining), so the grammar
                accepts exactly one comparison operator per level. Write the
                conjunction explicitly: `$a < $b && $b < $c`. The same holds
                for equality (`$a == $b == $c` is rejected).

                Captured command output is a string, so convert before math:
                `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
                whitespace; `FLOAT` accepts int strings and rejects
                non-finite).

                Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
                as quoted.

                When the right-hand side is a synchronous command
                (`LET $out: STRING = ECHO hi`), the command runs to completion and its
                exact stdout bytes are captured into the variable as a string (no newline
                stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
                an error). Combining capture with an explicit
                `WITH_IO [stdout=$var]` is a parse error.

                Coming from Bash, the capture line looks familiar but behaves
                strictly:

                | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
                | --- | --- | --- |
                | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
                | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
                | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
                | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |

                `LET $out: TYPE = AWAIT $var` binds the background task's
                explicit `RETURN` value instead (tasks stream their stdout
                live, so there is no output left to capture); a task that
                succeeded without `RETURN` yields `INT` 0, like a process
                exit status.

                An inline block (`LET $var: TYPE = { <commands> }`) runs its
                steps in a fresh scope and binds the nearest `RETURN` value,
                like a zero-arg function body: fallthrough without `RETURN`
                binds `""`, and `BREAK`/`CONTINUE` escaping the block are
                errors. Think IIFE: the block executes immediately where it
                stands and its value is the result. The block reads outer
                variables but its own LETs never leak out. A `{k: v}` shape
                still parses as a map literal; anything else in braces is
                a block.

                The split is deliberate: synchronous commands capture
                stdout because they run inline to completion on the same
                thread; background tasks never capture stdout because
                concurrent output has no well-defined value. Task results
                travel only through `RETURN` (or `INT` 0 for void tasks).

                `LET $e: STRING = env:FOO` reads the script environment into a plain
                string.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "let",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $name: STRING = "world"
                ECHO "hello, {{ $name }}"
                ASSERT_CONTAINS stdout "hello, world"

                LET $items: LIST<STRING> = ["a", "b"]
                ASSERT_CONTAINS $items "a"
                ASSERT_CONTAINS $items "b"

                LET $count: INT = 42
                ASSERT_EQ $count 42
            "#},
                },
                Example {
                    name: "bool coercion",
                    fence_meta: None,
                    code: indoc! {r#"
                # BOOL spellings coerce case-insensitively. Empty is
                # not a boolean: absent flags state a default through
                # BOOL_OR instead of converting here.
                LET $t: BOOL = "TRUE"
                ASSERT_EQ $t true
                LET $f: BOOL = "no"
                ASSERT_EQ $f false
            "#},
                },
                Example {
                    name: "bool coercion rejects empty",
                    fence_meta: Some("expect_error:\"expected BOOL\""),
                    code: indoc! {r#"
                # Empty never reads as false: an empty string fails
                # BOOL coercion instead of picking a polarity.
                ENV EMPTY_FLAG=""
                LET $e: BOOL = "{{ env:EMPTY_FLAG }}"
            "#},
                },
                Example {
                    name: "no hoisting",
                    fence_meta: Some("expect_error:\"undefined variable\""),
                    code: indoc! {r#"
                # Reading before the LET runs is an error, not an empty value.
                ECHO $too_early
                LET $too_early: STRING = "too late"
            "#},
                },
                Example {
                    name: "glob binding",
                    fence_meta: None,
                    code: indoc! {r#"
                # The RHS is an expression: GLOB(...) runs and binds a list.
                IMPORT [STD]
                WRITE a.txt "x"
                LET $files: LIST<STRING> = GLOB("*.txt")
                FOR $f: STRING IN $files { ECHO $f }

                ASSERT_CONTAINS stdout "a.txt"
            "#},
                },
                Example {
                    name: "scoped variable reverts",
                    fence_meta: None,
                    code: indoc! {r#"
                # LET inside a braced block reverts when the block exits.
                LET $a: STRING = "outer"

                [bool:true] {
                    LET $a: STRING = "inner"
                    WRITE inner.txt "{{ $a }}"
                }

                WRITE outer.txt "{{ $a }}"

                LET $in_body: STRING = READ inner.txt
                ASSERT_EQ $in_body "inner"

                LET $out_body: STRING = READ outer.txt
                ASSERT_EQ $out_body "outer"
            "#},
                },
                Example {
                    name: "capture command output",
                    fence_meta: None,
                    code: indoc! {r#"
                # Capture keeps the trailing newline.
                LET $out: STRING = ECHO hi
                ASSERT_EQ $out "hi\n"
            "#},
                },
                Example {
                    name: "inline block",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $who: STRING = "ada"

                # An inline block binds its RETURN value like a function body.
                LET $res: STRING = {
                    LET $loud: STRING = "{{ $who }}!"
                    RETURN $loud
                }
                ASSERT_EQ $res "ada!"

                # Any declared type works: the block value checks like any RHS.
                LET $n: INT = {
                    RETURN 40 + 2
                }
                ASSERT_EQ $n 42
            "#},
                },
                Example {
                    name: "arithmetic over captured output",
                    fence_meta: None,
                    code: indoc! {r#"
                # Captured output converts explicitly: INT() then arithmetic.
                IMPORT [STD]
                LET $size_str: STRING = ECHO 41
                LET $total: INT = INT($size_str) + 1
                ASSERT_EQ $total 42

                # FLOAT() promotes instead of truncating.
                LET $ratio: FLOAT = 1 + 2.5
                ASSERT_EQ $ratio 3.5

                # Int x Int stays INT: integer division truncates.
                LET $half: INT = 7 / 2
                ASSERT_EQ $half 3
            "#},
                },
                Example {
                    name: "float equality is exact",
                    fence_meta: None,
                    code: indoc! {r#"
                # Binary fractions compare cleanly; decimal fractions may not:
                # 0.1 + 0.2 is 0.30000000000000004, so == is false.
                IMPORT [STD]
                LET $exact: BOOL = 0.5 + 0.25 == 0.75
                LET $decimal: BOOL = 0.1 + 0.2 == 0.3
                IF $exact {
                    WRITE exact.txt yes
                }
                IF $decimal {
                    WRITE unexpected.txt no
                }

                LET $ok: STRING = READ exact.txt
                ASSERT_EQ $ok "yes"

                LET $t: STRING = PATH_TYPE("unexpected.txt")
                ASSERT_EQ $t "absent"
            "#},
                },
                Example {
                    name: "bound inexact decimals",
                    fence_meta: None,
                    code: indoc! {r#"
                # Never test inexact decimals for equality; bound them.
                LET $sum: FLOAT = 0.1 + 0.2
                IF $sum > 0.299999 && $sum < 0.300001 {
                    WRITE bounded.txt yes
                }

                LET $ok: STRING = READ bounded.txt
                ASSERT_EQ $ok "yes"
            "#},
                },
                Example {
                    name: "inspect a variable",
                    fence_meta: None,
                    code: indoc! {r#"
                # INSPECT($var) snapshots a variable into a MAP: declared
                # type plus live details (pipe backend stats here), so
                # scripts can branch on engine state.
                IMPORT [STD]
                LET $p: PIPE
                WITH_IO [stdout=$p] ECHO hello
                LET $info: MAP<ANY> = INSPECT($p)
                IF $info.is_os_pipe {
                    WRITE unexpected.txt "should be a script pipe"
                }

                ASSERT_EQ $info.type "PIPE"
                LET $t: STRING = PATH_TYPE("unexpected.txt")
                ASSERT_EQ $t "absent"
            "#},
                },
            ],
        },
        CommandMeta {
            // `MUTATION` is not an actual keyword, so don't index it as such.
            in_index: false,
            name: "MUTATION",
            syntax: "$var = <expr>",
            summary: "Mutate a declared variable.",
            description: indoc! {r#"
                Reassigns an existing variable, converting the new value to
                the type declared at LET time through the same narrow
                coercion pairs as declaration. Strings never parse to
                numbers implicitly: `$n = "42"` is a TypeMismatch for an
                INT, write `$n = INT("42")` instead.
                Expressions never convert: `"100" + 1` is a Type Error, use
                `INT()` / `FLOAT()` to cross that boundary explicitly.

                The leading `$` distinguishes mutation from `KEY=value` command
                assignments. Assigning an undeclared variable or a mismatched type is
                an error.

                Mutation writes through to the scope where the variable was
                declared, so it survives block exit: `LET $x` outside a block
                followed by `$x = ...` inside still reads back the new value
                afterwards, for every type. This is the counterpart to LET
                shadowing, where `LET $x` *inside* the block declares a
                separate inner variable that reverts on exit.

                Reassignment rebinds the variable to a new value: values
                captured earlier keep the old word (see the rebinding
                example below).
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "mutate",
                    fence_meta: None,
                    code: indoc! {r#"
                # Mutation writes through: the binding holds the new value.
                LET $count: INT = 1
                $count = 2
                ASSERT_EQ $count 2
            "#},
                },
                Example {
                    name: "rebind keeps earlier captures",
                    fence_meta: None,
                    code: indoc! {r#"
                # Reassignment rebinds: a map built from `$s` still
                # reads the original string after `$s` moves on.
                LET $s: STRING = "test"
                LET $m: MAP<ANY> = {a: $s}
                $s = "changed"
                ASSERT_EQ $m.a "test"

                # Appending to one list binding never touches its clones.
                LET $a: LIST<STRING> = ["1"]
                LET $b: LIST<STRING> = $a
                LIST_APPEND $a "2"
                LET $want: LIST<STRING> = ["1"]
                ASSERT_EQ $b $want
            "#},
                },
                Example {
                    name: "convert before math",
                    fence_meta: None,
                    code: indoc! {r#"
                # Captured output is a string: `"100" + 1` is a Type Error.
                # Convert explicitly, then mutate with arithmetic.
                IMPORT [STD]
                LET $raw: STRING = ECHO 100
                LET $n: INT = INT($raw)
                $n = $n + 1

                # The declared slot stays strict: strings parse only
                # through the explicit converter, never on assignment.
                $n = INT("42")
                ASSERT_EQ $n 42

                # Same crossing for decimals via FLOAT().
                LET $frac_str: STRING = ECHO 2.5
                LET $f: FLOAT = FLOAT($frac_str) + 0.25
                ASSERT_EQ $f 2.75
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "ASYNC",
            syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }",
            summary: "Run steps in a background thread.",
            description: indoc! {r#"
                Runs a command or block of commands in a background thread with
                subshell isolation.

                Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
                task handle for `AWAIT`. Task output streams live to the parent
                stdout; a task publishes a value with an explicit `RETURN`,
                which `LET $out: TYPE = AWAIT $task` binds.

                `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
                then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
                the main thread before the worker spawns. Placing `WITH_IO` directly
                inside `ASYNC` is rejected at parse time.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "async",
                    fence_meta: None,
                    code: indoc! {r#"
                # Inline and block forms both run in the background; AWAIT joins them.
                ASYNC ECHO "warming-up"
                LET $a: HANDLE<VOID> = ASYNC ECHO "first"
                LET $b: HANDLE<VOID> = ASYNC {
                    ECHO "second"
                }
                AWAIT $a
                AWAIT $b
                ASSERT_CONTAINS stdout "first"
                ASSERT_CONTAINS stdout "second"
                "#},
                },
                Example {
                    name: "async task handle",
                    fence_meta: None,
                    code: indoc! {r#"
                    LET $task: HANDLE<VOID> = ASYNC {
                        ECHO "built"
                    }
                    AWAIT $task
                    ASSERT_CONTAINS stdout "built"
                "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "AWAIT",
            syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
            summary: "Join a background task.",
            description: indoc! {r#"
                Blocks until the named task completes. Propagates errors if the task failed.

                Task output streams live during the run; joining binds nothing by
                itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
                `RETURN` value instead, or `INT` 0 when the task succeeded
                without one (add `RETURN <expr>` to the task body to yield
                a value).
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "await",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $task: HANDLE<VOID> = ASYNC ECHO "done"
                AWAIT $task
                ASSERT_CONTAINS stdout "done"
            "#},
                },
                Example {
                    name: "await capture",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $task: HANDLE<STRING> = ASYNC {
                    ECHO "logged"
                    RETURN "returned"
                }

                # AWAIT binds the RETURN value, not the streamed output.
                LET $out: STRING = AWAIT $task
                ASSERT_EQ $out "returned"
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "CANCEL",
            syntax: "CANCEL $var",
            summary: "Synchronously cancel a background task.",
            description: indoc! {r#"
                Kills the named background task spawned via `LET $var: HANDLE<T> = ASYNC ...`.

                Blocking: returns only after the task thread has been joined and its OS
                process reaped, so no residual filesystem or stream mutation follows. A
                later AWAIT $var reports cancellation. Only named tasks can be cancelled.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "cancel",
                    fence_meta: None,
                    code: indoc! {r#"
                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
                CANCEL $task
            "#},
                },
                Example {
                    name: "await after cancel reports cancellation",
                    fence_meta: Some("expect_error:\"was cancelled\""),
                    code: indoc! {r#"
                # A cancelled task stays cancelled: joining it reports.
                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
                CANCEL $task
                AWAIT $task
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "TIMEOUT",
            syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
            summary: "Enforce an execution deadline.",
            description: indoc! {r#"
                Aborts the wrapped step or block with a deadline error if it exceeds the
                duration (e.g. 500ms, 10s, 2m; a bare number means seconds).

                A blocking foreground process is killed.

                ASYNC nests in either order with order-dependent deadline
                semantics: `LET $task: HANDLE<VOID> = ASYNC TIMEOUT 30s RUN "build"` enforces
                the deadline inside the background thread (a later `AWAIT $task`
                surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
                preempts a hung task from the awaiting side.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "timeout",
                    fence_meta: None,
                    code: indoc! {r#"
                    TIMEOUT 30s WRITE heartbeat.txt alive
                    LET $beat: STRING = READ heartbeat.txt
                    ASSERT_EQ $beat "alive"
                "#},
                },
                Example {
                    name: "timeout block",
                    fence_meta: None,
                    code: indoc! {r#"
                    TIMEOUT 30s {
                        WRITE a.txt one
                        WRITE b.txt two
                    }
                    LET $a: STRING = READ a.txt
                    LET $b: STRING = READ b.txt
                    ASSERT_EQ $a "one"
                    ASSERT_EQ $b "two"
                "#},
                },
                Example {
                    name: "deadline aborts the step",
                    fence_meta: Some("expect_error:\"TIMEOUT after\""),
                    code: indoc! {r#"
                    # 50ms expires long before the sleep does: the step dies
                    # with a deadline error instead of running out the clock.
                    TIMEOUT 50ms SLEEP 30s
                "#},
                },
                Example {
                    name: "timeout variable duration",
                    fence_meta: None,
                    code: indoc! {r#"
                    # Durations resolve at runtime, so variables work too.
                    LET $budget: DURATION = "30s"
                    TIMEOUT $budget WRITE heartbeat.txt alive

                    LET $beat: STRING = READ heartbeat.txt
                    ASSERT_EQ $beat "alive"
                "#},
                },
                Example {
                    name: "timeout await",
                    fence_meta: None,
                    code: indoc! {r#"
                    # AWAIT form bounds a task join instead of a step.
                    LET $quick: HANDLE<VOID> = ASYNC {
                        ECHO hi
                    }
                    TIMEOUT 30s AWAIT $quick
                "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "ISOLATED",
            syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
            summary: "Run steps with the seeded script environment.",
            description: indoc! {r#"
                Resets the script environment for the block to the session
                seed: spawned children see the sandbox defaults plus names
                the block re-adds through its leading `INHERIT_ENV`.

                The allowlist resolves against the outer scope, never the
                host. Absent names stay absent silently, matching top-level
                `INHERIT_ENV`.

                Script variables, pipes, and files flow through untouched;
                only `env:` is reset. Files share the session workspace:
                blocks selecting the same `WORKSPACE` target resolve to the
                same directory with no per-block overlay, so one block's
                writes are visible to another.

                Blocks nest (each level re-seeds from the same seed, so
                nesting only narrows through the allowlists) and combine
                with `ASYNC` and `FUNC`. Scope exit restores the prior
                environment.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "isolated scope",
                    fence_meta: None,
                    code: indoc! {r#"
                    # The block sees a clean env; plain steps still run and
                    # outer bindings survive untouched.
                    ENV MODE=outer
                    ISOLATED {
                        ENV MODE=inner
                        WRITE inner.txt "{{ env:MODE }}"
                    }
                    LET $back: STRING = "{{ env:MODE }}"
                    ASSERT_EQ $back "outer"
                    LET $body: STRING = READ inner.txt
                    ASSERT_EQ $body "inner"
                "#},
                },
                Example {
                    name: "reseeded child env",
                    fence_meta: None,
                    code: indoc! {r#"
                    # The block resets to the session seed: plain steps and
                    # spawns run with zero prelude. PATH needs no
                    # declaration: contract seed rows are always admitted.
                    WRITE top-path.txt "{{ env:PATH }}"
                    ISOLATED {
                        WRITE inner-path.txt "{{ env:PATH }}"
                        RUN "echo seed-ok"
                    }
                    LET $top: STRING = READ top-path.txt
                    LET $inner: STRING = READ inner-path.txt
                    ASSERT_EQ $inner $top
                    ASSERT_CONTAINS stdout "seed-ok"
                "#},
                },
                Example {
                    name: "outer customs stay out",
                    fence_meta: Some("expect_error:\"env:OUTER_CUSTOM\""),
                    code: indoc! {r#"
                    # Outer customs never enter the block: without an
                    # allowlist entry the static gate rejects the read
                    # before the first step runs.
                    ENV OUTER_CUSTOM=outer-val
                    ISOLATED {
                        WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
                    }
                "#},
                },
                Example {
                    name: "absent names stay absent",
                    fence_meta: None,
                    code: indoc! {r#"
                    # Listing a name the outer scope lacks is not an error:
                    # the block simply runs without it.
                    ISOLATED {
                        INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
                        ECHO still-runs
                    }
                    ASSERT_CONTAINS stdout "still-runs"
                "#},
                },
                Example {
                    name: "nesting narrows",
                    fence_meta: None,
                    code: indoc! {r#"
                    # Each level snapshots the already-scrubbed parent, so
                    # an inner block cannot recover what the outer dropped.
                    ENV KEEP=yes
                    ISOLATED {
                        INHERIT_ENV [KEEP]
                        ISOLATED {
                            ENV KEEP=inner
                            WRITE deep.txt "{{ env:KEEP }}"
                        }
                        LET $mid: STRING = "{{ env:KEEP }}"
                        ASSERT_EQ $mid "yes"
                    }
                    LET $deep: STRING = READ deep.txt
                    ASSERT_EQ $deep "inner"
                "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "REMOTE",
            syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
            summary: "Run a sealed block on a remote target.",
            description: indoc! {r#"
                Runs the braced block on the named remote target, which the
                host binds at startup (`--remote`). The block is sealed:
                only header-listed `$var` and `env:NAME` entries cross, the
                guest starts empty, and results return through declared
                transfers or `WITH_IO` pipes.

                The target is a static literal, never a variable. Unknown
                targets fail before execution starts.

                Bodies check twice: the host static pass validates the
                body before anything ships, and the guest re-validates on
                arrival through the same entry point, so a body type error
                fails locally, never mid-run on the remote.

                A failing guest fails the host step: EXIT in the body
                exits the guest, and the host relays the code to its own
                process exit status (see EXIT).
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "sealed header values cross, outer scope does not",
                    fence_meta: Some("mock_remote:prod"),
                    code: indoc! {r#"
                    # Only header-listed names arrive: `$version` is visible
                    # on the guest, `$secret` was never sent.
                    LET $version: STRING = "1.2.3"
                    LET $secret: STRING = "host-only"
                    REMOTE prod [$version] {
                        WRITE version.txt "{{ $version }}"
                        COPY --to-host ./version.txt back.txt
                    }

                    # The pushed file proves the guest saw the injected value.
                    LET $back: STRING = READ back.txt
                    ASSERT_EQ $back "1.2.3"
                "#},
                },
                Example {
                    name: "background tasks stream through shared pipes",
                    fence_meta: Some("mock_remote:prod"),
                    code: indoc! {r#"
                    # Two background REMOTEs share one capture pipe while a
                    # WITH_IO block holds the write end open.
                    IMPORT [STD]
                    LET $cap: PIPE
                    WITH_IO [stdout=$cap] {
                        LET $a: HANDLE<VOID> = ASYNC REMOTE prod {
                            ECHO "from-a"
                        }
                        LET $b: HANDLE<VOID> = ASYNC REMOTE prod {
                            ECHO "from-b"
                        }
                        AWAIT $a
                        AWAIT $b
                    }

                    # EOF ends the drain: no sentinel line, no baked-in count.
                    LET $n: INT = 0
                    WHILE !EOF($cap) {
                        WITH_IO [stdin=$cap] READ_LINE $line
                        $n = $n + 1
                    }
                    ASSERT_EQ $n 2
                "#},
                },
                Example {
                    name: "declared files cross both directions",
                    fence_meta: Some("mock_remote:prod roots:unified"),
                    code: indoc! {r#"
                    # Fetches ride in, pushes ride back. Anything undeclared
                    # never leaves its side.
                    WRITE send.txt "payload"
                    REMOTE prod {
                        COPY --from-host ./send.txt got.txt
                        LET $v: STRING = READ got.txt
                        ASSERT_EQ $v "payload"
                        WRITE back.txt "returned"
                        COPY --to-host ./back.txt back.txt
                    }

                    # The push landed on the host; guest staging is gone.
                    LET $b: STRING = READ back.txt
                    ASSERT_EQ $b "returned"
                "#},
                },
                Example {
                    name: "guest workspace selection stays on the guest",
                    fence_meta: Some("mock_remote:prod"),
                    code: indoc! {r#"
                    # WORKSPACE switches inside the block resolve against the
                    # guest staging dir, which serves as both the SNAPSHOT
                    # root and the LOCAL build context. The host selection
                    # restores when the block exits.
                    REMOTE prod {
                        WORKSPACE SNAPSHOT
                        WRITE out.txt "from-snapshot"
                        COPY --to-host ./out.txt snap.txt
                    }

                    LET $s: STRING = READ snap.txt
                    ASSERT_EQ $s "from-snapshot"
                "#},
                },
                Example {
                    name: "guest cache persists across execs",
                    fence_meta: Some("mock_remote:prod"),
                    code: indoc! {r#"
                    # WORKSPACE CACHE addresses guest-local persistent
                    # storage: the second block reads what the first wrote,
                    # while the guest staging starts empty every time.
                    REMOTE prod {
                        WORKSPACE CACHE
                        WRITE marker.txt "run-marker"
                    }
                    REMOTE prod {
                        WORKSPACE CACHE
                        LET $m: STRING = READ marker.txt
                        ASSERT_EQ $m "run-marker"
                    }
                "#},
                },
                Example {
                    name: "pushes outside staging fail closed",
                    fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
                    code: indoc! {r#"
                    # WORKSPACE SYSTEM exposes the whole guest machine, but
                    # transfers stay staging scoped: a push source outside
                    # staging fails loudly instead of crossing.
                    REMOTE prod {
                        WORKSPACE SYSTEM
                        COPY --to-host /no/such/file.txt got.txt
                    }
                "#},
                },
                Example {
                    name: "guest exit fails the step, host survives",
                    fence_meta: Some(
                        "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
                    ),
                    code: indoc! {r#"
                    # EXIT in the body exits the guest with code 3. The
                    # host is unaffected: it keeps executing after the
                    # guest is already dead, and the failure surfaces as
                    # a host step error carrying the same code. The CLI
                    # then exits with it, so the guest code reaches the OS.
                    LET $t: HANDLE<VOID> = ASYNC REMOTE prod {
                        EXIT 3
                    }
                    WRITE host-alive.txt "still here"
                    AWAIT $t
                "#},
                },
                Example {
                    name: "remote block without a runner",
                    fence_meta: Some("expect_error:\"has no registered session\""),
                    code: indoc! {r#"
                    # Without a bound session, the block bails instead of
                    # executing anywhere unexpected.
                    REMOTE prod {
                        ECHO "do something on remote"
                    }
                "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "FUNC",
            syntax: "FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }",
            summary: "Define a user function.",
            description: indoc! {r#"
                Defines a user function with UPPERCASE name and explicitly typed
                parameters. `FUNC` runs synchronously; `ASYNC FUNC` is the same
                with a structural guarantee: the declaration must be
                `HANDLE<T>`, so every `RETURN` hands out a task handle.

                Params bind by position, converting each argument to its
                declared parameter type before the body runs.
                A trailing `$name?: TYPE` marks an optional param: callers
                may omit trailing optionals, which fill with zero values
                (`false`, `""`, `0`, `0.0`, `[]`, `{}`) before the body
                binds. A required param after an optional one fails at
                definition, and an optional param with no zero value
                (records with required fields, unions, handles, custom
                types) fails at definition naming the fix: drop the `?`
                or pass the argument explicitly.
                Bodies run in a fresh variable scope; LETs inside do not leak. A nested
                FUNC definition is scoped to its block and reverts on exit. Names share
                one namespace with native and host-registered functions, which a FUNC
                may never shadow.

                Functions resolve like variables: a name is visible from its
                definition line, so recursion works but mutual recursion does
                not (the second name does not exist while the first body
                lowers). Calls name their module (`STD::GLOB(...)`) unless
                imported; see IMPORT.

                Invoke any function with one syntax: `NAME(...)` as a statement
                (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
                the RETURN value (fallthrough without RETURN is a static error unless RET is VOID).

                `ASYNC FUNC` does not spawn on call. The body runs
                synchronously on the caller thread up to its inner `ASYNC`
                step, which spawns the background task and yields its handle
                immediately; the function then hands that handle out with
                `RETURN $t`. The caller joins it separately with `AWAIT`.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "func def call",
                    fence_meta: None,
                    code: indoc! {r#"
                FUNC GREET($name: STRING): STRING {
                  RETURN $name
                }

                LET $res: STRING = GREET("ada")
                ASSERT_EQ $res "ada"

                # Statement form: parens stay, the value drops.
                GREET("bex")
            "#},
                },
                Example {
                    name: "bind then interpolate",
                    fence_meta: None,
                    code: indoc! {r#"
                # Script FUNCs run as steps, never inside {{ }}.
                FUNC GREET($name: STRING): STRING {
                  RETURN $name
                }

                # Call as a step to capture the RETURN.
                LET $res: STRING = GREET("ada")

                # {{ }} reads the bound var.
                LET $msg: STRING = "says {{ $res }}"

                ASSERT_EQ $msg "says ada"
            "#},
                },
                Example {
                    name: "script funcs never resolve in placeholders",
                    fence_meta: Some(
                        "expect_error:\"placeholder function 'SCRIPT::GREET' is a script function\"",
                    ),
                    code: indoc! {r#"
                # Placeholders carry no step context: pure registry only.
                FUNC GREET($name: STRING): STRING {
                  RETURN $name
                }

                # Bind the argument as a step var to keep quoting flat.
                LET $who: STRING = "ada"

                # This fails naming the pure-only boundary.
                ECHO "{{ SCRIPT::GREET($who) }}"
            "#},
                },
                Example {
                    name: "optional params fill zero values",
                    fence_meta: None,
                    code: indoc! {r#"
                IMPORT [STD]
                # Trailing `?` params may be omitted; they fill with
                # zero values (false, empty map) before the body binds,
                # so plain IF works on an omitted BOOL.
                FUNC ENSURE($check?: BOOL, $opts?: MAP<mode?: STRING>): STRING {
                    IF $check {
                        RETURN "checked"
                    }
                    IF HAS_KEY($opts, "mode") {
                        RETURN "opts"
                    }
                    RETURN "plain"
                }
                LET $a: STRING = ENSURE()
                ASSERT_EQ $a "plain"
                LET $b: STRING = ENSURE(true)
                ASSERT_EQ $b "checked"
                LET $opts: MAP<mode?: STRING> = PARSE_JSON("{\"mode\": \"fast\"}")
                LET $c: STRING = ENSURE(false, $opts)
                ASSERT_EQ $c "opts"
            "#},
                },
                Example {
                    name: "optional params must trail",
                    fence_meta: Some("expect_error:\"optional ? params must be trailing\""),
                    code: indoc! {r#"
                # A required param after an optional one fails at definition.
                FUNC BAD($a?: STRING, $b: STRING): STRING {
                    RETURN $b
                }
            "#},
                },
                Example {
                    name: "async func is a handle guarantee",
                    fence_meta: None,
                    code: indoc! {r#"
                # Side by side: identical bodies, identical handling. The
                # ASYNC marker only guarantees the HANDLE declaration.
                ASYNC FUNC FETCH(): HANDLE<STRING> {
                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
                  RETURN $t
                }
                FUNC MAKE(): HANDLE<STRING> {
                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
                  RETURN $t
                }

                # Both run synchronously to RETURN; the inner ASYNC spawns.
                LET $a: HANDLE<STRING> = FETCH()
                LET $b: HANDLE<STRING> = MAKE()
                LET $x: STRING = AWAIT $a
                LET $y: STRING = AWAIT $b
                ASSERT_EQ $x "hi"
                ASSERT_EQ $y "hi"
            "#},
                },
                Example {
                    name: "call with pipes",
                    fence_meta: None,
                    code: indoc! {r#"
                # A pipe handle travels into a function as a typed argument
                # and is usable as a binding target in both directions.
                # `LET $p: PIPE` mints the handle; `$p` passes it on.
                FUNC DRAIN($q: PIPE): STRING {
                  WITH_IO [stdin=$q] READ_LINE $line
                  RETURN $line
                }

                LET $p: PIPE
                WITH_IO [stdout=$p] ECHO "payload"

                LET $got: STRING = DRAIN($p)
                ASSERT_EQ $got "payload"
            "#},
                },
            ],
        },
        CommandMeta {
            in_index: true,
            name: "RETURN",
            syntax: "RETURN [<expr>]",
            summary: "Return a value from a function, task, or inline block.",
            description: indoc! {r#"
                Ends the nearest enclosing boundary with a value: a function
                call, an `ASYNC` task (bound by `LET $out: STRING = AWAIT $t`), or an
                inline `LET` block. Bare `RETURN` with no expression yields
                `""`.

                Falling off the end without RETURN yields "". RETURN with no
                enclosing boundary (including at top level) is an error; use
                EXIT or ECHO there.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[Example {
                name: "return",
                fence_meta: None,
                code: indoc! {r#"
                FUNC PICK($flag: BOOL): STRING {
                  IF $flag {
                    RETURN "yes"
                  }
                  RETURN "no"
                }

                LET $res: STRING = PICK(true)
                ASSERT_EQ $res "yes"

                # Fallthrough without RETURN yields its own value.
                LET $no: STRING = PICK(false)
                ASSERT_EQ $no "no"
            "#},
            }],
        },
        CommandMeta {
            in_index: true,
            name: "WHILE",
            syntax: "WHILE <bool-expr> { <commands> }",
            summary: "Loop while a condition holds.",
            description: indoc! {r#"
                Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
                non-Bool is a type error).

                Each iteration runs in a fresh scope; mutate outer state with $var = ...
                so the next check observes it. BREAK exits the loop; CONTINUE skips to
                the next check.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[Example {
                name: "while loop",
                fence_meta: None,
                code: indoc! {r#"
                # The condition re-evaluates every iteration: three passes, then stop.
                LET $n: INT = 0
                WHILE $n < 3 {
                  WRITE tick.txt "{{ $n }}"
                  $n = $n + 1
                }

                ASSERT_EQ $n 3
                LET $tick: STRING = READ tick.txt
                ASSERT_EQ $tick "2"
            "#},
            }],
        },
        CommandMeta {
            in_index: true,
            name: "BREAK",
            syntax: "BREAK",
            summary: "Exit the innermost loop.",
            description: indoc! {r#"
                Exits the innermost enclosing FOR or WHILE loop.

                BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[Example {
                name: "break",
                fence_meta: None,
                code: indoc! {r#"
                # BREAK leaves after the first pass: only "a" is written.
                FOR $x: STRING IN ["a", "b"] {
                  WRITE picked.txt "{{ $x }}"
                  BREAK
                }

                LET $body: STRING = READ picked.txt
                ASSERT_EQ $body "a"
            "#},
            }],
        },
        CommandMeta {
            in_index: true,
            name: "CONTINUE",
            syntax: "CONTINUE",
            summary: "Skip to the next loop iteration.",
            description: indoc! {r#"
                Skips the rest of the innermost enclosing FOR or WHILE body and starts
                the next iteration.

                CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[Example {
                name: "continue",
                fence_meta: None,
                code: indoc! {r#"
                # CONTINUE skips the write on "a": only "b" lands.
                FOR $x: STRING IN ["a", "b"] {
                  IF $x == "a" {
                    CONTINUE
                  }
                  WRITE picked.txt "{{ $x }}"
                }

                LET $body: STRING = READ picked.txt
                ASSERT_EQ $body "b"
            "#},
            }],
        },
        CommandMeta {
            in_index: true,
            name: KEYWORD_IMPORT,
            syntax: "IMPORT [<module>, ...] | IMPORT <module> | IMPORT [\"<path>\" AS <ALIAS>] | IMPORT [<module | \"<path>\" AS <ALIAS> | [F, ... FROM (\"<path>\" | <module>) (AS <ALIAS>)?]>, ...]",
            summary: "Bring module functions into bare-call scope; import script files and types.",
            description: indoc! {r#"
                Bare calls:
                - Every call names its module (`STD::GLOB(...)`)
                  unless the module is imported. `IMPORT [STD]` lets
                  the rest of the scope call `GLOB(...)` bare.
                - Calls resolve at parse time: `SCRIPT` definitions
                  first, then imported modules. Unknown modules,
                  unknown functions, and unimported bare calls are
                  parse errors, never runtime surprises.

                Scope:
                - `IMPORT` is a lowering directive, not a step. It
                  applies from its line to the enclosing block exit,
                  then reverts like `LET` scoping, with no runtime
                  footprint. Guards do not apply to it.
                - Two imported modules exporting one name is an
                  ambiguity error: qualify the call instead.

                File imports:
                - Form: `IMPORT ["./lib.oxdock" AS LIB]` (any file
                  extension). The alias is mandatory and becomes the
                  namespace (`LIB::FOO`), with no filename inference.
                - Only `EXPORT`ed top-level `FUNC`s cross the
                  boundary. Unexported means private; variables are
                  never exportable.
                - Types cross qualified: a whole-file import exposes
                  every exported alias as `ALIAS::NAME` only
                  (`LET $p: LIB::PERSON` after
                  `IMPORT ["./lib.oxfile" AS LIB]`), mirroring func
                  views. Nothing bare leaks from an aliased import,
                  so same-named types in different files coexist;
                  harvests below stay the explicit way to request a
                  bare name.
                - Each file initializes once; every alias shares the
                  module's top-level bindings.
                - The file must exist when the run starts. Generated
                  imports are rejected before the first step.

                Mixed brackets:
                - Brackets mix both kinds across lines if needed
                  (`IMPORT [STD, "a.oxdock" AS A]`). Each module entry
                  registers in order; each file entry runs in order.
                - Without an alias a file entry is a parse error.
                - Value positions (`LET`, `ASYNC`,
                  `WITH_IO`/`TIMEOUT` inners) take exactly one file
                  entry and no modules.

                Selective harvests:
                - Form: `IMPORT [FOO FROM "x.oxdock"]`,
                  optionally `AS ALIAS`. Only the named top-level
                  functions register, bare or namespaced under the
                  alias. Harvested names must be `EXPORT`ed.
                - Single name needs no inner brackets
                  (`IMPORT [FOO FROM "x.oxdock"]`); several names from
                  one file combine in one bracket with explicit kinds
                  (`IMPORT [TYPE A, TYPE B FROM "x.oxdock"]`, file or
                  host alike: `IMPORT [FUNC FOO, FUNC BAR FROM
                  "x.oxdock"]`). Bare names always read as modules, so
                  a bare multi-name fails naming the explicit-kind
                  fix. Prefer one import per file over grouping
                  harvests.
                - Types and functions combine in one entry
                  (`IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]`).
                  Harvested types must be `EXPORT TYPE`d. Unaliased
                  harvests persist bare globally (collision-checked),
                  so `FUNC` signatures keep working; aliased harvests
                  persist qualified-only, like whole-file imports.
                - The file body never executes, so harvesting is
                  side-effect free. The file's own nested imports
                  still load. Harvests produce no value and never
                  appear in value positions.

                Host library types:
                - Form: `IMPORT [TYPE PIPE FROM STD]`. The import
                  validates the type resolves globally and records no
                  file. Host types stay global with or without the
                  harvest; the explicit form only documents the
                  dependency and fails fast on typos.
                - Bare `FROM` names a library; quoted `FROM`
                  names a file path. Quoted `FROM "STD"` still parses
                  for backcompat, but bare is preferred.

                Paths:
                - Workspace-side, against the importing file's
                  directory (entry parent at top level; off-workspace
                  entries resolve like stdin against the root).
                - Relative operation paths resolve against the ambient
                  cwd in every file, module or entry alike. `WORKSPACE`
                  and `WORKDIR` mean the same everywhere.
                - Missing files fail before the first step runs.
                  Write-then-import in one script is rejected; check
                  libraries into the tree, or combine them at runtime
                  and run a child interpreter (see the child run
                  examples below).

                Module rules (every file import is a module):
                - Context: never inherits the caller's namespace. Env
                  resets to the seed plus the module init's own
                  contributions (declared `INHERIT_ENV` names re-read
                  from the host on every call). Workspace selection
                  and cwd flow through untouched, so module code
                  observes the same workspace its importer does.
                - Determinism: behavior is a pure function of the
                  script. The same file with the same ambient cwd and
                  selection behaves identically no matter who imports
                  it.
                - State: one init per file, shared by every alias.
                  Top-level `LET` bindings drain into a single store
                  visible to all of the module's functions.
                - Workspace: `WORKSPACE` and `WORKDIR` mean the same
                  in module scope as in entry code, selecting the
                  shared workspace and moving the shared cwd.
                - Exports: only `EXPORT`ed top-level `FUNC`s and
                  `EXPORT TYPE` aliases cross. Variables never cross.
                - Imports: whole-file or harvest, only exported
                  functions and types cross. Stateful harvests are
                  rejected (import the file to share its module).
                  Nested imports load automatically.
                - Cycles: circular imports and depth over 32 fail
                  before the first step runs.

                Exports and tools:
                - `EXPORT` marks top-level `FUNC`s as externally
                  callable (`EXPORT FOO`, `EXPORT [FOO, BAR]`) and as
                  the file importable interface. Re-exports promote
                  an import (`IMPORT ["x.oxdock" AS A]` then `EXPORT
                  A::FOO`).
                - `EXPORT TYPE` marks aliases the same way
                  (`EXPORT TYPE PERSON`, `EXPORT TYPE [A, B]`, mixed
                  `EXPORT [TYPE A, FUNC B]`). Only exported aliases
                  cross, so `FUNC` signatures survive imports.
                - Serving resolves re-exports through the registry;
                  unexported names fail tool setup instead of serving
                  a dead tool. The MCP server skips `TYPE` exports
                  when building tools while still resolving imported
                  types for signatures. Single-file scope otherwise;
                  see the MCP host for consumption.
            "#},
            args: &[],
            flags: &[],
            default_output: None,
            examples: &[
                Example {
                    name: "import",
                    fence_meta: None,
                    code: indoc! {r#"
                # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
                WRITE a.txt "hi \{{ env:WHO }}!"
                IMPORT [STD]
                FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
                ASSERT_CONTAINS stdout "hi World!"
            "#},
                },
                Example {
                    name: "import missing file fails upfront",
                    fence_meta: Some("expect_error:\"must exist when the run starts\""),
                    code: indoc! {r#"
                # Generated imports are rejected: a file that does not
                # exist when the run starts cannot be analyzed, so the
                # import fails before the first step runs.
                WORKSPACE LOCAL
                WRITE lib.oxdock 'FUNC F($x: STRING): STRING { RETURN $x } EXPORT F'
                IMPORT ["lib.oxdock" AS LIB]
            "#},
                },
                Example {
                    name: "import missing alias fails",
                    fence_meta: Some("expect_error:\"mandatory alias\""),
                    code: indoc! {r#"
                # A file entry without AS is a parse error.
                IMPORT ["./lib.oxdock"]
            "#},
                },
                Example {
                    name: "module cannot export a variable",
                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
                    code: indoc! {r#"
                # Only top-level FUNCs are exportable, never variables.
                LET $FOO: STRING = "x"
                EXPORT FOO
            "#},
                },
                Example {
                    name: "import re-export unknown alias fails",
                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
                    code: indoc! {r#"
                # Re-exports name a visible import alias.
                IMPORT ["x.oxdock" AS A]
                EXPORT NOSUCH::FOO
            "#},
                },
                Example {
                    name: "export type aliases",
                    fence_meta: None,
                    code: indoc! {r#"
                # TYPE aliases declare shapes once; EXPORT TYPE shares
                # them so importing files can use the same spelling.
                TYPE PERSON = MAP<name: STRING>

                FUNC GREET($p: PERSON): STRING {
                    RETURN "hi {{ $p.name }}"
                }
                EXPORT GREET
                EXPORT TYPE PERSON

                LET $p: PERSON = {name: "Ada"}
                LET $greeting: STRING = GREET($p)
                ASSERT_EQ $greeting "hi Ada"
            "#},
                },
                Example {
                    name: "import type from library",
                    fence_meta: None,
                    code: indoc! {r#"
                # One bracket mixes entry kinds: STD brings functions bare,
                # each harvest names a type. Types resolve globally with
                # or without the harvests; the explicit form only documents
                # the dependency, so this grouping is example only. Bare
                # FROM names a library; quoted FROM names a file path.
                IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]

                LET $p: PIPE
                WITH_IO [stdout=$p] ECHO hello
                WITH_IO [stdin=$p] READ_LINE $line
                ASSERT_EQ $line "hello"

                LET $d: DURATION = "5s"
                LET $files: LIST<STRING> = GLOB("*.oxdock")
            "#},
                },
                Example {
                    name: "run rendered modules in a child",
                    fence_meta: Some("roots:unified"),
                    code: indoc! {r#"
                # Dynamic assembly with files: the parent writes a
                # library and an entry script, then runs the entry in a
                # fresh interpreter. Child-side {{ }} stays escaped so
                # the parent does not interpolate it while writing. The
                # child runs by path so entry-relative IMPORT resolves.
                # Unified roots: the child inherits one workspace, so
                # parent and child see the same files.
                IMPORT [STD]
                WRITE lib.oxfile """
                    FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
                    EXPORT GREET
                    """
                WRITE main.oxfile """
                    IMPORT ["lib.oxfile" AS LIB]
                    LET $g: STRING = LIB::GREET("Ada")
                    ECHO "says \{{ $g }}"
                    """
                LET $exe: STRING = INTERPRETER()
                LET $out: STRING = RUN [$exe, "main.oxfile"]
                ASSERT_CONTAINS $out "says hi Ada"
            "#},
                },
                Example {
                    name: "dynamic module assembly",
                    fence_meta: Some("roots:unified"),
                    code: indoc! {r#"
                # A function that assembles a module: MAKE_GREETER bakes
                # its argument into a generated file with a bare {{ }},
                # then a child run imports the result. Bare {{ }} injects
                # parent values at write time; escaped \{{ }} survives for
                # the child to interpolate. Bind imported calls with LET:
                # {{ }} placeholders resolve pure functions only.
                IMPORT [STD]

                # The renderer: parent values land in the module source.
                FUNC MAKE_GREETER($who: STRING): STRING {
                    WRITE greeter.oxfile """
                        FUNC GREET(): STRING { RETURN "hi {{ $who }}" }
                        EXPORT GREET
                        """
                    RETURN "greeter.oxfile"
                }

                # The entry: imports the rendered module by its path.
                WRITE main.oxfile """
                    IMPORT ["greeter.oxfile" AS G]
                    LET $g: STRING = G::GREET()
                    ECHO "says \{{ $g }}"
                    """

                # Assemble, then run the entry in a fresh interpreter.
                LET $made: STRING = MAKE_GREETER("Ada")
                ASSERT_EQ $made "greeter.oxfile"
                LET $exe: STRING = INTERPRETER()
                LET $out: STRING = RUN [$exe, "main.oxfile"]
                ASSERT_CONTAINS $out "says hi Ada"
            "#},
                },
                Example {
                    name: "export unknown type fails",
                    fence_meta: Some("expect_error:\"does not match any top-level TYPE\""),
                    code: indoc! {r#"
                # Only declared TYPE aliases are exportable.
                TYPE PERSON = MAP<name: STRING>
                EXPORT TYPE ANIMAL
            "#},
                },
                Example {
                    name: "undeclared type fails",
                    fence_meta: Some("expect_error:\"unknown type\""),
                    code: indoc! {r#"
                # TYPE names must be declared before use.
                LET $p: PERSON = {name: "Ada"}
            "#},
                },
            ],
        },
    ]
}

// ── Display ────────────────────────────────────────────────────────────────

impl fmt::Display for StepKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
            StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
            StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
            StepKind::Env { key, value } => {
                write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
            }
            StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
            StepKind::RunExec { argv } => {
                let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
                write!(f, "RUN [{}]", parts.join(", "))
            }
            StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
            StepKind::Copy {
                from_workspace,
                from_host,
                to_host,
                from,
                to,
            } => {
                let mut head = String::from("COPY");
                if let Some(target) = from_workspace {
                    head.push_str(&format!(" --from-workspace {target}"));
                }
                if *from_host {
                    head.push_str(" --from-host");
                }
                if *to_host {
                    head.push_str(" --to-host");
                }
                write!(
                    f,
                    "{head} {} {}",
                    fmt_value(from, quote_arg),
                    fmt_value(to, quote_arg)
                )
            }
            StepKind::Symlink {
                from_workspace,
                from,
                to,
            } => {
                if let Some(target) = from_workspace {
                    write!(
                        f,
                        "SYMLINK --from-workspace {} {} {}",
                        target,
                        fmt_value(from, quote_arg),
                        fmt_value(to, quote_arg)
                    )
                } else {
                    write!(
                        f,
                        "SYMLINK {} {}",
                        fmt_value(from, quote_arg),
                        fmt_value(to, quote_arg)
                    )
                }
            }
            StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
            StepKind::Install { from, to } => write!(
                f,
                "INSTALL {} {}",
                fmt_value(from, quote_arg),
                fmt_value(to, quote_arg)
            ),
            StepKind::SetExecutable { path } => {
                write!(f, "SET_EXECUTABLE {}", fmt_value(path, quote_arg))
            }
            StepKind::Archive { src, dst, raw } => {
                if *raw {
                    write!(
                        f,
                        "ARCHIVE --raw {} {}",
                        fmt_value(src, quote_arg),
                        fmt_value(dst, quote_arg)
                    )
                } else {
                    write!(
                        f,
                        "ARCHIVE {} {}",
                        fmt_value(src, quote_arg),
                        fmt_value(dst, quote_arg)
                    )
                }
            }
            StepKind::Unarchive {
                src,
                dst,
                max_bytes,
            } => {
                write!(f, "UNARCHIVE")?;
                if let Some(n) = max_bytes {
                    write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
                }
                write!(
                    f,
                    " {} {}",
                    fmt_value(src, quote_arg),
                    fmt_value(dst, quote_arg)
                )
            }
            StepKind::Ls(a) => {
                write!(f, "LS")?;
                if let Some(x) = a {
                    write!(f, " {}", fmt_value(x, quote_arg))?;
                }
                Ok(())
            }
            StepKind::Read(a) => {
                write!(f, "READ")?;
                if let Some(x) = a {
                    write!(f, " {}", fmt_value(x, quote_arg))?;
                }
                Ok(())
            }
            StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
            StepKind::Prompt {
                var,
                message,
                default,
            } => {
                write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
                if let Some(d) = default {
                    write!(f, " {}", fmt_value(d, quote_arg))?;
                }
                Ok(())
            }
            StepKind::Write { path, contents } => {
                write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
                if let Some(b) = contents {
                    write!(f, " {}", fmt_value(b, quote_msg))?;
                }
                Ok(())
            }
            StepKind::Append { path, contents } => {
                write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
                if let Some(b) = contents {
                    write!(f, " {}", fmt_value(b, quote_msg))?;
                }
                Ok(())
            }
            StepKind::AppendLine { path, contents } => {
                write!(
                    f,
                    "APPEND_LINE {} {}",
                    fmt_value(path, quote_arg),
                    fmt_value(contents, quote_msg)
                )
            }
            StepKind::Remove { path, recursive } => {
                if *recursive {
                    write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
                } else {
                    write!(f, "REMOVE {}", fmt_value(path, quote_arg))
                }
            }
            StepKind::Expand { path, overrides } => {
                write!(f, "EXPAND")?;
                if let Some(p) = path {
                    write!(f, " {}", fmt_value(p, quote_arg))?;
                }
                for (k, v) in overrides {
                    write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
                }
                Ok(())
            }
            StepKind::AssertEq {
                hash,
                actual,
                expected,
            }
            | StepKind::AssertNe {
                hash,
                actual,
                expected,
            } => {
                let verb = match self {
                    StepKind::AssertEq { .. } => Command::AssertEq.as_str(),
                    _ => Command::AssertNe.as_str(),
                };
                if let Some(d) = hash {
                    write!(f, "{verb} --hash {d} {}", fmt_assert_target(actual))?;
                } else {
                    write!(
                        f,
                        "{verb} {} {}",
                        fmt_assert_target(actual),
                        fmt_value(
                            expected
                                .as_ref()
                                .expect("Display of ASSERT without --hash needs expected"),
                            quote_msg
                        )
                    )?;
                }
                Ok(())
            }
            StepKind::AssertContains { haystack, needle } => write!(
                f,
                "{} {} {}",
                Command::AssertContains.as_str(),
                fmt_assert_target(haystack),
                fmt_value(needle, quote_msg)
            ),
            StepKind::WithIo { bindings, cmd } => {
                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
                write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
            }
            StepKind::WithIoBlock { bindings } => {
                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
                write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
            }
            StepKind::CopyGit {
                rev,
                from,
                to,
                include_dirty,
            } => {
                if *include_dirty {
                    write!(
                        f,
                        "COPY_GIT --include-dirty {} {} {}",
                        fmt_value(rev, quote_arg),
                        fmt_value(from, quote_arg),
                        fmt_value(to, quote_arg)
                    )
                } else {
                    write!(
                        f,
                        "COPY_GIT {} {} {}",
                        fmt_value(rev, quote_arg),
                        fmt_value(from, quote_arg),
                        fmt_value(to, quote_arg)
                    )
                }
            }
            StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
            StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
            StepKind::ListAppend { list, item } => {
                write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
            }
            StepKind::For {
                key_var,
                key_type,
                var,
                var_type,
                in_expr,
                body,
            } => {
                match key_var {
                    Some(k) => {
                        let kt = key_type.as_deref().unwrap_or("STRING");
                        write!(
                            f,
                            "FOR ${}: {}, ${}: {} IN {} {{",
                            k, kt, var, var_type, in_expr
                        )?
                    }
                    None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
                }
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::If {
                cond,
                then_body,
                else_ifs,
                else_body,
            } => {
                write!(f, "IF {} {{", cond)?;
                for s in then_body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, " }}")?;
                for (c, b) in else_ifs {
                    write!(f, " ELSE IF {} {{", c)?;
                    for s in b {
                        write!(f, "\n    {}", s)?;
                    }
                    write!(f, " }}")?;
                }
                if let Some(b) = else_body {
                    write!(f, " ELSE {{")?;
                    for s in b {
                        write!(f, "\n    {}", s)?;
                    }
                    write!(f, " }}")?;
                }
                Ok(())
            }
            StepKind::Assign {
                var,
                decl_type,
                expr,
            } => {
                // Bare pipe declarations round-trip without an initializer.
                if matches!(expr, Expr::FreshPipe) {
                    write!(f, "LET ${}: {}", var, decl_type)
                } else {
                    write!(f, "LET ${}: {} = {}", var, decl_type, expr)
                }
            }
            StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
            StepKind::AssignCapture {
                var,
                decl_type,
                cmd,
            } => {
                write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
            }
            StepKind::AsyncBlock { body } => {
                write!(f, "ASYNC {{")?;
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::AssignAsync {
                var,
                decl_type,
                body,
            } => {
                write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::Await { var } => write!(f, "AWAIT ${}", var),
            StepKind::AwaitCapture {
                out_var,
                out_type,
                task_var,
            } => {
                write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
            }
            StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
            StepKind::Timeout { duration, body } => {
                let budget = fmt_raw_arg(duration);
                // Single-command form cannot carry an inner guard (the
                // grammar has no guard slot there), so guarded singles
                // take block form rather than silently dropping it.
                if body.len() == 1 && body[0].guard.is_none() {
                    write!(f, "TIMEOUT {} {}", budget, body[0].kind)
                } else {
                    write!(f, "TIMEOUT {} {{", budget)?;
                    for s in body {
                        write!(f, "\n    {}", s)?;
                    }
                    write!(f, "\n}}")
                }
            }
            StepKind::Isolated { body } => {
                if body.len() == 1 && body[0].guard.is_none() {
                    write!(f, "ISOLATED {}", body[0].kind)
                } else {
                    write!(f, "ISOLATED {{")?;
                    for s in body {
                        write!(f, "\n    {}", s)?;
                    }
                    write!(f, "\n}}")
                }
            }
            StepKind::IsolatedInheritEnv { keys } => {
                // Deliberately the prelude spelling: the node only ever
                // renders nested inside ISOLATED Display, where readers
                // see the enclosing block for what it is.
                write!(f, "INHERIT_ENV [{}]", keys.join(", "))
            }
            StepKind::RemoteBlock {
                target,
                vars,
                env,
                body,
            } => {
                let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
                entries.extend(env.iter().map(|e| format!("env:{e}")));
                if entries.is_empty() {
                    write!(f, "REMOTE {target} {{")?;
                } else {
                    write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
                }
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::FuncDef {
                name,
                params,
                return_type,
                is_async,
                body,
                docs,
            } => {
                // Doc blocks render back as `#` lines so Display
                // reparses to identical docs (first line is the
                // summary, the rest follow verbatim).
                if let Some((_, full)) = docs {
                    for doc_line in full.split('\n') {
                        writeln!(f, "# {doc_line}")?;
                    }
                }
                let ps: Vec<String> = params
                    .iter()
                    .map(|(p, t, optional)| {
                        format!("${}{}: {}", p, if *optional { "?" } else { "" }, t)
                    })
                    .collect();
                if *is_async {
                    write!(
                        f,
                        "ASYNC FUNC {}({}): {} {{",
                        name,
                        ps.join(", "),
                        return_type
                    )?;
                } else {
                    write!(f, "FUNC {}({}): {} {{", name, ps.join(", "), return_type)?;
                }
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::Call { name, args } => {
                let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
                write!(f, "{}({})", name, ps.join(", "))
            }
            StepKind::ImportFile { path, alias } => {
                write!(f, "IMPORT [\"{}\" AS {}]", path, alias)
            }
            StepKind::ImportFuncs {
                path,
                alias,
                func_names,
                type_names,
            } => {
                let mut parts: Vec<String> = Vec::new();
                for t in type_names {
                    parts.push(format!("TYPE {t}"));
                }
                for n in func_names {
                    parts.push(n.clone());
                }
                match alias {
                    Some(alias) => write!(
                        f,
                        "IMPORT [[{} FROM \"{}\" AS {}]]",
                        parts.join(", "),
                        path,
                        alias
                    ),
                    None => write!(f, "IMPORT [[{} FROM \"{}\"]]", parts.join(", "), path),
                }
            }
            StepKind::Return { expr, is_bare } => {
                if *is_bare {
                    write!(f, "RETURN")
                } else {
                    write!(f, "RETURN {}", expr)
                }
            }
            StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
            StepKind::While { cond, body } => {
                write!(f, "WHILE {} {{", cond)?;
                for s in body {
                    write!(f, "\n    {}", s)?;
                }
                write!(f, "\n}}")
            }
            StepKind::Break => write!(f, "BREAK"),
            StepKind::Continue => write!(f, "CONTINUE"),
        }
    }
}

/// One lowered instruction token: a positional argument, or a pre-split
/// `KEY=value` assignment from the unified grammar rule. Assignments reach
/// ENV/EXPAND lowerings intact; every other command sees them collapsed to
/// canonical `key=value` text (see `lower_instruction_pair`).
pub(crate) enum InsToken {
    Pos(Arg),
    Assign(String, Arg),
}

pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
    if tokens.is_empty() {
        return Err(ParseError::validation(
            "ENV",
            "ENV requires KEY=value".to_string(),
            ctx,
        ));
    }
    match tokens.as_slice() {
        [InsToken::Assign(key, value)] => {
            // Same KEY=value check the ENV lower applies on the
            // `lower_command` path, over the joined assignment form.
            if crate::command::split_assignment(&format!("{key}={}", value.render()))
                .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
                .is_none()
            {
                return Err(ParseError::validation(
                    "ENV",
                    "ENV requires KEY=value format".to_string(),
                    ctx,
                ));
            }
            Ok(StepKind::Env {
                key: key.clone(),
                value: value.clone(),
            })
        }
        [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
            .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
        {
            Some((key, value)) => Ok(StepKind::Env { key, value }),
            None => Err(ParseError::validation(
                "ENV",
                "ENV requires KEY=value format".to_string(),
                ctx,
            )),
        },
        _ => Err(ParseError::validation(
            "ENV",
            "ENV requires KEY=value format".to_string(),
            ctx,
        )),
    }
}

/// Parser-direct `EXPAND` lowering: positional tokens are the optional path,
/// assignments are overrides. Split quoted values can never masquerade as
/// extra paths : tokenize time already proved they are one value.
pub(crate) fn lower_expand_tokens(
    ctx: &SpanContext,
    tokens: Vec<InsToken>,
) -> ParseResult<StepKind> {
    let mut path = None;
    let mut overrides = Vec::new();
    for token in tokens {
        match token {
            InsToken::Assign(key, value) => {
                if key.is_empty() {
                    return Err(ParseError::validation(
                        "EXPAND",
                        "EXPAND requires KEY=value format for overrides".to_string(),
                        ctx,
                    ));
                }
                overrides.push((key, value));
            }
            InsToken::Pos(arg) => match &arg {
                Arg::String(text, quoted) if !quoted && text.contains('=') => {
                    let Some((key, value)) = crate::command::split_assignment(text)
                        .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?
                    else {
                        return Err(ParseError::validation(
                            "EXPAND",
                            "EXPAND requires KEY=value format for overrides".to_string(),
                            ctx,
                        ));
                    };
                    overrides.push((key, value));
                }
                _ => {
                    if path.is_none() {
                        // Path-typed positional, checked like every other
                        // `lower_command` path arg (literals always pass;
                        // resolution stays runtime).
                        ArgType::Path
                            .check_arg(&arg)
                            .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?;
                        path = Some(arg);
                    } else {
                        return Err(ParseError::validation(
                            "EXPAND",
                            "EXPAND accepts at most one path".to_string(),
                            ctx,
                        ));
                    }
                }
            },
        }
    }
    Ok(StepKind::Expand { path, overrides })
}

/// Wrapper-shared validators, promoted verbatim from the retired pest
/// backend, so every parse entry point enforces identical bodies.
/// Pure outcome logic over [`StepKind`]: contexts only feed error spans.
#[derive(Default)]
pub(crate) struct IoBindingSet {
    stdin: Option<IoBinding>,
    stdout: Option<IoBinding>,
    stderr: Option<IoBinding>,
    tty: Option<IoBinding>,
    rows: Option<IoBinding>,
    cols: Option<IoBinding>,
}

impl IoBindingSet {
    pub(crate) fn insert(&mut self, binding: IoBinding) {
        match binding.stream {
            IoStream::Stdin => self.stdin = Some(binding),
            IoStream::Stdout => self.stdout = Some(binding),
            IoStream::Stderr => self.stderr = Some(binding),
            IoStream::Tty => self.tty = Some(binding),
            IoStream::Rows(_) => self.rows = Some(binding),
            IoStream::Cols(_) => self.cols = Some(binding),
        }
    }

    pub(crate) fn into_vec(self) -> Vec<IoBinding> {
        let mut out = Vec::new();
        if let Some(binding) = self.stdin {
            out.push(binding);
        }
        if let Some(binding) = self.stdout {
            out.push(binding);
        }
        if let Some(binding) = self.stderr {
            out.push(binding);
        }
        if let Some(binding) = self.tty {
            out.push(binding);
        }
        if let Some(binding) = self.rows {
            out.push(binding);
        }
        if let Some(binding) = self.cols {
            out.push(binding);
        }
        out
    }
}

pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
    let mut set = IoBindingSet::default();
    for binding in defaults {
        set.insert(binding.clone());
    }
    for binding in overrides {
        set.insert(binding.clone());
    }
    set.into_vec()
}

pub(crate) fn and_guard_exprs(
    left: Option<GuardExpr>,
    right: Option<GuardExpr>,
) -> Option<GuardExpr> {
    match (left, right) {
        (None, None) => None,
        (Some(expr), None) | (None, Some(expr)) => Some(expr),
        (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
    }
}

pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
    bindings
        .iter()
        .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
}

/// Reject async machinery inside a capture body: background tasks are
/// captured via `LET $o: STRING = AWAIT $t`, never inline.
pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
    let bad = match kind {
        StepKind::AsyncBlock { .. }
        | StepKind::AssignAsync { .. }
        | StepKind::Await { .. }
        | StepKind::AwaitCapture { .. }
        | StepKind::Cancel { .. } => true,
        _ => {
            let mut bad = false;
            kind.walk_child_kinds(&mut |child| {
                bad = bad || reject_async_in_capture(ctx, child).is_err();
            });
            bad
        }
    };
    if bad {
        return Err(ParseError::structural("let", "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE<T> = ASYNC ... then LET $o: STRING = AWAIT $t".to_string(), ctx));
    }
    Ok(())
}

/// Reject `WITH_IO [stdout=$var]` anywhere inside a capture body: the
/// capture sink owns stdout.
pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
    if let StepKind::WithIo { bindings, .. } = kind
        && has_stdout_pipe(bindings)
    {
        return Err(ParseError::structural(
            "let",
            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
                .to_string(),
            ctx,
        ));
    }
    let mut result = Ok(());
    kind.walk_child_kinds(&mut |child| {
        if result.is_ok() {
            result = reject_pipe_stdout_in_capture(ctx, child);
        }
    });
    result
}

/// Rewrite prelude-shaped `INHERIT_ENV` nodes anywhere inside an `ISOLATED`
/// body into `IsolatedInheritEnv`: the nested allowlist reads the isolated
/// snapshot, never the host.
pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
    for step in body {
        rewrite_isolated_inherit_kind(&mut step.kind);
    }
}

/// Single-kind half of [`rewrite_isolated_inherit`]: rewrite the node
/// itself, then recurse through whatever it contains (`WITH_IO` wraps and
/// captures hold one kind; loop/if bodies hold steps).
pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
    if let StepKind::InheritEnv { keys } = kind {
        *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
    }
    match kind {
        StepKind::For { body, .. }
        | StepKind::While { body, .. }
        | StepKind::Timeout { body, .. }
        | StepKind::Isolated { body }
        | StepKind::AssignAsync { body, .. }
        | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
        StepKind::If {
            then_body,
            else_ifs,
            else_body,
            ..
        } => {
            rewrite_isolated_inherit(then_body);
            for (_, branch) in else_ifs {
                rewrite_isolated_inherit(branch);
            }
            if let Some(else_body) = else_body {
                rewrite_isolated_inherit(else_body);
            }
        }
        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
            rewrite_isolated_inherit_kind(cmd);
        }
        _ => {}
    }
}

pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
    if matches!(kind, StepKind::InheritEnv { .. }) {
        return true;
    }
    let mut found = false;
    kind.walk_child_kinds(&mut |child| {
        found = found || contains_inherit_env(child);
    });
    found
}

/// Reject an `INHERIT_ENV` nested anywhere inside another command: the
/// prelude directive only reads at statement level (and, rewritten,
/// inside `ISOLATED` bodies, which never reach here).
pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
    if contains_inherit_env(kind) {
        return Err(ParseError::structural(
            "inherit_env",
            "INHERIT_ENV cannot be nested inside other commands".to_string(),
            ctx,
        ));
    }
    Ok(())
}

pub(crate) fn check_tty_wrapping(
    bindings: &[IoBinding],
    cmd: Option<&StepKind>,
    span: &SpanContext,
) -> ParseResult<()> {
    let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
    let has_geometry = bindings
        .iter()
        .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
    if has_geometry && !has_tty {
        return Err(ParseError::structural(
            "with_io",
            "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size".to_string(),
            span,
        ));
    }
    if !has_tty {
        return Ok(());
    }
    if bindings
        .iter()
        .any(|b| matches!(b.stream, IoStream::Stderr))
    {
        return Err(ParseError::structural(
            "with_io",
            "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex".to_string(),
            span,
        ));
    }
    match cmd {
        Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
        Some(_) => Err(ParseError::structural(
            "with_io",
            "WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it".to_string(),
            span,
        )),
    }
}

/// Reject `WITH_IO` steps directly inside an `ASYNC` body: pipe wiring
/// belongs outside the task (`WITH_IO [...] ASYNC ...`), never inside.
pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
    for step in body {
        if matches!(&step.kind, StepKind::WithIo { .. }) {
            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), ctx));
        }
    }
    Ok(())
}

/// Validate `EXPORT` names at end of parse. Forward references are
/// allowed (EXPORT may precede its FUNCs), so this runs against the
/// completed top-level scope. Bare names must match a top-level
/// `FUNC`; qualified `MOD::NAME` names must match a known module
/// member (opaque modules skip the member check; the runtime registry
/// resolves them or fails serving). Duplicates are rejected at the
/// EXPORT site. Promoted verbatim (the pest finish pass delegates).
pub(crate) fn validate_exports(
    ctx: &SpanContext,
    func_exports: &[String],
    type_exports: &[String],
    top: &HashSet<String>,
    top_types: &HashSet<String>,
    modules: &ModuleTable,
    top_imports: &[String],
) -> ParseResult<()> {
    for name in func_exports {
        let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
            None => top.contains(name),
            Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
                top.contains(base)
            }
            Some((module, _base)) => match modules.modules.get(module) {
                None => {
                    // File-import aliases (#115) never enter the module
                    // table: a re-export names an imported function for
                    // the entry's own tool surface. The alias must be a
                    // visible import; whether the file actually exports
                    // the name is checked where the import loads (closure
                    // validation, then serving), since parse performs no
                    // IO. Anything else is an unknown module.
                    top_imports.iter().any(|m| m == module)
                }
                Some(None) => true,
                Some(Some(funcs)) => funcs.func_names.contains(_base),
            },
        };
        if !valid {
            return Err(ParseError::validation(
                crate::constants::KEYWORD_EXPORT,
                format!("EXPORT `{name}` does not match any top-level FUNC or known module member"),
                ctx,
            ));
        }
    }
    for name in type_exports {
        // Local TYPE aliases export bare; qualified `ALIAS::TYPE`
        // re-exports defer existence to import loading (same as func
        // re-exports), requiring only a visible import alias here.
        // Bare re-exports of imported types (whole-file types land
        // bare) defer when the file has imports, so `EXPORT PERSON`
        // after `IMPORT ["lib" AS LIB]` can promote the imported type.
        let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
            None => top_types.contains(name) || !top_imports.is_empty(),
            Some((module, _base)) => {
                if module == crate::constants::SCRIPT_MODULE_NAME {
                    top_types.contains(_base)
                } else {
                    match modules.modules.get(module) {
                        None => top_imports.iter().any(|m| m == module),
                        // Host modules: types live in the global type
                        // directory, not the func table. Parse cannot
                        // know host type membership (descriptors register
                        // at runtime), so a known module passes here and
                        // import loading validates the member.
                        Some(_) => true,
                    }
                }
            }
        };
        if !valid {
            return Err(ParseError::validation(
                crate::constants::KEYWORD_EXPORT,
                format!("EXPORT TYPE `{name}` does not match any top-level TYPE"),
                ctx,
            ));
        }
    }
    Ok(())
}

/// REMOTE whole-script validators and body-symbol collectors,
/// promoted verbatim from the pest backend (which delegates) so both
/// parse pathways enforce identical blocks.
/// Reject `COPY --from-host` / `--to-host` outside `REMOTE` bodies.
/// Transfer declarations only mean something where a session hoists them;
/// anywhere else they would silently behave as local copies.
pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
    fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
        if let StepKind::Copy {
            from_host, to_host, ..
        } = kind
            && (*from_host || *to_host)
            && !in_remote
        {
            return Err(ParseError::structural(
                "copy",
                "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
                ctx,
            ));
        }
        let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
        let mut result = Ok(());
        kind.walk_child_kinds(&mut |child| {
            if result.is_ok() {
                result = visit_kind(child, child_remote, ctx);
            }
        });
        result
    }
    for step in steps {
        visit_kind(&step.kind, false, ctx)?;
    }
    Ok(())
}

/// True when any step in the slice (transitively, through nested bodies)
/// is a `REMOTE` block. `REMOTE` blocks never nest: the inner block would
/// have no session, no inventory, and no defined sync boundary.
pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
    steps.iter().any(|step| contains_remote_kind(&step.kind))
}

pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
    if matches!(kind, StepKind::RemoteBlock { .. }) {
        return true;
    }
    let mut found = false;
    kind.walk_child_kinds(&mut |child| {
        found = found || contains_remote_kind(child);
    });
    found
}

/// Collect transitively defined `FUNC` names and invoked call names from a
/// `REMOTE` body. Statement calls, expression calls (including compiled
/// math ops and inline blocks), and calls nested in any sub-body are all
/// covered through the uniform [`StepKind`] walkers. Only user-defined
/// `SCRIPT` symbols matter downstream: qualified module calls pass through.
pub(crate) fn collect_remote_body_symbols(
    steps: &[Step],
    defs: &mut HashSet<String>,
    calls: &mut Vec<String>,
) {
    for step in steps {
        collect_remote_kind_symbols(&step.kind, defs, calls);
    }
}

pub(crate) fn collect_remote_kind_symbols(
    kind: &StepKind,
    defs: &mut HashSet<String>,
    calls: &mut Vec<String>,
) {
    if let StepKind::FuncDef { name, .. } = kind {
        defs.insert(name.clone());
    }
    if let StepKind::Call { name, .. } = kind {
        calls.push(name.clone());
    }
    kind.walk_step_exprs(&mut |expr| match expr {
        Expr::Call { name, .. } => calls.push(name.clone()),
        Expr::CompiledMath(ops) => {
            for op in ops {
                if let MathOp::Call { name, .. } = op {
                    calls.push(name.clone());
                }
            }
        }
        Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
        _ => {}
    });
}

/// Expression lowering core, promoted verbatim from the retired pest
/// backend: folding constructors, RPN compilation, boundary rejection,
/// and numeric classification. The parser calls
/// these directly, so folding and overflow behavior are single-sourced.
/// Reject a staged `UnsignedIntBoundary` in any position where unary `-`
/// cannot consume it (every compound constructor calls this on children).
/// Expression lowering core (promoted verbatim from the retired pest
/// backend): operates on `Expr`, never on token pairs.
pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
        return Err(ParseError::structural(
            "expr",
            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
            ctx,
        ));
    }
    Ok(())
}

/// Apply unary `-`: fold literals, consume the `i64::MIN` boundary, else
/// compile to RPN `Neg` (or AST `0 - x` fallback for non-math operands).
/// Shared with the v2 backend.
pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
    match expr {
        Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
            (Some(n), _) => match n.checked_neg() {
                Some(neg) => Ok(Expr::Literal(Value::int(neg))),
                None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
            },
            (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
            (None, None) => {
                let other = Expr::Literal(v);
                if let Some(mut ops) = expr_to_rpn(&other) {
                    ops.push(MathOp::Neg);
                    Ok(Expr::CompiledMath(ops))
                } else {
                    // Non-math operand (list/map/logical): `0 - x` evaluates via
                    // the shared arithmetic helper to a runtime Type Error.
                    Ok(Expr::Arithmetic {
                        op: ArithOp::Sub,
                        left: Box::new(Expr::Literal(Value::int(0))),
                        right: Box::new(other),
                    })
                }
            }
        },
        Expr::UnsignedIntBoundary(n) => {
            if n == i64::MAX as u64 + 1 {
                Ok(Expr::Literal(Value::int(i64::MIN)))
            } else {
                Err(ParseError::structural(
                    "expr",
                    format!("integer overflow: {} exceeds i64::MAX", n),
                    ctx,
                ))
            }
        }
        other => {
            if let Some(mut ops) = expr_to_rpn(&other) {
                ops.push(MathOp::Neg);
                Ok(Expr::CompiledMath(ops))
            } else {
                // Non-math operand (list/map/logical): `0 - x` evaluates via
                // the shared arithmetic helper to a runtime Type Error.
                Ok(Expr::Arithmetic {
                    op: ArithOp::Sub,
                    left: Box::new(Expr::Literal(Value::int(0))),
                    right: Box::new(other),
                })
            }
        }
    }
}

/// Try parse-time constant folding for binary arithmetic/comparison.
/// Returns `Some(literal)` on success, `None` when not both literals or
/// when the op would error at runtime (div-zero/overflow/non-finite:
/// leave for the RPN evaluator so the error surfaces at runtime).
fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
        return None;
    };
    fold_arith_values(op, lv, rv).map(Expr::Literal)
}

fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
    match (left.as_i64(), right.as_i64()) {
        (Some(a), Some(b)) => {
            let v = match op {
                ArithOp::Add => a.checked_add(b)?,
                ArithOp::Sub => a.checked_sub(b)?,
                ArithOp::Mul => a.checked_mul(b)?,
                ArithOp::Div => a.checked_div(b)?,
            };
            Some(Value::int(v))
        }
        _ => {
            let (af, bf) = (as_f64(left)?, as_f64(right)?);
            fold_float(op, af, bf)
        }
    }
}

fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
    if !a.is_finite() || !b.is_finite() {
        return None;
    }
    let v = match op {
        ArithOp::Add => a + b,
        ArithOp::Sub => a - b,
        ArithOp::Mul => a * b,
        ArithOp::Div => {
            if b == 0.0 {
                return None;
            }
            a / b
        }
    };
    if v.is_finite() {
        Some(Value::float(v))
    } else {
        None
    }
}

fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
        return None;
    };
    match (lv.as_i64(), rv.as_i64()) {
        (Some(a), Some(b)) => {
            let r = match op {
                CompareOp::Eq => a == b,
                CompareOp::Ne => a != b,
                CompareOp::Lt => a < b,
                CompareOp::Le => a <= b,
                CompareOp::Gt => a > b,
                CompareOp::Ge => a >= b,
            };
            Some(Expr::Literal(Value::bool(r)))
        }
        _ => {
            if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
                return match op {
                    CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
                    CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
                    _ => None,
                };
            }
            let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
            let r = match op {
                CompareOp::Eq => af == bf,
                CompareOp::Ne => af != bf,
                CompareOp::Lt => af < bf,
                CompareOp::Le => af <= bf,
                CompareOp::Gt => af > bf,
                CompareOp::Ge => af >= bf,
            };
            Some(Expr::Literal(Value::bool(r)))
        }
    }
}

fn as_f64(v: &Value) -> Option<f64> {
    if let Some(n) = v.as_i64() {
        return Some(n as f64);
    }
    match v.as_f64() {
        Some(f) if f.is_finite() => Some(f),
        _ => None,
    }
}

/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
pub(crate) fn make_arith(
    ctx: &SpanContext,
    op: ArithOp,
    left: Expr,
    right: Expr,
) -> ParseResult<Expr> {
    reject_boundary(ctx, &left)?;
    reject_boundary(ctx, &right)?;
    if let Some(folded) = try_fold_arith(op, &left, &right) {
        return Ok(folded);
    }
    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
        lops.append(&mut rops);
        lops.push(match op {
            ArithOp::Add => MathOp::Add,
            ArithOp::Sub => MathOp::Sub,
            ArithOp::Mul => MathOp::Mul,
            ArithOp::Div => MathOp::Div,
        });
        return Ok(Expr::CompiledMath(lops));
    }
    Ok(Expr::Arithmetic {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
pub(crate) fn make_compare(
    ctx: &SpanContext,
    op: CompareOp,
    left: Expr,
    right: Expr,
) -> ParseResult<Expr> {
    reject_boundary(ctx, &left)?;
    reject_boundary(ctx, &right)?;
    if let Some(folded) = try_fold_compare(op, &left, &right) {
        return Ok(folded);
    }
    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
        lops.append(&mut rops);
        lops.push(match op {
            CompareOp::Eq => MathOp::Eq,
            CompareOp::Ne => MathOp::Ne,
            CompareOp::Lt => MathOp::Lt,
            CompareOp::Le => MathOp::Le,
            CompareOp::Gt => MathOp::Gt,
            CompareOp::Ge => MathOp::Ge,
        });
        return Ok(Expr::CompiledMath(lops));
    }
    Ok(Expr::Compare {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

/// Convert an operand subtree to flat RPN. Returns `None` for shapes with
/// no RPN encoding (`Not`/`Logical`/`List`/`Map`/`FreshPipe`/stray boundary): callers
/// fall back to AST nodes evaluated recursively.
/// Shared with the v2 backend.
///
pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
    match expr {
        Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
        Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
        Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
        Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
            base: base.clone(),
            keys: keys.clone(),
        }]),
        Expr::Call { name, args } => {
            let mut ops = Vec::new();
            for arg in args {
                ops.extend(expr_to_rpn(arg)?);
            }
            ops.push(MathOp::Call {
                name: name.clone(),
                arity: args.len(),
            });
            Some(ops)
        }
        Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
        Expr::Arithmetic { op, left, right } => {
            let mut ops = expr_to_rpn(left)?;
            ops.extend(expr_to_rpn(right)?);
            ops.push(match op {
                ArithOp::Add => MathOp::Add,
                ArithOp::Sub => MathOp::Sub,
                ArithOp::Mul => MathOp::Mul,
                ArithOp::Div => MathOp::Div,
            });
            Some(ops)
        }
        Expr::Compare { op, left, right } => {
            let mut ops = expr_to_rpn(left)?;
            ops.extend(expr_to_rpn(right)?);
            ops.push(match op {
                CompareOp::Eq => MathOp::Eq,
                CompareOp::Ne => MathOp::Ne,
                CompareOp::Lt => MathOp::Lt,
                CompareOp::Le => MathOp::Le,
                CompareOp::Gt => MathOp::Gt,
                CompareOp::Ge => MathOp::Ge,
            });
            Some(ops)
        }
        Expr::CompiledMath(ops) => Some(ops.clone()),
        Expr::FreshPipe => None,
        Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
        Expr::UnsignedIntBoundary(_) => None,
    }
}

/// Pure numeric classification (the token backend gates
/// `_`-separator shape before calling: the classifier strips them, so
/// `1__0` must never reach it as numeric). Returns the literal,
/// `UnsignedIntBoundary` staging, or the exact pest error text.
pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
    let clean = text.replace('_', "");
    if clean.contains('.') {
        let parsed: f64 = clean
            .parse()
            .map_err(|_| format!("invalid float literal {text:?}"))?;
        if !parsed.is_finite() {
            return Err(format!("invalid float literal {text:?}"));
        }
        return Ok(Expr::Literal(Value::float(parsed)));
    }
    let digits: u64 = clean
        .parse()
        .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
    if digits <= i64::MAX as u64 {
        Ok(Expr::Literal(Value::int(digits as i64)))
    } else if digits == i64::MAX as u64 + 1 {
        Ok(Expr::UnsignedIntBoundary(digits))
    } else {
        Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::{
        format_byte_count, format_duration, parse_byte_count, parse_duration,
        strip_digit_separators,
    };
    use crate::parser::parse_script;

    fn parse_err(script: &str) -> String {
        parse_script(script, lower_command)
            .expect_err("script must fail to parse")
            .to_string()
    }

    #[test]
    fn malformed_with_io_binding_names_the_bad_binding() {
        let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
        assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
        assert!(!err.contains("unknown command"), "{err}");
        assert!(err.contains("stdout=discard"), "{err}");
        assert!(err.contains("[stdout=$p]"), "{err}");
    }

    #[test]
    fn connect_is_unknown_command() {
        // `CONNECT` left core for the NET plugin: the builtin name no
        // longer resolves. Use `NET_CONNECT` with explicit pipes.
        let err = parse_err("CONNECT 127.0.0.1:8080\n");
        assert!(err.contains("unknown command"), "{err}");
        assert!(err.contains("CONNECT"), "{err}");
    }

    #[test]
    fn listen_is_unknown_command() {
        // `LISTEN` left core for the NET plugin: the builtin name no
        // longer resolves. Use `NET_LISTEN` for a listener handle.
        let err = parse_err("LISTEN 127.0.0.1:8080\n");
        assert!(err.contains("unknown command"), "{err}");
        assert!(err.contains("LISTEN"), "{err}");
    }

    #[test]
    fn await_without_task_variable_points_at_syntax() {
        let err = parse_err("AWAIT ECHO \"test\"\n");
        assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
        assert!(!err.contains("unknown command"), "{err}");
        assert!(err.contains("AWAIT $t"), "{err}");
        assert!(err.contains("ECHO"), "{err}");
    }

    #[test]
    fn bare_let_without_type_points_at_typed_syntax() {
        let err = parse_err("LET $x = 1\n");
        assert!(err.contains("LET requires explicit types"), "{err}");
        assert!(err.contains("LET $var: TYPE = <expr>"), "{err}");
    }

    #[test]
    fn workspace_accepts_all_four_targets_uppercase_only() {
        // WORKSPACE targets are uppercase-only, like every other DSL
        // keyword argument: lowercase spellings are rejected.
        for (spelling, target) in [
            ("SNAPSHOT", WorkspaceTarget::Snapshot),
            ("LOCAL", WorkspaceTarget::Local),
            ("CACHE", WorkspaceTarget::Cache { local: false }),
            ("SYSTEM", WorkspaceTarget::System),
        ] {
            let steps =
                parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
            assert_eq!(steps.len(), 1);
            assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
            assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
        }
        for spelling in ["snapshot", "local", "cache", "system"] {
            let err = parse_err(&format!("WORKSPACE {spelling}\n"));
            assert!(
                err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
                "{spelling}: {err}"
            );
        }
        let err = parse_err("WORKSPACE REMOTE\n");
        assert!(
            err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
            "{err}"
        );

        // `--local` selects the project-tree cache and round-trips
        // through Display; anywhere else it is rejected.
        let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
        assert_eq!(
            steps[0].kind,
            StepKind::Workspace(WorkspaceTarget::Cache { local: true })
        );
        assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
        for bad in [
            "WORKSPACE SNAPSHOT --local\n",
            "WORKSPACE LOCAL --local\n",
            "WORKSPACE SYSTEM --local\n",
        ] {
            let err = parse_err(bad);
            assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
        }
    }

    #[test]
    fn archive_unarchive_parse_and_round_trip() {
        let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
        match &steps[0].kind {
            StepKind::Archive { src, dst, raw } => {
                assert_eq!(src.as_str(), "bundle");
                assert_eq!(dst.as_str(), "bundle.tar.gz");
                assert!(!raw);
            }
            other => panic!("expected Archive, got {other:?}"),
        }
        assert_eq!(
            steps[0].kind.to_string(),
            "ARCHIVE bundle \"bundle.tar.gz\""
        );

        let steps =
            parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
        assert!(
            matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
            "unexpected lowering: {:?}",
            steps[0].kind
        );
        assert_eq!(
            steps[0].kind.to_string(),
            "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
        );

        let steps =
            parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
        match &steps[0].kind {
            StepKind::Unarchive {
                src,
                dst,
                max_bytes,
            } => {
                assert_eq!(src.as_str(), "pack.tar.gz");
                assert_eq!(dst.as_str(), "unpacked");
                assert_eq!(max_bytes, &None);
            }
            other => panic!("expected Unarchive, got {other:?}"),
        }
        assert_eq!(
            steps[0].kind.to_string(),
            "UNARCHIVE \"pack.tar.gz\" unpacked"
        );

        let steps = parse_script(
            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
            lower_command,
        )
        .expect("parses");
        match &steps[0].kind {
            StepKind::Unarchive {
                src,
                dst,
                max_bytes,
            } => {
                assert_eq!(src.as_str(), "pack.tar.gz");
                assert_eq!(dst.as_str(), "unpacked");
                assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
            }
            other => panic!("expected Unarchive, got {other:?}"),
        }
        assert_eq!(
            steps[0].kind.to_string(),
            "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
        );

        for script in [
            "ARCHIVE bundle bundle.tar.gz\n",
            "ARCHIVE --raw tool.bin tool.tar\n",
            "UNARCHIVE pack.tar.gz unpacked\n",
            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
        ] {
            let first = parse_script(script, lower_command).expect("parses");
            let rendered = first[0].kind.to_string() + "\n";
            let second = parse_script(&rendered, lower_command).expect("reparses");
            // Quoting is parse provenance (Display normalizes it), so the
            // fixpoint is on rendering, not on full equality.
            assert_eq!(
                second[0].kind.to_string(),
                first[0].kind.to_string(),
                "Display must fixpoint for {script:?}"
            );
        }

        for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
            let err = parse_err(bad);
            assert!(
                err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
                "{bad}: {err}"
            );
        }
    }

    #[test]
    fn copy_from_workspace_selects_source_root() {
        for (spelling, target) in [
            ("SNAPSHOT", WorkspaceTarget::Snapshot),
            ("LOCAL", WorkspaceTarget::Local),
            ("CACHE", WorkspaceTarget::Cache { local: false }),
            ("SYSTEM", WorkspaceTarget::System),
        ] {
            let steps = parse_script(
                &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
                lower_command,
            )
            .expect("parses");
            assert!(
                matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
                "unexpected lowering for {spelling}: {:?}",
                steps[0].kind
            );
        }
        // The `=` form carries the value inline on one token: `--`
        // tokens never match `assignment`, so `strip_flags` splits it.
        for script in [
            "COPY --from-workspace=CACHE a.txt b.txt\n",
            "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
        ] {
            let steps = parse_script(script, lower_command).expect("parses");
            assert!(
                matches!(
                    &steps[0].kind,
                    StepKind::Copy {
                        from_workspace: Some(WorkspaceTarget::Cache { local: false }),
                        ..
                    }
                ),
                "unexpected lowering for {script:?}: {:?}",
                steps[0].kind
            );
        }
        // An absent flag means the build-context default.
        let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
        assert!(
            matches!(
                &steps[0].kind,
                StepKind::Copy {
                    from_workspace: None,
                    ..
                }
            ),
            "unexpected lowering: {:?}",
            steps[0].kind
        );
        // Unknown and lowercase values are rejected uppercase-only.
        for bad in ["REMOTE", "local"] {
            let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
        }
    }

    #[test]
    fn symlink_from_workspace_selects_source_root() {
        for (spelling, target) in [
            ("SNAPSHOT", WorkspaceTarget::Snapshot),
            ("LOCAL", WorkspaceTarget::Local),
            ("CACHE", WorkspaceTarget::Cache { local: false }),
            ("SYSTEM", WorkspaceTarget::System),
        ] {
            let steps = parse_script(
                &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
                lower_command,
            )
            .expect("parses");
            assert!(
                matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
                "unexpected lowering for {spelling}: {:?}",
                steps[0].kind
            );
            let roundtrip = steps[0].kind.to_string();
            assert!(
                roundtrip.contains("--from-workspace"),
                "display should round-trip the flag: {roundtrip}"
            );
        }
        let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
        assert!(
            matches!(
                &steps[0].kind,
                StepKind::Symlink {
                    from_workspace: None,
                    ..
                }
            ),
            "unexpected lowering: {:?}",
            steps[0].kind
        );
        for bad in ["REMOTE", "local"] {
            let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
        }
        // The `=` form carries the value inline, like COPY.
        let steps = parse_script(
            "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
            lower_command,
        )
        .expect("parses");
        assert!(
            matches!(
                &steps[0].kind,
                StepKind::Symlink {
                    from_workspace: Some(WorkspaceTarget::Local),
                    ..
                }
            ),
            "unexpected lowering: {:?}",
            steps[0].kind
        );
    }

    #[test]
    fn dash_dash_equals_tokens_bypass_assignment() {
        // `--` tokens never match `assignment`: flags keep their `=`
        // form as one argument, while other commands see the same text.
        let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
        let StepKind::Env { key, value } = &steps[0].kind else {
            panic!("expected Env, got {:?}", steps[0].kind);
        };
        assert_eq!(key, "--foo");
        assert_eq!(value.as_str(), "bar");

        let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
        let StepKind::Run(cmd) = &steps[0].kind else {
            panic!("expected Run, got {:?}", steps[0].kind);
        };
        assert!(
            cmd.as_str().contains("--foo=bar"),
            "unexpected RUN lowering: {cmd:?}"
        );

        let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
        let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
            .expect("parses");
        let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
            panic!("expected AssertEq, got {:?}", steps[0].kind);
        };
        assert_eq!(hash.as_deref(), Some(digest));

        // EXPAND still treats `--k=v` positionals as overrides.
        let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
        let StepKind::Expand { path, overrides } = &steps[0].kind else {
            panic!("expected Expand, got {:?}", steps[0].kind);
        };
        assert!(path.is_none());
        assert_eq!(overrides.len(), 1);
        assert_eq!(overrides[0].0.as_str(), "--k");
    }

    #[test]
    fn assert_ne_lowers_and_round_trips() {
        let steps = parse_script("ASSERT_NE $status 404\n", lower_command).expect("parses");
        let StepKind::AssertNe {
            hash,
            actual,
            expected,
        } = &steps[0].kind
        else {
            panic!("expected AssertNe, got {:?}", steps[0].kind);
        };
        assert!(hash.is_none());
        assert!(
            matches!(actual, AssertTarget::Value(_)),
            "unexpected actual: {actual:?}"
        );
        assert!(
            matches!(expected, Some(Arg::Expr(_))),
            "numeric expected lowers to an expression: {expected:?}"
        );
        let roundtrip = steps[0].kind.to_string();
        assert!(
            roundtrip.contains(Command::AssertNe.as_str()) && roundtrip.contains("404"),
            "display should round-trip the command: {roundtrip}"
        );

        let err = parse_script("ASSERT_NE $status\n", lower_command).expect_err("needs expected");
        assert!(
            err.to_string().contains("requires an expected value"),
            "unexpected error: {err}"
        );

        let err = parse_script("ASSERT_NE --hash abc123 $status \"junk\"\n", lower_command)
            .expect_err("hash plus expected must fail");
        assert!(
            err.to_string().contains("cannot be combined"),
            "unexpected error: {err}"
        );

        // Parity: the shared lowering rejects the combination for EQ too.
        let err = parse_script("ASSERT_EQ --hash abc123 $status \"junk\"\n", lower_command)
            .expect_err("hash plus expected must fail");
        assert!(
            err.to_string().contains("cannot be combined"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn space_before_paren_is_not_a_call() {
        // The call head and `(` must be contiguous: `ECHO (1 + 2)` is an
        // instruction, never a function invocation.
        let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
        assert_eq!(steps.len(), 1);
        assert!(
            !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
            "space before paren must not route to a call: {:?}",
            steps[0].kind
        );
    }

    #[test]
    fn unknown_type_tag_parses_as_custom() {
        // Open type tags: declarations carry plain names and resolve
        // against the descriptor table at runtime, so host types need no
        // grammar change (see the custom_types core tests).
        let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
        let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
            panic!("expected Assign, got {:?}", steps[0].kind);
        };
        assert_eq!(decl_type, "FOO");
    }

    #[test]
    fn bare_for_without_types_is_rejected() {
        let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
        assert!(err.contains("FOR requires explicit types"), "{err}");
    }

    #[test]
    fn mutate_statement_parses_without_keyword() {
        let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
        assert!(matches!(steps[0].kind, StepKind::Set { .. }));
    }

    #[test]
    fn set_keyword_is_rejected_with_mutation_hint() {
        let err = parse_err("SET $y = 2\n");
        assert!(err.contains("not a keyword"), "{err}");
        assert!(err.contains("$var = <expr>"), "{err}");
    }

    #[test]
    fn structural_fallthrough_commits_per_keyword() {
        for (script, cmd) in [
            ("CANCEL foo\n", "CANCEL"),
            ("TIMEOUT foo\n", "TIMEOUT"),
            ("FOR foo\n", "FOR"),
            ("IF foo\n", "IF"),
            ("LET foo\n", "LET"),
            // NOTE: INHERIT_ENV is dual-registered as a leaf command
            // (`INHERIT_ENV <key>...`), so `INHERIT_ENV foo` lowers
            // successfully instead of erroring : excluded here.
            ("ASYNC\n", "ASYNC"),
            ("ELSE foo\n", "ELSE"),
        ] {
            let err = parse_err(script);
            assert!(
                err.contains(&format!("invalid syntax for command {cmd}")),
                "{cmd}: {err}"
            );
            assert!(!err.contains("unknown command"), "{cmd}: {err}");
        }
    }

    #[test]
    fn leaf_arity_errors_carry_invalid_syntax_prefix() {
        let err = parse_err("SLEEP 1s 2s\n");
        assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
        assert!(!err.contains("unknown command"), "{err}");
    }

    #[test]
    fn list_append_lowers_variable_and_item() {
        let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
        let StepKind::ListAppend { list, item } = &steps[0].kind else {
            panic!("expected ListAppend, got {:?}", steps[0].kind);
        };
        assert_eq!(list, "items");
        assert!(matches!(item, Arg::String(s, _) if s == "hi"));
        assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
    }

    #[test]
    fn list_append_accepts_call_shaped_item() {
        // A bare full-region call in arg position stays typed
        // (evaluated at runtime) instead of appending the source
        // text: same owner as assignment values and RUN-exec items.
        let steps = parse_script(
            "FUNC MAKE(): STRING { RETURN \"made\" }\nLIST_APPEND $items MAKE()\n",
            lower_command,
        )
        .expect("parses");
        let StepKind::ListAppend { list, item } = &steps[1].kind else {
            panic!("expected ListAppend, got {:?}", steps[1].kind);
        };
        assert_eq!(list, "items");
        assert!(
            matches!(item, Arg::Expr(Expr::Call { name, .. }) if name == "SCRIPT::MAKE"),
            "{item:?}"
        );
    }

    #[test]
    fn list_append_rejects_unknown_call_shaped_item() {
        // Unknown callees fail loud (unknown-function, with span),
        // never silently append. Well-formed-statement errors win:
        // see `func_def_malformed_params_name_the_shape`.
        let err = parse_err("LIST_APPEND $items NOPE()\n");
        assert!(err.contains("unknown function `NOPE`"), "{err}");
    }

    #[test]
    fn list_append_rejects_wrong_arity() {
        for script in [
            "LIST_APPEND\n",
            "LIST_APPEND $items\n",
            "LIST_APPEND $items \"a\" \"b\"\n",
        ] {
            let err = parse_err(script);
            assert!(
                err.contains("invalid syntax for command LIST_APPEND"),
                "{script}: {err}"
            );
            assert!(!err.contains("unknown command"), "{script}: {err}");
        }
    }

    #[test]
    fn list_append_rejects_non_variable_target() {
        let err = parse_err("LIST_APPEND items \"a\"\n");
        assert!(
            err.contains("invalid syntax for command LIST_APPEND"),
            "{err}"
        );
        assert!(!err.contains("unknown command"), "{err}");
    }

    #[test]
    fn read_line_rejects_bare_word_target() {
        // The `$var` shape lives in the lower function now that the
        // central vocabulary holds value types only: a missing sigil
        // fails lowering with the command-specific error.
        let err = parse_err("READ_LINE reply\n");
        assert!(err.contains("READ_LINE requires a $variable"), "{err}");
        assert!(!err.contains("unknown command"), "{err}");
    }

    #[test]
    fn genuinely_unknown_command_keeps_bare_message() {
        let err = parse_err("FROBNICATE hi\n");
        assert!(err.contains("unknown command: FROBNICATE"), "{err}");
        assert!(!err.contains("did you mean"), "{err}");
    }

    #[test]
    fn lowercase_command_suggests_uppercase() {
        // Lowercase never reaches lowering through `parse_script` (the
        // grammar rejects it with its own uppercase hint), so exercise the
        // public `lower_command` dispatcher directly.
        let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
            .expect_err("must fail")
            .to_string();
        assert!(err.contains("unknown command: echo"), "{err}");
        assert!(err.contains("did you mean `ECHO`"), "{err}");
    }

    #[test]
    fn func_def_requires_typed_uppercase_name() {
        let steps = parse_script(
            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\n",
            lower_command,
        )
        .expect("func def parses");
        let StepKind::FuncDef {
            name,
            params,
            return_type,
            is_async,
            body,
            docs,
        } = &steps[0].kind
        else {
            panic!("expected FuncDef, got {:?}", steps[0].kind);
        };
        assert_eq!(name, "GREET");
        assert_eq!(
            params,
            &vec![("name".to_string(), "STRING".to_string(), false)],
            "{params:?}"
        );
        assert_eq!(return_type, "STRING", "{return_type:?}");
        assert!(!is_async, "plain FUNC is not async");
        assert!(matches!(body[0].kind, StepKind::Return { .. }));
        assert!(docs.is_none(), "undocumented FUNC carries no docs");
    }

    #[test]
    fn lowercase_func_name_is_rejected() {
        let err = parse_err("FUNC greet($x: STRING) {\n  RETURN $x\n}\n");
        assert!(err.contains("FUNC"), "{err}");
    }

    #[test]
    fn func_def_optional_params_parse_with_flag() {
        let steps = parse_script(
            "FUNC F($a: STRING, $b?: INT): STRING {\n  RETURN $a\n}\n",
            lower_command,
        )
        .expect("optional params parse");
        let StepKind::FuncDef { params, .. } = &steps[0].kind else {
            panic!("expected FuncDef, got {:?}", steps[0].kind);
        };
        assert_eq!(
            params,
            &vec![
                ("a".to_string(), "STRING".to_string(), false),
                ("b".to_string(), "INT".to_string(), true),
            ],
            "{params:?}"
        );
        assert_eq!(
            steps[0].kind.to_string(),
            "FUNC F($a: STRING, $b?: INT): STRING {\n    RETURN $a\n}",
            "display marks the optional"
        );
    }

    #[test]
    fn func_def_optional_params_must_trail() {
        let err = parse_err("FUNC F($a?: INT, $b: STRING): STRING {\n  RETURN $b\n}\n");
        assert!(err.contains("optional ? params must be trailing"), "{err}");
        assert!(err.contains("`$b`"), "{err}");
    }

    #[test]
    fn func_def_param_type_must_be_uppercase() {
        let err = parse_err("FUNC F($q: string): STRING {\n  RETURN $q\n}\n");
        assert!(err.contains("needs an uppercase type"), "{err}");
        assert!(err.contains("`string`"), "{err}");
    }

    #[test]
    fn func_def_malformed_params_name_the_shape() {
        for (script, expected) in [
            (
                "FUNC F($x?): STRING {\n  RETURN \"hi\"\n}\n",
                "needs `: TYPE` after the name",
            ),
            (
                "FUNC F(bar): STRING {\n  RETURN \"hi\"\n}\n",
                "must be `$name: TYPE` separated by commas",
            ),
            (
                "FUNC F($x: STRING,): STRING {\n  RETURN $x\n}\n",
                "must not end with a trailing comma",
            ),
        ] {
            let err = parse_err(script);
            assert!(err.contains(expected), "{script}: {err}");
        }
        // `FUNC FOO() ECHO hi` still misses to generic: the
        // header-only invalid syntax echoes just the header.
        let err = parse_err("FUNC FOO() ECHO hi\n");
        assert!(err.contains("invalid syntax for command FUNC"), "{err}");
        assert!(err.contains("got `FOO() ECHO hi`"), "{err}");
    }

    #[test]
    fn call_and_while_lower_correctly() {
        let steps = parse_script(
            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nGREET(\"ada\")\n",
            lower_command,
        )
        .expect("call parses");
        assert!(
            matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
            "{:?}",
            steps[1].kind
        );
        let steps = parse_script(
            "FUNC GREET($a: STRING, $b: STRING): STRING {\n  RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
            lower_command,
        )
        .expect("spaced call parses");
        assert!(
            matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
            "{:?}",
            steps[1].kind
        );
        let steps = parse_script(
            indoc! {r#"
                WHILE !$done {
                  BREAK
                }
            "#},
            lower_command,
        )
        .expect("while parses");
        let StepKind::While { body, .. } = &steps[0].kind else {
            panic!("expected While, got {:?}", steps[0].kind);
        };
        assert!(matches!(body[0].kind, StepKind::Break));
    }

    #[test]
    fn let_capture_call_and_async_call_lower() {
        // A bare `NAME(...)` on the LET RHS stays an expression assignment;
        // only ASYNC/TIMEOUT/command captures produce AssignCapture.
        let steps = parse_script(
            indoc! {r#"
                FUNC GREET($name: STRING): STRING {
                  RETURN $name
                }
                LET $r: STRING = GREET("ada")
            "#},
            lower_command,
        )
        .expect("capture call parses");
        let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
            panic!("expected Assign, got {:?}", steps[1].kind);
        };
        assert_eq!(var, "r");
        assert!(
            matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
            "{expr:?}"
        );
        let steps = parse_script(
            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nLET $t: HANDLE<STRING> = ASYNC GREET(\"a\")\n",
            lower_command,
        )
        .expect("async call parses");
        assert!(
            matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
            "{:?}",
            steps[1].kind
        );
    }

    #[test]
    fn multiline_call_args_span_lines() {
        // Regression: long invocations (e.g. 4-arg SSH_SERVE with an
        // options map) may put one argument per line. Bracket interiors
        // tolerate linebreaks while statement structure stays single-line.
        let steps = parse_script(
            "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP): STRING {\n  RETURN $b\n}\nLET $m: MAP = SERVE(\n  \"127.0.0.1:2241\",\n  \"test\",\n  \"test123\", {\n    key_path: \"test_key\"\n  }\n)\n",
            lower_command,
        )
        .expect("multiline call parses");
        let StepKind::Assign { expr, .. } = &steps[1].kind else {
            panic!("expected Assign, got {:?}", steps[1].kind);
        };
        let Expr::Call { name, args } = expr else {
            panic!("expected Call expr, got {expr:?}");
        };
        assert_eq!(name, "SCRIPT::SERVE");
        assert_eq!(args.len(), 4);
        assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
        // Display stays single-line; reparsing the same text is identical.
        let rendered = steps[1].to_string();
        assert!(!rendered.contains('\n'), "{rendered}");
        let script = "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP): STRING {\n  RETURN $b\n}\nLET $m: MAP = SERVE(\n  \"127.0.0.1:2241\",\n  \"test\",\n  \"test123\", {\n    key_path: \"test_key\"\n  }\n)\n";
        let again = parse_script(script, lower_command).expect("reparse ok");
        assert_eq!(again, steps);
    }

    #[test]
    fn multiline_bare_call_and_list_span_lines() {
        let steps = parse_script(
            indoc! {r#"
                FUNC GREET($a: STRING): STRING {
                  RETURN $a
                }
                GREET(
                  "ada"
                )
            "#},
            lower_command,
        )
        .expect("multiline bare call parses");
        let StepKind::Call { name, args } = &steps[1].kind else {
            panic!("expected Call, got {:?}", steps[1].kind);
        };
        assert_eq!(name, "SCRIPT::GREET");
        assert_eq!(args.len(), 1);
        let steps = parse_script(
            indoc! {r#"
                LET $l: LIST = [
                  "a",
                  "b"
                ]
            "#},
            lower_command,
        )
        .expect("multiline list parses");
        let StepKind::Assign { expr, .. } = &steps[0].kind else {
            panic!("expected Assign, got {:?}", steps[0].kind);
        };
        assert!(
            matches!(expr, Expr::List(items) if items.len() == 2),
            "{expr:?}"
        );
    }

    #[test]
    fn parse_duration_units() {
        use std::time::Duration;
        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
        assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
        assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
        // One optional space separates number from unit, like bytes.
        assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
        assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
    }

    #[test]
    fn parse_duration_rejects_garbage() {
        assert!(parse_duration("").is_err());
        assert!(parse_duration("banana").is_err());
        assert!(parse_duration("10x").is_err());
        assert!(parse_duration("0s").is_err());
        assert!(parse_duration("0").is_err());
        assert!(parse_duration("-5s").is_err());
        // Three parts or a split digit run stay rejected.
        assert!(parse_duration("30 s s").is_err());
        assert!(parse_duration("3 0s").is_err());
    }

    #[test]
    fn parse_byte_count_units() {
        assert_eq!(parse_byte_count("500").unwrap(), 500);
        assert_eq!(parse_byte_count("500B").unwrap(), 500);
        assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
        assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
        assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
        assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
        assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
        assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
        assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
        assert_eq!(
            parse_byte_count("1TIB").unwrap(),
            1_024 * 1_024 * 1_024 * 1_024
        );
        // Case-insensitive: `1gb`, `1GB`, and `1Gb` agree.
        assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
        assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
        assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
        assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
        // Rust-literal grouping: separators ride between digits only.
        assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
        assert_eq!(
            parse_byte_count("1_000_000_000_000").unwrap(),
            1_000_000_000_000
        );
        assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
        assert_eq!(
            parse_byte_count("1_0GiB").unwrap(),
            10 * 1_024 * 1_024 * 1_024
        );
        // One optional space separates number from unit, never digits.
        assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
        assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
        assert_eq!(parse_byte_count("  2MB  ").unwrap(), 2_000_000);
        // A leading `+` rides spaced or glued; `-` stays rejected.
        assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
        assert!(parse_byte_count("-1 GB").is_err());
    }

    #[test]
    fn parse_byte_count_rejects_garbage() {
        for bad in [
            "",
            "banana",
            "10x",
            "1G",
            "1K",
            "1.5GB",
            "-5",
            "-5GB",
            "0",
            "0GB",
            "_100",
            "100_",
            "1__000",
            "_",
            "1_GB",
            // A space splits tokens, never digit runs or units.
            "1 G B",
            "1 2",
            "1 0",
            // Absurd magnitudes fail loudly instead of wrapping.
            "1000000000000000000000000",
            "1000000000TB",
        ] {
            assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
        }
    }

    #[test]
    fn format_byte_count_round_trips() {
        for text in [
            "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
        ] {
            let parsed = parse_byte_count(text).unwrap();
            let rendered = format_byte_count(parsed);
            assert_eq!(
                parse_byte_count(&rendered).unwrap(),
                parsed,
                "round-trip failed for {text}"
            );
        }
        assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
        assert_eq!(format_byte_count(1_000_000_000), "1GB");
    }

    #[test]
    fn strip_digit_separators_passes_signs_through() {
        // Signs belong to signed domains: the strip keeps them so
        // `-1_000` reads as -1000 wherever ints coerce, while unsigned
        // callers (byte counts) still reject at parse time.
        assert_eq!(strip_digit_separators("-1_000"), "-1000");
        assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
        assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
        assert_eq!(strip_digit_separators("1_000"), "1000");
        for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
            assert_eq!(strip_digit_separators(untouched), untouched);
        }
        // Unsigned byte counts reject `-` at parse time but take `+`
        // like every other Rust-parsed number in the DSL.
        assert!(parse_byte_count("-1_000").is_err());
        assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
    }

    #[test]
    fn format_byte_count_is_lossless() {
        // The canonical form parses back to the exact input value:
        // formatting never loses information, only spelling.
        // Zero is unrepresentable by design (like durations): the
        // parser rejects it, so it cannot round-trip.
        for n in [
            1,
            500,
            999,
            1_000,
            1_024,
            1_500,
            1_000_000,
            1_048_576,
            1_000_000_000,
            1_073_741_824,
            1_000_000_000_000,
            1_099_511_627_776,
            u64::MAX,
        ] {
            assert_eq!(
                parse_byte_count(&format_byte_count(n)).unwrap(),
                n,
                "lossless round-trip failed for {n}"
            );
        }
    }

    #[test]
    fn format_duration_round_trips() {
        for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
            let parsed = parse_duration(text).unwrap();
            let rendered = format_duration(&parsed);
            assert_eq!(
                parse_duration(&rendered).unwrap(),
                parsed,
                "round-trip failed for {text}"
            );
        }
        assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
        assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
    }

    #[test]
    fn structural_metadata_covers_all_structural_kinds() {
        use crate::ast::Value;

        // Tripwire: adding a structural StepKind variant without registering
        // documentation fails to compile here (non-exhaustive match). Leaf
        // commands map to None; they are covered by declare_commands!.
        fn metadata_name(kind: &StepKind) -> Option<&'static str> {
            match kind {
                StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
                StepKind::For { .. } => Some("FOR"),
                StepKind::If { .. } => Some("IF"),
                StepKind::Assign { .. } => Some("LET"),
                StepKind::Set { .. } => Some("MUTATION"),
                StepKind::AssignCapture { .. } => Some("LET"),
                StepKind::AwaitCapture { .. } => Some("AWAIT"),
                StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
                StepKind::Await { .. } => Some("AWAIT"),
                StepKind::Cancel { .. } => Some("CANCEL"),
                StepKind::Timeout { .. } => Some("TIMEOUT"),
                StepKind::Isolated { .. } => Some("ISOLATED"),
                StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
                StepKind::RemoteBlock { .. } => Some("REMOTE"),
                StepKind::FuncDef { .. } => Some("FUNC"),
                // Bare `NAME(...)` calls share the `FUNC` reference page;
                // there is no call keyword to document on its own.
                StepKind::Call { .. } => None,
                // Both import forms are documented on the `IMPORT` page.
                StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => Some("IMPORT"),
                StepKind::Return { .. } => Some("RETURN"),
                StepKind::While { .. } => Some("WHILE"),
                StepKind::Break => Some("BREAK"),
                StepKind::Continue => Some("CONTINUE"),
                // Aliases are declared by `TYPE` but documented with the
                // type-word prose on the `LET` page (define-once,
                // use-everywhere); no dedicated reference page.
                StepKind::TypeAlias { .. } => Some("LET"),
                StepKind::RunExec { .. } => None,
                StepKind::Workdir(_)
                | StepKind::Workspace(_)
                | StepKind::Env { .. }
                | StepKind::InheritEnv { .. }
                | StepKind::Run(_)
                | StepKind::Echo(_)
                | StepKind::Copy { .. }
                | StepKind::Symlink { .. }
                | StepKind::Mkdir(_)
                | StepKind::Archive { .. }
                | StepKind::Unarchive { .. }
                | StepKind::Install { .. }
                | StepKind::SetExecutable { .. }
                | StepKind::Ls(_)
                | StepKind::Read(_)
                | StepKind::ReadLine { .. }
                | StepKind::Prompt { .. }
                | StepKind::Write { .. }
                | StepKind::Append { .. }
                | StepKind::AppendLine { .. }
                | StepKind::Remove { .. }
                | StepKind::Expand { .. }
                | StepKind::AssertEq { .. }
                | StepKind::AssertContains { .. }
                | StepKind::AssertNe { .. }
                | StepKind::CopyGit { .. }
                | StepKind::Exit(_)
                | StepKind::Sleep { .. }
                | StepKind::ListAppend { .. } => None,
            }
        }

        // Exercise the matcher once per structural variant so the arms cannot
        // rot (a new variant breaks compilation above first).
        let dummies: Vec<StepKind> = vec![
            StepKind::WithIo {
                bindings: Vec::new(),
                cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
                    "x".to_string(),
                    false,
                ))),
            },
            StepKind::For {
                key_var: None,
                key_type: None,
                var: "i".to_string(),
                var_type: "STRING".to_string(),
                in_expr: Expr::Literal(Value::bool(true)),
                body: Vec::new(),
            },
            StepKind::If {
                cond: Box::new(Expr::Literal(Value::bool(true))),
                then_body: Vec::new(),
                else_ifs: Vec::new(),
                else_body: None,
            },
            StepKind::Assign {
                var: "v".to_string(),
                decl_type: "BOOL".to_string(),
                expr: Expr::Literal(Value::bool(true)),
            },
            StepKind::Set {
                var: "v".to_string(),
                expr: Expr::Literal(Value::bool(true)),
            },
            StepKind::AssignCapture {
                var: "v".to_string(),
                decl_type: "STRING".to_string(),
                cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
                    "x".to_string(),
                    false,
                ))),
            },
            StepKind::AwaitCapture {
                out_var: "o".to_string(),
                out_type: "STRING".to_string(),
                task_var: "t".to_string(),
            },
            StepKind::AsyncBlock { body: Vec::new() },
            StepKind::AssignAsync {
                var: "t".to_string(),
                decl_type: "HANDLE".to_string(),
                body: Vec::new(),
            },
            StepKind::Await {
                var: "t".to_string(),
            },
            StepKind::Cancel {
                var: "t".to_string(),
            },
            StepKind::Timeout {
                duration: Arg::String("1s".to_string(), false),
                body: Vec::new(),
            },
            StepKind::Isolated { body: Vec::new() },
            StepKind::IsolatedInheritEnv { keys: Vec::new() },
            StepKind::RemoteBlock {
                target: "prod".to_string(),
                vars: Vec::new(),
                env: Vec::new(),
                body: Vec::new(),
            },
            StepKind::FuncDef {
                name: "F".to_string(),
                params: Vec::new(),
                return_type: "STRING".to_string(),
                is_async: false,
                body: Vec::new(),
                docs: None,
            },
            StepKind::Call {
                name: "F".to_string(),
                args: Vec::new(),
            },
            StepKind::Return {
                expr: Box::new(Expr::Literal(Value::bool(true))),
                is_bare: false,
            },
            StepKind::While {
                cond: Box::new(Expr::Literal(Value::bool(true))),
                body: Vec::new(),
            },
            StepKind::Break,
            StepKind::Continue,
            StepKind::TypeAlias {
                name: "PERSON".to_string(),
                target: "MAP<name: STRING>".to_string(),
            },
        ];
        let registry = all_structural_metadata();
        for kind in &dummies {
            // Bare calls share the FUNC reference page and map to None.
            let Some(name) = metadata_name(kind) else {
                continue;
            };
            assert!(
                registry.iter().any(|meta| meta.name == name),
                "no structural metadata entry for {}",
                name
            );
        }
    }
}