oxdock-core 0.40.0-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
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
use anyhow::{Context, Result, anyhow, bail};
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};

use flate2::Compression;
use flate2::write::GzEncoder;
use oxdock_fs::CopySourceRoot;
use oxdock_fs::EXECUTABLE_MODE;
use oxdock_fs::EntryKind;
use oxdock_fs::GuardedPath;
use oxdock_fs::PathResolver;
use oxdock_fs::PolicyPath;
use oxdock_fs::command_path;
use oxdock_fs::to_forward_slashes;
use oxdock_parser::{
    Arg, Command, Expr, IoBinding, IoStream, PipeTarget, Step, StepKind, TypeTag, Value,
    WorkspaceTarget, render_structural,
};
use oxdock_process::{
    BackgroundHandle, CommandOptions, CommandResult, CommandStderr, CommandStdin, CommandStdout,
    INHERIT_STDOUT_ENV_VAR, PROCESS_DEBUG_ENV_VAR, ProcessManager, SharedInput, batch_shell,
    check_spawn_anchors, read_pump_chunk,
};
use oxdock_pty::{PtyInput, PtyOutcome, PtyRequest, WatchSize, run_pty_session};
use oxdock_utils::sha256_hex;
use oxdock_utils::tar::{StreamedEntry, sanitize_rel, unpack_auto_from};

use super::args::parse_bool_str;
use super::fs_ops::copy_entry;
use super::io::{StreamHandle, TaskTee, TeeStream, write_stdout};
use super::native::FuncBody;
use super::state::{ExecState, MAX_CALL_DEPTH, TaskPhase};
use super::steps::{Flow, StepCtx, TtyRequest};
use oxdock_pipe::{KeeperGuard, PipeHandle, PipeInner, SharedOutput};

/// Map a Flow reaching a context-free boundary (pipeline top, thread join)
/// into status. Only Done passes; anything else is a step-numbered error
/// naming the originating step in its own body.
fn top_level_flow(flow: Flow) -> Result<()> {
    match flow {
        Flow::Done => Ok(()),
        Flow::Break { idx } => {
            bail!("step {}: BREAK outside loop", idx + 1);
        }
        Flow::Continue { idx } => {
            bail!("step {}: CONTINUE outside loop", idx + 1);
        }
        Flow::Return { idx, .. } => {
            bail!(
                "step {}: RETURN outside function, ASYNC task, or LET block",
                idx + 1
            );
        }
    }
}

pub(super) fn inherit_env<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    keys: &[String],
) -> Result<()> {
    let mut removals: Vec<String> = Vec::new();
    let mut inserts: Vec<(String, String)> = Vec::new();
    for key in keys {
        if cx.state.io.inherit_env_is_removed(key) {
            removals.push(key.clone());
            continue;
        }
        if let Some(value) = cx.state.io.inherit_env_value(key).cloned() {
            inserts.push((key.clone(), value));
            continue;
        }
        if let Ok(value) = std::env::var(key) {
            inserts.push((key.clone(), value));
        }
    }
    let envs = Arc::make_mut(&mut cx.state.envs);
    for key in removals {
        envs.remove(&key);
    }
    for (key, value) in inserts {
        envs.insert(key, value);
    }
    Ok(())
}

pub(super) fn workdir<P: ProcessManager>(cx: &mut StepCtx<'_, P>, path: &str) -> Result<()> {
    cx.state.cwd = cx
        .state
        .fs
        .resolve_workdir(&cx.state.cwd, path)
        .with_context(|| format!("WORKDIR {}", path))?;
    Ok(())
}

pub(super) fn workspace<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    target: &WorkspaceTarget,
) -> Result<()> {
    // Selection only, no disk I/O. The snapshot side stays pending until the
    // first snapshot-targeted choke point materializes it (issue #131).
    // CACHE ensures its persistent directory on first cache-targeted use
    // and never deletes it; SYSTEM bypasses containment. SYSTEM keeps the
    // current working directory (rebased off the never-created snapshot
    // anchor when needed) so relative paths keep working from where the
    // script already was (issue #163).
    match target {
        WorkspaceTarget::Snapshot => {
            cx.state.fs.switch_to_snapshot();
            cx.state.cwd = cx.state.fs.root().clone();
        }
        WorkspaceTarget::Local => {
            cx.state.fs.switch_to_local();
            cx.state.cwd = cx.state.fs.root().clone();
        }
        WorkspaceTarget::Cache { local } => {
            cx.state.fs.switch_to_cache(*local);
            cx.state.cwd = cx.state.fs.root().clone();
        }
        WorkspaceTarget::System => {
            cx.state.fs.switch_to_system();
            let cwd = cx.state.cwd.clone();
            cx.state.cwd = cx.state.fs.system_entry_cwd(&cwd);
        }
    }
    Ok(())
}

pub(super) fn env<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    key: &str,
    value: &str,
) -> Result<()> {
    Arc::make_mut(&mut cx.state.envs).insert(key.to_owned(), value.to_owned());
    Ok(())
}

pub(super) fn run<P: ProcessManager>(cx: &mut StepCtx<'_, P>, cmd: &str) -> Result<()> {
    // Terminal steps spawn through the shared pty pump instead of the
    // process manager; everything else below stays hermetic pipes.
    if let Some(tty) = cx.tty {
        return run_pty(cx, &tty_shell_argv(cmd), tty, cmd, true);
    }
    let ctx = cx.state.command_ctx()?;
    let step_stdin = if cx.expose_stdin {
        cx.stdin.clone()
    } else {
        CommandStdin::Null
    };

    let inherit_override = cx
        .state
        .envs
        .get(INHERIT_STDOUT_ENV_VAR)
        .map(|v| parse_bool_str(v).unwrap_or(false))
        .unwrap_or(false);

    if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
        eprintln!(
            "DEBUG: step RUN {} inherit_override={}",
            cmd, inherit_override
        );
    }

    let stdout_mode = if inherit_override {
        CommandStdout::Inherit
    } else {
        cx.out
            .clone()
            .map(|handle| handle.to_stdout())
            .unwrap_or(CommandStdout::Inherit)
    };
    let stderr_mode = if inherit_override {
        CommandStderr::Inherit
    } else {
        cx.err
            .clone()
            .map(|handle| handle.to_stderr())
            .unwrap_or(CommandStderr::Inherit)
    };

    let mut options = if cx.state.inside_async || cx.state.cancellable {
        // Inside an ASYNC block : use background mode so we can register
        // the handle for cancellation via active_process.
        CommandOptions::background()
    } else {
        CommandOptions::foreground()
    };
    options.stdin = step_stdin;
    options.stdout = stdout_mode;
    options.stderr = stderr_mode;

    // A teardown that won the race already set cancellation: spawning
    // now would create an unkillable-by-teardown child (the killer
    // found nothing registered and moved on to joining), so refuse
    // before the spawn instead of after the wait.
    {
        use std::sync::atomic::Ordering;
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            bail!("RUN {} interrupted by cancellation", cmd);
        }
    }

    // Spawn the command.
    let mut handle = match cx
        .process
        .spawn_command(&ctx, cmd, options)
        .with_context(|| format!("RUN {}", cmd))?
    {
        CommandResult::Background(h) => h,
        CommandResult::Completed => return Ok(()),
        CommandResult::Captured(_) => {
            bail!("RUN {} unexpectedly captured output", cmd)
        }
    };

    // Register the handle for cancellation (only meaningful for background handles).
    {
        let mut guard = cx
            .state
            .active_process
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        *guard = Some(Box::new(handle.clone()));
    }

    // Cancellation landing between spawn and registration would miss
    // this handle the same way: re-check now that registration is
    // visible, killing our own handle (double-kill safe: reaped PIDs
    // zero out) instead of waiting out the child.
    {
        use std::sync::atomic::Ordering;
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            let _ = handle.kill();
            bail!("RUN {} interrupted by cancellation", cmd);
        }
    }

    // Wait for the process to complete.
    let status = handle.wait();

    // Clear the registration BEFORE dropping the handle clone in active_process.
    // The clone was never polled, so we must prevent Drop from logging it as killed.
    {
        let mut guard = cx
            .state
            .active_process
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        *guard = None;
    }

    let status = status?;
    if !status.success() {
        bail!("RUN {} exited with status {}", cmd, status);
    }
    Ok(())
}

/// Direct-spawn counterpart of [`run`]: executes an already-resolved `argv`
/// without any shell (`RUN ["exe", "arg", ...]`). `CommandContext` and
/// `CommandOptions` (cwd/env, `WITH_IO` pipes, `ASYNC`/cancellable
/// backgrounding, [`INHERIT_STDOUT_ENV_VAR`]) are built exactly like [`run`];
/// only the spawn call differs (`spawn_argv`, no `shell_cmd`).
pub(super) fn run_argv<P: ProcessManager>(cx: &mut StepCtx<'_, P>, argv: &[String]) -> Result<()> {
    // Terminal steps spawn through the shared pty pump instead of the
    // process manager; everything else below stays hermetic pipes.
    if let Some(tty) = cx.tty {
        let what = format!("{argv:?}");
        return run_pty(cx, argv, tty, &what, false);
    }
    let ctx = cx.state.command_ctx()?;
    let step_stdin = if cx.expose_stdin {
        cx.stdin.clone()
    } else {
        CommandStdin::Null
    };

    let inherit_override = cx
        .state
        .envs
        .get(INHERIT_STDOUT_ENV_VAR)
        .map(|v| parse_bool_str(v).unwrap_or(false))
        .unwrap_or(false);

    if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
        eprintln!(
            "DEBUG: step RUN {:?} inherit_override={}",
            argv, inherit_override
        );
    }

    let stdout_mode = if inherit_override {
        CommandStdout::Inherit
    } else {
        cx.out
            .clone()
            .map(|handle| handle.to_stdout())
            .unwrap_or(CommandStdout::Inherit)
    };
    let stderr_mode = if inherit_override {
        CommandStderr::Inherit
    } else {
        cx.err
            .clone()
            .map(|handle| handle.to_stderr())
            .unwrap_or(CommandStderr::Inherit)
    };

    let mut options = if cx.state.inside_async || cx.state.cancellable {
        // Inside an ASYNC block : use background mode so we can register
        // the handle for cancellation via active_process.
        CommandOptions::background()
    } else {
        CommandOptions::foreground()
    };
    options.stdin = step_stdin;
    options.stdout = stdout_mode;
    options.stderr = stderr_mode;

    // Same pre-spawn cancellation refusal as [`run`]: a teardown that
    // already ran must not gain a child it can no longer see.
    {
        use std::sync::atomic::Ordering;
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            bail!("RUN {argv:?} interrupted by cancellation");
        }
    }

    // Spawn the executable directly (no shell).
    let mut handle = match cx
        .process
        .spawn_argv(&ctx, argv, options)
        .with_context(|| format!("RUN {argv:?}"))?
    {
        CommandResult::Background(h) => h,
        CommandResult::Completed => return Ok(()),
        CommandResult::Captured(_) => {
            bail!("RUN {argv:?} unexpectedly captured output",)
        }
    };

    // Register the handle for cancellation (only meaningful for background handles).
    {
        let mut guard = cx
            .state
            .active_process
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        *guard = Some(Box::new(handle.clone()));
    }

    // Same post-registration re-check as [`run`].
    {
        use std::sync::atomic::Ordering;
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            let _ = handle.kill();
            bail!("RUN {argv:?} interrupted by cancellation");
        }
    }

    // Wait for the process to complete.
    let status = handle.wait();

    // Clear the registration BEFORE dropping the handle clone in active_process.
    // The clone was never polled, so we must prevent Drop from logging it as killed.
    {
        let mut guard = cx
            .state
            .active_process
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        *guard = None;
    }

    let status = status?;
    if !status.success() {
        bail!("RUN {argv:?} exited with status {}", status);
    }
    Ok(())
}

/// Pseudo-terminal counterpart of [`run`]/[`run_argv`]: spawns `argv`
/// under a pty through the shared pump instead of the process manager,
/// blocking the step like any `RUN` until the child exits and its
/// output drains.
///
/// The terminal request rides `cx.tty` (populated only by `with_io`
/// from `[tty]` bindings); every other path keeps hermetic pipes. The
/// master is one interleaved stream: it lands exclusively in the step
/// stdout sink, stdin flows from a `stdin = $p` script pipe or from
/// the host terminal itself when stdin is a real one (bare `[tty]`
/// headless stays closed), and cancellation kills the child through
/// the pump's own path before reporting like any interrupted `RUN`.
/// Environment, anchors, and working directory mirror [`run_argv`]
/// exactly: closed child env from the script map, the same anchor
/// pre-flight the native spawn runs (`shell` selects the shell-form
/// `PATH` requirement), the same snapshot-choked cwd. `what` renders
/// the step in errors exactly like the calling form.
#[allow(clippy::too_many_arguments)]
fn run_pty<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    argv: &[String],
    tty: TtyRequest,
    what: &str,
    shell: bool,
) -> Result<()> {
    use std::sync::atomic::Ordering;
    if argv.is_empty() {
        bail!("RUN {what} needs at least a program");
    }
    // Same pre-spawn cancellation refusal as [`run`].
    if cx.state.cancel_token.load(Ordering::SeqCst) {
        bail!("RUN {what} interrupted by cancellation");
    }
    if std::env::var(PROCESS_DEBUG_ENV_VAR).is_ok() {
        eprintln!("DEBUG: step RUN {what} under tty {tty:?}");
    }
    // Closed child env from the script map, staged verbatim after the
    // same anchor pre-flight the native spawn runs inside `apply_ctx`.
    let ctx = cx.state.command_ctx()?;
    let staged = ctx.envs().as_ref().clone();
    check_spawn_anchors(&argv[0], &staged, shell)?;
    let cwd = match ctx.cwd() {
        PolicyPath::Guarded(p) => command_path(p).to_string_lossy().into_owned(),
        PolicyPath::Unguarded(p) => p.as_path().to_string_lossy().into_owned(),
    };
    // Stdin feeds the master from a `stdin = $p` script pipe, or from
    // the host terminal itself when stdin is a real one: the backend
    // behind a pipe carries the wake hook that releases a worker
    // parked in a blocking read when the child dies, and the host
    // reader carries its own teardown flag plus a console unblock,
    // so neither strands the session. Anything else (bare `[tty]`
    // headless, ambient inheritance off-terminal, unwakeable
    // descriptors) runs closed instead of stranding the session on
    // a worker that can never observe exit.
    let input = match &cx.stdin {
        CommandStdin::Null | CommandStdin::Inherit
            if !cx.process.stdin_is_terminal() || cx.stdin.is_redirected() =>
        {
            None
        }
        CommandStdin::Null | CommandStdin::Inherit => oxdock_pty::acquire_host_stdin(),
        CommandStdin::Stream(reader) => match cx.stdin_pipe.clone() {
            Some(backend) => {
                let reader = reader.clone();
                Some(PtyInput {
                    read_chunk: Box::new(move |buf| read_pump_chunk(&reader, buf)),
                    cancel: Box::new(move || {
                        backend.cancel();
                    }),
                })
            }
            None => None,
        },
        #[cfg(not(miri))]
        CommandStdin::OsPipe(_) => {
            bail!(
                "WITH_IO [tty] stdin cannot arrive on a live OS pipe; bind a script pipe with stdin=$var"
            )
        }
    };
    // Master output lands exclusively in the step stdout sink. `None`
    // inherits host stdout, matching `write_stdout`; a live OS handle
    // is unreachable (terminal stdio resolves bridged), so it stays a
    // defensive bail like the DSL writers.
    let output: SharedOutput = match &cx.out {
        Some(StreamHandle::Stream(writer)) => writer.clone(),
        None => Arc::new(Mutex::new(std::io::stdout())),
        #[cfg(not(miri))]
        Some(StreamHandle::Os(_)) => {
            bail!(
                "WITH_IO [tty] stdout cannot arrive on a live OS pipe; bind a script pipe with stdout=$var"
            )
        }
    };
    let hub = cx.cancel_hub();
    let token = cx.cancel_token();
    // Geometry resolves here, at spawn: unnamed sides read the host
    // terminal behind our own stdio, so the pty matches the window
    // the author actually sees, not a stale parse-time guess. The
    // size cell keeps following the host while the step runs, so a
    // mid-run resize reaches the child through the normal watcher.
    let size = oxdock_pty::resolve_size(tty.rows, tty.cols);
    let outcome = run_pty_session(PtyRequest {
        argv: argv.to_vec(),
        env: staged.into_iter().collect(),
        cwd,
        initial_size: size,
        input,
        output,
        size_source: WatchSize::following_host(tty.rows, tty.cols),
        should_cancel: Box::new(move || hub.is_cancelled() || token.load(Ordering::SeqCst)),
        on_exit: None,
        on_output_drained: None,
        func: "RUN",
    })
    .with_context(|| format!("RUN {what}"))?;
    // Pipe EOF rides the writer drops like any `RUN`: the supervisor
    // returns only after the output worker finished, so every byte is
    // already in the sink before the code below runs.
    match outcome {
        PtyOutcome::Completed(code) => {
            if code != 0 {
                bail!("RUN {what} exited with status {code}");
            }
            Ok(())
        }
        PtyOutcome::Cancelled => {
            bail!("RUN {what} interrupted by cancellation");
        }
    }
}

/// Shell-form argv for a terminal spawn: the same deterministic batch
/// shell the native spawn runs (`sh -c` / `cmd /C`), so shell steps
/// read identically under pipes and under a pty.
fn tty_shell_argv(cmd: &str) -> Vec<String> {
    #[allow(clippy::disallowed_macros)]
    let flag = if cfg!(windows) { "/C" } else { "-c" };
    vec![batch_shell(), flag.to_string(), cmd.to_string()]
}

/// Resolve exec-form (`RUN [...]`) argv elements with explicit coercion:
/// `Arg::String`/`Arg::Parts` resolve to exactly one entry each;
/// `Arg::Expr` evaluates and coerces by value : `String`/`Int`/`Bool` push
/// one entry, `List` flattens recursively (each scalar becomes its own
/// entry), `Map`/`TaskHandle` bail with a type error.
/// Template expansion applies strictly to script-literal source text
/// (`Arg::String`/`Arg::Parts` via `resolve_arg`, string literals inline
/// below). Evaluated runtime values are opaque data and are never
/// re-expanded: a variable holding `{{ ... }}` text passes through
/// verbatim instead of leaking a second expansion pass.
/// Never uses shell joining or `expand_dsl_vars`.
pub(super) fn resolve_run_exec_argv<P: ProcessManager>(
    argv: &[Arg],
    cx: &mut StepCtx<'_, P>,
) -> Result<Vec<String>> {
    let mut out = Vec::new();
    for arg in argv {
        match arg {
            Arg::String(_, _) | Arg::Parts(_) => {
                out.push(super::args::resolve_arg(arg, cx)?);
            }
            Arg::Expr(Expr::Literal(v)) if v.as_str().is_some() => {
                let s = v.as_str().unwrap_or_default().to_string();
                out.push(super::args::expand_string(&s, &cx.state.envs, cx.state)?);
            }
            Arg::Expr(e) => {
                let val = super::args::evaluate_expr(e, cx)?;
                flatten_exec_value(&val, &mut out)?;
            }
        }
    }
    if out.is_empty() {
        bail!("RUN exec form requires at least one argument");
    }
    Ok(out)
}

fn flatten_exec_value(val: &Value, out: &mut Vec<String>) -> Result<()> {
    if let Some(s) = val.as_str() {
        out.push(s.to_string());
        return Ok(());
    }
    if let Some(i) = val.as_i64() {
        out.push(i.to_string());
        return Ok(());
    }
    if let Some(f) = val.as_f64() {
        out.push(f.to_string());
        return Ok(());
    }
    if let Some(b) = val.as_bool() {
        out.push(b.to_string());
        return Ok(());
    }
    if val.as_pipe_handle().is_some() {
        // A pipe in argv position is always a bug: a child process
        // cannot receive a handle as an argument string.
        anyhow::bail!(
            "cannot pass PIPE as a command argument: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
        );
    }
    if val.as_semaphore().is_some() {
        anyhow::bail!(
            "cannot pass SEMAPHORE as a command argument: semaphores coordinate task access between steps, not text."
        );
    }
    if val.as_permit().is_some() {
        anyhow::bail!(
            "cannot pass PERMIT as a command argument: permits grant scoped task access, not text."
        );
    }
    if let Some(d) = val.as_duration() {
        out.push(oxdock_parser::command::format_duration(&d));
        return Ok(());
    }
    if let Some(p) = val.as_path() {
        out.push(p.to_string_lossy().to_string());
        return Ok(());
    }
    if let Some(items) = val.as_list() {
        for item in items {
            flatten_exec_value(item, out)?;
        }
        return Ok(());
    }
    if val.as_map().is_some() {
        bail!("RUN exec form element must be a string, got map");
    }
    if let Some(id) = val.as_handle() {
        bail!("RUN exec form element must be a string, got task handle task#{id}");
    }
    // Every other type stringifies through its descriptor rendering
    // (host values through their `Display`).
    out.push(format!("{val}"));
    Ok(())
}

pub(super) fn echo<P: ProcessManager>(cx: &mut StepCtx<'_, P>, msg: &str) -> Result<()> {
    // One formatted write, not `writeln!`: the formatting machinery
    // emits the text and the newline as separate writes, and each one
    // re-locks the shared parent behind task tees, so concurrent
    // tasks interleave mid-line ("worker 0worker 1"). A single
    // `write_all` keeps every backend's synchronous completion as one
    // atomic line.
    let line = format!("{msg}\n");
    write_stdout(cx.out.clone(), |writer| {
        writer.write_all(line.as_bytes())?;
        Ok(())
    })?;
    Ok(())
}

/// Pipeline dispatch wrapper for `Sleep`
pub(crate) fn dispatch_sleep_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Sleep { duration } = step else {
        unreachable!()
    };
    let duration = super::args::resolve_arg_as_duration(duration, cx)?;
    sleep(cx, &duration)
}

/// Dispatch `SLEEP <duration>` : park the step without spawning a shell.
///
/// Cooperative: sleeps in bounded chunks and checks the cancellation token
/// between chunks, so an enclosing `TIMEOUT` deadline or parent task teardown
/// interrupts the sleep promptly. Never blocks on the full duration at once.
pub(crate) fn sleep<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    duration: &std::time::Duration,
) -> Result<()> {
    use std::sync::atomic::Ordering;
    use std::time::{Duration, Instant};

    let start = Instant::now();
    loop {
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            bail!("SLEEP interrupted by cancellation");
        }
        let elapsed = start.elapsed();
        if elapsed >= *duration {
            return Ok(());
        }
        let remaining = duration.saturating_sub(elapsed);
        std::thread::sleep(remaining.min(Duration::from_millis(10)));
    }
}

/// Map a `COPY --from-workspace` target onto the filesystem layer's source
/// root (issue #163). The parser owns the DSL vocabulary; `oxdock-fs`
/// stays a leaf crate, so the translation lives here. Shared with the
/// remote fetch resolver, which honors the same flag on `--from-host`.
pub(super) fn copy_source_root(target: WorkspaceTarget) -> CopySourceRoot {
    match target {
        WorkspaceTarget::Snapshot => CopySourceRoot::Snapshot,
        WorkspaceTarget::Local => CopySourceRoot::Local,
        WorkspaceTarget::Cache { .. } => CopySourceRoot::Cache,
        WorkspaceTarget::System => CopySourceRoot::System,
    }
}

pub(super) fn copy<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    from_workspace: Option<WorkspaceTarget>,
    from: &str,
    to: &str,
) -> Result<()> {
    let from_abs = if let Some(target) = from_workspace {
        cx.state
            .fs
            .resolve_copy_source_from_target(copy_source_root(target), from)
            .with_context(|| format!("COPY {} {}", from, to))?
    } else {
        cx.state
            .fs
            .resolve_copy_source(from)
            .with_context(|| format!("COPY {} {}", from, to))?
    };
    let to_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, to)
        .with_context(|| format!("COPY {} {}", from, to))?;
    let to_abs = place_file_in_dir(cx.state.fs.as_ref(), &from_abs, to, &to_abs)
        .with_context(|| format!("COPY {} {}", from, to))?;
    copy_entry(cx.state.fs.as_ref(), &from_abs, &to_abs)
        .with_context(|| format!("COPY {} {}", from, to))?;
    Ok(())
}

/// Docker destination semantics for file sources: when the destination
/// names a directory (an existing one, or a trailing-slash spell), the
/// file lands inside it under its own basename (`COPY file dir/`).
/// Directory sources already copy their contents into the destination,
/// and plain file paths keep the rename behavior. Returns the
/// (possibly rebased) destination guard.
fn place_file_in_dir(
    fs: &dyn oxdock_fs::WorkspaceFs,
    from_abs: &GuardedPath,
    to: &str,
    to_abs: &GuardedPath,
) -> Result<GuardedPath> {
    if !matches!(fs.entry_kind(from_abs), Ok(EntryKind::File)) {
        return Ok(to_abs.clone());
    }
    let trailing_slash = to.ends_with('/') || to.ends_with('\\');
    let dst_is_dir = matches!(fs.entry_kind(to_abs), Ok(EntryKind::Dir));
    if !trailing_slash && !dst_is_dir {
        return Ok(to_abs.clone());
    }
    let base = from_abs
        .as_path()
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .with_context(|| format!("COPY source has no file name: {}", from_abs.display()))?;
    to_abs
        .join(&base)
        .with_context(|| format!("COPY destination escapes root: {}", to_abs.display()))
}

#[allow(clippy::too_many_arguments)]
pub(super) fn copy_git<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    rev: &str,
    from: &str,
    to: &str,
    include_dirty: bool,
) -> Result<()> {
    let to_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, to)
        .with_context(|| format!("COPY_GIT {} {} {}", rev, from, to))?;
    cx.state
        .fs
        .copy_from_git(rev, from, &to_abs, include_dirty)
        .with_context(|| format!("COPY_GIT {} {} {}", rev, from, to))?;
    Ok(())
}

/// Resolve an archive source with a symlink refusal: canonical
/// resolution routes through the final link, so the resolved guard alone
/// cannot see it. The parent resolves normally (intermediate links stay
/// contained); the final name is matched against the parent's own
/// listing, whose file types never follow links. Matching is
/// case-insensitive so case-insensitive filesystems probe the entry the
/// resolve would actually open; any link among the matches refuses.
fn resolve_archive_src<P: ProcessManager>(
    cx: &StepCtx<'_, P>,
    src: &str,
    tag: &str,
) -> Result<GuardedPath> {
    let trimmed = to_forward_slashes(src).trim_end_matches('/').to_string();
    // A leading slash roots the parent at `/` itself: without the
    // index-zero arm `/foo` would split into parent `""` and resolve
    // against the working directory instead of the root.
    let (parent, name) = match trimmed.rfind('/') {
        Some(0) => ("/".to_string(), trimmed[1..].to_string()),
        Some(idx) => (trimmed[..idx].to_string(), trimmed[idx + 1..].to_string()),
        None => (String::new(), trimmed),
    };
    if name.is_empty() || name == "." || name == ".." {
        // Root-ish spellings carry no final component to probe: a root
        // is never a link itself.
        return cx
            .state
            .fs
            .resolve_read(&cx.state.cwd, src)
            .with_context(|| tag.to_string());
    }
    let parent_abs = if parent.is_empty() {
        cx.state.cwd.clone()
    } else {
        cx.state
            .fs
            .resolve_read(&cx.state.cwd, &parent)
            .with_context(|| tag.to_string())?
    };
    let mut matched = false;
    for entry in cx
        .state
        .fs
        .read_dir_entries(&parent_abs)
        .with_context(|| tag.to_string())?
    {
        if entry
            .file_name()
            .to_string_lossy()
            .eq_ignore_ascii_case(&name)
        {
            matched = true;
            let is_link = entry
                .file_type()
                .map(|kind| kind.is_symlink())
                .unwrap_or(true);
            if is_link {
                bail!("{tag}: refuses to pack symlink source {src:?}");
            }
        }
    }
    if !matched {
        // Genuinely missing: let the resolver report it authoritatively.
        return cx
            .state
            .fs
            .resolve_read(&cx.state.cwd, src)
            .with_context(|| tag.to_string());
    }
    parent_abs.join(&name).with_context(|| tag.to_string())
}

/// Collected packable tree: `(rel, guard)` files plus `(rel, guard)`
/// dirs, all forward-slash relative and sorted for deterministic
/// archives.
type ArchiveTree = (Vec<(String, GuardedPath)>, Vec<(String, GuardedPath)>);

/// Collect one packable tree (see [`ArchiveTree`]). Sources arrive
/// pre-probed ([`resolve_archive_src`]); every descendant is probed at
/// visit time through its own listing entry, whose file type never
/// follows links.
fn collect_archive_tree(
    fs: &dyn oxdock_fs::WorkspaceFs,
    src_abs: &GuardedPath,
    src: &str,
    dst: &str,
) -> Result<ArchiveTree> {
    let tag = format!("ARCHIVE {src} {dst}");
    match fs.entry_kind(src_abs).with_context(|| tag.clone())? {
        EntryKind::File => {
            let base = src_abs
                .as_path()
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .with_context(|| {
                    format!("{tag}: source has no file name: {}", src_abs.display())
                })?;
            let rel = sanitize_rel(&to_forward_slashes(&base)).with_context(|| tag.clone())?;
            Ok((vec![(rel, src_abs.clone())], Vec::new()))
        }
        EntryKind::Dir => {
            let mut files = Vec::new();
            let mut dirs = Vec::new();
            let mut stack = vec![(src_abs.clone(), String::new())];
            while let Some((dir_abs, dir_rel)) = stack.pop() {
                // A swapped intermediate link would redirect the whole
                // subtree walk: the rel prefixes must be real
                // directories before listing.
                PathResolver::refuse_link_ancestors(src_abs, &dir_rel)
                    .with_context(|| tag.clone())?;
                let mut entries = fs.read_dir_entries(&dir_abs).with_context(|| tag.clone())?;
                entries.sort_by_key(|entry| entry.file_name());
                for entry in entries {
                    let name = entry.file_name().to_string_lossy().to_string();
                    let joined = if dir_rel.is_empty() {
                        name.clone()
                    } else {
                        format!("{dir_rel}/{name}")
                    };
                    let child_rel = to_forward_slashes(&joined);
                    let is_link = entry
                        .file_type()
                        .map(|kind| kind.is_symlink())
                        .unwrap_or(true);
                    if is_link {
                        bail!("{tag}: refuses to pack symlink {child_rel:?}");
                    }
                    let child = dir_abs.join(&name).with_context(|| tag.clone())?;
                    match fs.entry_kind(&child).with_context(|| tag.clone())? {
                        EntryKind::Dir => {
                            dirs.push((child_rel.clone(), child.clone()));
                            stack.push((child, child_rel));
                        }
                        EntryKind::File => files.push((child_rel, child)),
                        EntryKind::Symlink => {
                            unreachable!("following entry_kind never reports symlinks")
                        }
                    }
                }
            }
            files.sort_by(|a, b| a.0.cmp(&b.0));
            dirs.sort_by(|a, b| a.0.cmp(&b.0));
            Ok((files, dirs))
        }
        EntryKind::Symlink => unreachable!("following entry_kind never reports symlinks"),
    }
}

/// Append one collected tree to an open tar builder, opening each file
/// only for its own append: file handles never accumulate, so archive
/// size stays O(chunk) memory with O(1) open files.
fn append_archive_tree<W: std::io::Write>(
    fs: &dyn oxdock_fs::WorkspaceFs,
    builder: &mut tar::Builder<W>,
    files: &[(String, GuardedPath)],
    dirs: &[(String, GuardedPath)],
    src_abs: &GuardedPath,
    tag: &str,
) -> Result<()> {
    for (rel, guard) in dirs {
        let rel = sanitize_rel(rel).with_context(|| tag.to_string())?;
        let mode = fs
            .archive_member_stat(guard)
            .map(|(_, mode)| mode.unwrap_or(0o755))
            .with_context(|| tag.to_string())?;
        let mut header = tar::Header::new_gnu();
        header.set_mode(mode);
        header.set_entry_type(tar::EntryType::Directory);
        header.set_size(0);
        header.set_cksum();
        builder
            .append_data(&mut header, &rel, std::io::empty())
            .with_context(|| tag.to_string())?;
    }
    for (rel, guard) in files {
        let rel = sanitize_rel(rel).with_context(|| tag.to_string())?;
        let (len, mode) = fs
            .archive_member_stat(guard)
            .with_context(|| tag.to_string())?;
        // Link-refusing open: a symlink planted after the listing
        // probe fails here instead of packing its target's bytes, and
        // the descriptor must stay under the packed tree.
        let mut reader = fs
            .open_read_nofollow(guard, src_abs)
            .with_context(|| tag.to_string())?;
        let mut header = tar::Header::new_gnu();
        header.set_mode(mode.unwrap_or(0o644));
        header.set_size(len);
        header.set_cksum();
        builder
            .append_data(&mut header, &rel, &mut reader)
            .with_context(|| tag.to_string())?;
    }
    Ok(())
}

pub(super) fn archive<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    src: &str,
    dst: &str,
    raw: bool,
) -> Result<()> {
    let tag = format!("ARCHIVE {src} {dst}");
    let src_abs = resolve_archive_src(cx, src, &tag)?;
    let dst_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, dst)
        .with_context(|| tag.clone())?;
    // Opening the destination truncates it: an archive landing on its
    // own source would destroy inputs before their bytes stream, so
    // equal paths fail closed. A pre-existing destination inside the
    // packed tree would likewise be truncated before its own append
    // reads it back; a fresh one is safe (collection already ran, so it
    // cannot be a member) which keeps whole-tree archives like
    // `ARCHIVE project project.tar.gz` working.
    if dst_abs == src_abs {
        bail!("{tag}: destination {dst:?} cannot be the source itself");
    }
    if dst_abs.as_path().starts_with(src_abs.as_path()) && dst_abs.exists() {
        bail!("{tag}: destination {dst:?} cannot overwrite inside the packed tree");
    }
    let (files, dirs) = collect_archive_tree(cx.state.fs.as_ref(), &src_abs, src, dst)?;
    cx.state
        .fs
        .ensure_parent_dir(&dst_abs)
        .with_context(|| tag.clone())?;
    let out = cx
        .state
        .fs
        .open_write(&dst_abs)
        .with_context(|| tag.clone())?;
    if raw {
        let mut builder = tar::Builder::new(out);
        append_archive_tree(
            cx.state.fs.as_ref(),
            &mut builder,
            &files,
            &dirs,
            &src_abs,
            &tag,
        )?;
        let mut out = builder.into_inner().with_context(|| tag.clone())?;
        std::io::Write::flush(&mut out).with_context(|| tag.clone())?;
    } else {
        let encoder = GzEncoder::new(out, Compression::default());
        let mut builder = tar::Builder::new(encoder);
        append_archive_tree(
            cx.state.fs.as_ref(),
            &mut builder,
            &files,
            &dirs,
            &src_abs,
            &tag,
        )?;
        builder
            .into_inner()
            .with_context(|| tag.clone())?
            .try_finish()
            .with_context(|| tag.clone())?;
    }
    Ok(())
}

pub(super) fn unarchive<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    src: &str,
    dst: &str,
    max_bytes: Option<&str>,
) -> Result<()> {
    let tag = format!("UNARCHIVE {src} {dst}");
    let cap = match max_bytes {
        Some(raw) => oxdock_parser::command::parse_byte_count(raw)
            .with_context(|| format!("{tag}: --max-bytes {raw:?}"))?,
        None => DEFAULT_UNARCHIVE_MAX_BYTES,
    };
    let src_abs = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, src)
        .with_context(|| tag.clone())?;
    let dst_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, dst)
        .with_context(|| tag.clone())?;
    cx.state
        .fs
        .create_dir_all(&dst_abs)
        .with_context(|| tag.clone())?;
    let reader = cx
        .state
        .fs
        .open_read(&src_abs)
        .with_context(|| tag.clone())?;
    let fs = cx.state.fs.as_ref();
    // Directory modes apply after every member lands: a read-only
    // header (e.g. 0555) would otherwise lock its own children out
    // before they extract. Deepest first, so restrictive parents settle
    // last with nothing left to write beneath them.
    let mut deferred_dir_modes: Vec<(GuardedPath, u32)> = Vec::new();
    // The expansion budget spans the whole archive, not one member: a
    // bomb split across many just-under-cap members must still trip it.
    let mut remaining = cap;
    unpack_auto_from(reader, &mut |entry| {
        let entry_tag = format!("{tag}: member");
        match entry {
            StreamedEntry::Dir { path, mode } => {
                // Re-validate the decoder's rel at the write site: a
                // sanitized rel is pure descent, so the join below
                // cannot escape lexically in any path normalization
                // domain (verbatim, short names, slashes). Escapes via
                // planted links stay the filesystem layers' job, and
                // those run next, on every member, in every mode.
                let rel = sanitize_rel(&path).with_context(|| entry_tag.clone())?;
                PathResolver::refuse_link_ancestors(&dst_abs, &rel)
                    .with_context(|| entry_tag.clone())?;
                let dir = dst_abs.join(&rel).with_context(|| entry_tag.clone())?;
                fs.create_dir_all(&dir).with_context(|| entry_tag.clone())?;
                deferred_dir_modes.push((dir, mode));
            }
            StreamedEntry::File { path, mode, reader } => {
                let rel = sanitize_rel(&path).with_context(|| entry_tag.clone())?;
                PathResolver::refuse_link_ancestors(&dst_abs, &rel)
                    .with_context(|| entry_tag.clone())?;
                let file = dst_abs.join(&rel).with_context(|| entry_tag.clone())?;
                fs.ensure_parent_dir(&file)
                    .with_context(|| entry_tag.clone())?;
                // Link-refusing open: a symlink planted at the member
                // path fails here instead of truncating its target,
                // and the descriptor must stay under the destination.
                let mut out = fs
                    .open_write_nofollow(&file, &dst_abs)
                    .with_context(|| entry_tag.clone())?;
                // Metered copy: bombs read small and write huge, so the
                // cap counts member bytes out, not archive bytes in. The
                // tripped member stays truncated while the step fails.
                let mut capped = CappedReader {
                    inner: reader,
                    remaining,
                };
                std::io::copy(&mut capped, &mut out).map_err(|e| {
                    if e.kind() == std::io::ErrorKind::QuotaExceeded {
                        anyhow!(
                            "{entry_tag}: archive exceeds the {cap}-byte expansion cap at {path:?}"
                        )
                    } else {
                        anyhow::Error::new(e).context(entry_tag.clone())
                    }
                })?;
                remaining = capped.remaining;
                std::io::Write::flush(&mut out).with_context(|| entry_tag.clone())?;
                restore_archive_mode(fs, &file, mode).with_context(|| entry_tag.clone())?;
            }
            StreamedEntry::Symlink { path, target } => {
                bail!("{entry_tag}: refuses symlink member {path:?} -> {target:?}");
            }
        }
        Ok(())
    })
    .with_context(|| tag.clone())?;
    for (dir, mode) in deferred_dir_modes.into_iter().rev() {
        restore_archive_mode(fs, &dir, mode).with_context(|| format!("{tag}: restoring mode"))?;
    }
    Ok(())
}

/// Default `UNARCHIVE` expansion cap (1 GiB of member bytes): release
/// artifacts are megabytes, so this never gates legitimate use while a
/// decompression bomb trips it long before runner disks fill. Per-call
/// `--max-bytes` moves the ceiling either way.
const DEFAULT_UNARCHIVE_MAX_BYTES: u64 = 1024 * 1024 * 1024;

/// Read adapter metering decompressed member bytes against the
/// expansion cap: bombs read small and write huge, so the meter sits on
/// the output side. Zero-length probes pass through so EOF detection
/// keeps working, and an exhausted budget probes the stream before
/// erroring: a payload ending exactly on the cap reads `Ok(0)` there
/// instead of false-tripping.
struct CappedReader<'a> {
    inner: &'a mut dyn std::io::Read,
    remaining: u64,
}

impl std::io::Read for CappedReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        if self.remaining == 0 {
            let mut probe = [0u8; 1];
            if self.inner.read(&mut probe)? == 0 {
                return Ok(0);
            }
            return Err(std::io::Error::new(
                std::io::ErrorKind::QuotaExceeded,
                "archive member exceeds the expansion cap",
            ));
        }
        let allowed = (buf.len() as u64).min(self.remaining) as usize;
        let n = self.inner.read(&mut buf[..allowed])?;
        self.remaining -= n as u64;
        Ok(n)
    }
}
/// Restore one header mode through the fs abstraction (Unix-effective,
/// no-op elsewhere). Zero modes skip: a degenerate header must never
/// brick its file unreadable.
fn restore_archive_mode(
    fs: &dyn oxdock_fs::WorkspaceFs,
    path: &GuardedPath,
    mode: u32,
) -> Result<()> {
    let mode = mode & 0o7777;
    if mode != 0 {
        fs.set_permissions_mode_unix(path, mode)?;
    }
    Ok(())
}

pub(super) fn symlink<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    from_workspace: Option<WorkspaceTarget>,
    from: &str,
    to: &str,
) -> Result<()> {
    let to_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, to)
        .with_context(|| format!("SYMLINK {} {}", from, to))?;
    let from_abs = if let Some(target) = from_workspace {
        cx.state
            .fs
            .resolve_copy_source_from_target(copy_source_root(target), from)
            .with_context(|| format!("SYMLINK {} {}", from, to))?
    } else {
        cx.state
            .fs
            .resolve_copy_source(from)
            .with_context(|| format!("SYMLINK {} {}", from, to))?
    };
    // `ln -s` destination semantics: a directory destination (existing,
    // or named with a trailing slash) receives the link under the
    // source basename instead of failing as "already exists".
    let to_abs = if to.ends_with('/') || to.ends_with('\\') {
        let base = link_base_name(&from_abs, from)?;
        to_abs
            .join(&base)
            .with_context(|| format!("SYMLINK {} {}", from, to))?
    } else if matches!(cx.state.fs.entry_kind(&to_abs), Ok(EntryKind::Dir)) {
        let base = link_base_name(&from_abs, from)?;
        to_abs
            .join(&base)
            .with_context(|| format!("SYMLINK {} {}", from, to))?
    } else {
        to_abs
    };
    cx.state
        .fs
        .symlink(&from_abs, &to_abs)
        .with_context(|| format!("SYMLINK {} {}", from, to))?;
    Ok(())
}

/// Basename of a link source for directory-destination placement. Lexical:
/// dangling sources have no entry kind to inspect.
fn link_base_name(from_abs: &GuardedPath, from: &str) -> Result<String> {
    from_abs
        .as_path()
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .with_context(|| format!("SYMLINK source has no file name: {from}"))
}

pub(super) fn mkdir<P: ProcessManager>(cx: &mut StepCtx<'_, P>, path: &str) -> Result<()> {
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, path)
        .with_context(|| format!("MKDIR {}", path))?;
    cx.state
        .fs
        .create_dir_all(&target)
        .with_context(|| format!("failed to create dir {}", target.display()))?;
    Ok(())
}

pub(super) fn set_executable<P: ProcessManager>(cx: &mut StepCtx<'_, P>, path: &str) -> Result<()> {
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, path)
        .with_context(|| format!("SET_EXECUTABLE {path}"))?;
    cx.state
        .fs
        .set_executable(&target)
        .with_context(|| format!("SET_EXECUTABLE {path}"))?;
    Ok(())
}

pub(super) fn ls<P: ProcessManager>(cx: &mut StepCtx<'_, P>, arg: &Option<String>) -> Result<()> {
    let target_dir = if let Some(p) = arg {
        cx.state
            .fs
            .resolve_read(&cx.state.cwd, p)
            .with_context(|| format!("LS {}", p))?
    } else {
        // Bare `LS` lists the current directory: ride the choke point so a
        // pending snapshot materializes (a snapshot read), matching the
        // explicit-path branch above. Local roots resolve with zero I/O.
        cx.state
            .fs
            .resolve_read(&cx.state.cwd, ".")
            .with_context(|| "LS".to_string())?
    };
    let mut entries = cx
        .state
        .fs
        .read_dir_entries(&target_dir)
        .with_context(|| format!("LS {}", target_dir.display()))?;
    entries.sort_by_key(|e| e.file_name());
    write_stdout(cx.out.clone(), |writer| {
        writeln!(writer, "{}:", target_dir.display())?;
        for entry in &entries {
            writeln!(writer, "{}", entry.file_name().to_string_lossy())?;
        }
        Ok(())
    })?;
    Ok(())
}

pub(super) fn read<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path_opt: &Option<String>,
) -> Result<()> {
    if let Some(path) = path_opt {
        let target = cx
            .state
            .fs
            .resolve_read(&cx.state.cwd, path)
            .with_context(|| format!("READ {}", path))?;
        let mut reader = cx
            .state
            .fs
            .open_read(&target)
            .with_context(|| format!("failed to open {}", target.display()))?;
        write_stdout(cx.out.clone(), |writer| {
            let mut buf = [0u8; super::io::CHUNK_SIZE];
            loop {
                let n = reader.read(&mut buf).context("failed to read from file")?;
                if n == 0 {
                    break;
                }
                writer
                    .write_all(&buf[..n])
                    .context("failed to write to output")?;
            }
            Ok(())
        })?;
    } else {
        let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
            bail!("READ requires stdin (use WITH_IO [stdin=...] READ)");
        };
        let mut buf = [0u8; super::io::CHUNK_SIZE];
        loop {
            let n = {
                let mut guard = input_stream
                    .lock()
                    .map_err(|_| anyhow!("failed to lock stdin for READ"))?;
                guard.read(&mut buf).context("failed to read from stdin")?
            };
            if n == 0 {
                break;
            }
            write_stdout(cx.out.clone(), |writer| {
                writer
                    .write_all(&buf[..n])
                    .context("failed to write to output")
            })?;
        }
    }
    Ok(())
}

pub(super) fn read_line<P: ProcessManager>(cx: &mut StepCtx<'_, P>, var: &str) -> Result<()> {
    let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
        bail!("READ_LINE requires stdin (use WITH_IO [stdin=...] READ_LINE $var)");
    };
    let clean_var = var.trim_start_matches('$').to_string();
    let mut buf = Vec::new();
    let mut byte = [0u8; 1];
    loop {
        let n = {
            let mut guard = input_stream
                .lock()
                .map_err(|_| anyhow!("failed to lock stdin for READ_LINE"))?;
            guard.read(&mut byte).context("failed to read from stdin")?
        };
        if n == 0 {
            break;
        }
        buf.push(byte[0]);
        if byte[0] == b'\n' {
            break;
        }
    }
    let line = String::from_utf8(buf).context("READ_LINE received non-UTF8 bytes")?;
    let line = line
        .strip_suffix("\r\n")
        .or_else(|| line.strip_suffix('\n'))
        .unwrap_or(&line);
    let text = Value::string(line.to_string());
    if cx.state.get_var_typed(&clean_var).is_some() {
        cx.state.mutate_var(&clean_var, text)?;
    } else {
        cx.state.declare_var(clean_var, TypeTag::String, text)?;
    }
    Ok(())
}

/// Structured variable snapshot backing the `INSPECT()` expression form:
/// base keys (`type`, `variable`, `name`, `value`) plus live details :
/// pipe backend stats for `PIPE`, task phase for `HANDLE`. Undeclared
/// names are an error. (Expression evaluation carries no step index, so
/// unlike statement handlers this reports no step number.)
pub(super) fn inspect_var_map<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    var: &str,
) -> Result<BTreeMap<String, Value>> {
    let clean_var = var.trim_start_matches('$').to_string();
    let Some((decl_type, value)) = cx.state.get_var_typed(&clean_var) else {
        bail!("variable '${clean_var}' is not defined");
    };
    let mut map = BTreeMap::new();
    map.insert(
        "type".to_string(),
        Value::string(render_structural(&decl_type)),
    );
    map.insert("variable".to_string(), Value::string(clean_var.clone()));
    match (decl_type, value.as_pipe_handle()) {
        (TypeTag::Pipe, Some(handle)) => {
            let info = cx.state.io.inspect_pipe(&handle);
            map.insert("name".to_string(), Value::string(clean_var.clone()));
            map.insert("value".to_string(), Value::string(format!("{value}")));
            map.insert("is_os_pipe".to_string(), Value::bool(info.kind.is_os()));
            map.insert(
                "pipe_kind".to_string(),
                Value::string(info.kind.as_str().to_string()),
            );
            map.insert(
                "buffer_bytes".to_string(),
                Value::int(info.buffered.min(i64::MAX as u64) as i64),
            );
            map.insert("readers".to_string(), Value::int(info.readers as i64));
            map.insert("writers".to_string(), Value::int(info.writers as i64));
        }
        (TypeTag::Handle | TypeTag::HandleOf(_), _) => {
            if let Some(task_id) = value.as_handle() {
                map.insert("name".to_string(), Value::string(clean_var.clone()));
                map.insert(
                    "value".to_string(),
                    Value::string(format!("task {task_id}")),
                );
                let phase = cx
                    .state
                    .named_tasks
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .get(&task_id)
                    .map(|entry| {
                        let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
                        match guard.phase {
                            TaskPhase::Running => "Running",
                            TaskPhase::Awaiting => "Awaiting",
                            TaskPhase::Cancelled => "Cancelled",
                            TaskPhase::Completed => "Completed",
                        }
                        .to_string()
                    })
                    .unwrap_or_else(|| "unknown (already awaited?)".to_string());
                map.insert("task_id".to_string(), Value::int(task_id as i64));
                map.insert("task_phase".to_string(), Value::string(phase));
            } else {
                map.insert("name".to_string(), Value::string(clean_var.clone()));
                map.insert("value".to_string(), Value::string(format!("{value}")));
            }
        }
        _ => {
            map.insert("name".to_string(), Value::string(clean_var.clone()));
            map.insert("value".to_string(), Value::string(format!("{value}")));
        }
    }
    Ok(map)
}

pub(super) fn write<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path: &str,
    contents: Option<&str>,
) -> Result<()> {
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, path)
        .with_context(|| format!("WRITE {}", path))?;
    cx.state
        .fs
        .ensure_parent_dir(&target)
        .with_context(|| format!("failed to create parent for {}", target.display()))?;
    if let Some(body) = contents {
        cx.state
            .fs
            .write_file(&target, body.as_bytes())
            .with_context(|| format!("failed to write {}", target.display()))?;
    } else {
        let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
            bail!(
                "WRITE {} requires stdin (use WITH_IO [stdin=...] WRITE)",
                path
            );
        };
        let mut guard = input_stream
            .lock()
            .map_err(|_| anyhow!("failed to lock stdin for WRITE"))?;
        let mut writer = cx
            .state
            .fs
            .open_write(&target)
            .with_context(|| format!("failed to open {} for writing", target.display()))?;
        let mut buf = [0u8; super::io::CHUNK_SIZE];
        loop {
            let n = guard
                .read(&mut buf)
                .context("failed to read from stdin for WRITE")?;
            if n == 0 {
                break;
            }
            writer
                .write_all(&buf[..n])
                .with_context(|| format!("failed to write to {}", target.display()))?;
            writer.flush()?;
        }
    }
    Ok(())
}

pub(super) fn append<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path: &str,
    contents: Option<&str>,
) -> Result<()> {
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, path)
        .with_context(|| format!("APPEND {}", path))?;
    cx.state
        .fs
        .ensure_parent_dir(&target)
        .with_context(|| format!("failed to create parent for {}", target.display()))?;
    if let Some(body) = contents {
        cx.state
            .fs
            .append_file(&target, body.as_bytes())
            .with_context(|| format!("failed to append to {}", target.display()))?;
    } else {
        let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
            bail!(
                "APPEND {} requires stdin (use WITH_IO [stdin=...] APPEND)",
                path
            );
        };
        let mut guard = input_stream
            .lock()
            .map_err(|_| anyhow!("failed to lock stdin for APPEND"))?;
        let mut writer = cx
            .state
            .fs
            .open_append(&target)
            .with_context(|| format!("failed to open {} for appending", target.display()))?;
        let mut buf = [0u8; super::io::CHUNK_SIZE];
        loop {
            let n = guard
                .read(&mut buf)
                .context("failed to read from stdin for APPEND")?;
            if n == 0 {
                break;
            }
            writer
                .write_all(&buf[..n])
                .with_context(|| format!("failed to append to {}", target.display()))?;
            writer.flush()?;
        }
    }
    Ok(())
}

pub(super) fn replace<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path_opt: &Option<String>,
    overrides: &[(String, String)],
) -> Result<()> {
    let ctx = cx.state.command_ctx()?;
    let vars = cx.state.all_vars();
    // Dispatch `{{ MODULE::FUNC(args) }}` through the shared pure table.
    // Known callees reuse the static-gate wording through an owned
    // snapshot: the `'static` closure cannot borrow the registry.
    let table = cx.state.pure_function_table();
    let snapshot = cx
        .state
        .functions
        .placeholder_snapshot(&super::import::active_unit_alias_targets(cx.state));
    let inner = super::native::placeholder_resolver(table);
    let calls: oxdock_process::PlaceholderCall =
        std::sync::Arc::new(move |module, func, args| match inner(module, func, args) {
            Ok(value) => Ok(value),
            Err(err) => {
                if let Some(text) = snapshot.describe(module, func) {
                    return Err(anyhow::anyhow!("{text}"));
                }
                Err(err)
            }
        });

    let mut expander = oxdock_process::StreamingExpand::new(overrides, ctx.envs())
        .with_vars(&vars)
        .with_call_resolver(calls);
    let mut out_buf = Vec::with_capacity(super::io::CHUNK_SIZE);

    write_stdout(cx.out.clone(), |w| {
        if let Some(path) = path_opt {
            let target = cx
                .state
                .fs
                .resolve_read(&cx.state.cwd, path)
                .with_context(|| format!("EXPAND {}", path))?;
            let mut reader = cx
                .state
                .fs
                .open_read(&target)
                .with_context(|| format!("failed to open {}", target.display()))?;
            let mut buf = [0u8; super::io::CHUNK_SIZE];
            loop {
                let n = reader
                    .read(&mut buf)
                    .with_context(|| format!("failed to read {}", target.display()))?;
                if n == 0 {
                    break;
                }
                expander.process_bytes(&buf[..n], &mut out_buf)?;
                w.write_all(&out_buf).context("failed to write output")?;
                out_buf.clear();
            }
        } else {
            let CommandStdin::Stream(input_stream) = cx.stdin.clone() else {
                bail!(
                    "EXPAND requires stdin when no file path is given \
                     (use WITH_IO [stdin=...] EXPAND)"
                );
            };
            let mut guard = input_stream
                .lock()
                .map_err(|_| anyhow!("failed to lock stdin for EXPAND"))?;
            let mut buf = [0u8; super::io::CHUNK_SIZE];
            loop {
                let n = guard.read(&mut buf).context("failed to read from stdin")?;
                if n == 0 {
                    break;
                }
                expander.process_bytes(&buf[..n], &mut out_buf)?;
                w.write_all(&out_buf).context("failed to write output")?;
                out_buf.clear();
            }
        }

        expander.flush(&mut out_buf)?;
        if !out_buf.is_empty() {
            w.write_all(&out_buf).context("failed to write output")?;
            out_buf.clear();
        }

        Ok(())
    })?;

    Ok(())
}

/// Strict equality/inequality assertion over evaluated values, stream
/// buffers, and pipe buffers. Typed `Value` comparison with no coercion;
/// files never appear here (read them into variables first). `--hash`
/// compares the SHA-256 of a string, pipe, or captured-stdout actual
/// instead of the raw bytes (`stderr` is unsupported).
///
/// `expect_equal` selects the polarity: true is `ASSERT_EQ`, false is
/// `ASSERT_NE`. All target resolution, Mode-1 draining, and digest logic
/// lives here once; the two verbs differ only in pass/fail sense and
/// error text.
#[allow(clippy::too_many_arguments)]
pub(super) fn assert_equality<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    verb: &str,
    expect_equal: bool,
    hash: &Option<String>,
    actual: &super::steps::ResolvedAssertTarget,
    expected: Option<&Value>,
) -> Result<()> {
    use super::steps::ResolvedAssertTarget;
    // Mode 1: exact stdout with piped stdin consumes the stream, mirroring
    // the legacy substring behavior, but compares exact bytes.
    if let ResolvedAssertTarget::Stdout = actual
        && let CommandStdin::Stream(input_stream) = cx.stdin.clone()
    {
        let drained = drain_stdin_bounded(input_stream, verb)?;
        super::io::write_stdout(cx.out.clone(), |w| {
            w.write_all(&drained)?;
            Ok(())
        })?;
        if let Some(sha) = hash {
            // Hash form carries no positional expected: digest the
            // drained stream and compare with the selected polarity.
            let computed = sha256_hex(&drained);
            let is_equal = computed.eq_ignore_ascii_case(sha);
            if is_equal != expect_equal {
                if expect_equal {
                    bail!("{verb} --hash mismatch: expected {sha}, computed {computed}");
                } else {
                    bail!("{verb} --hash match: content matches {sha}");
                }
            }
            return Ok(());
        }
        let Some(want) = expected.and_then(|v| v.as_str()) else {
            bail!(
                "{verb} stream mismatch\nexpected: {:?}\nactual:   {:?}",
                expected,
                String::from_utf8_lossy(&drained)
            );
        };
        let is_equal = drained == want.as_bytes();
        if is_equal != expect_equal {
            if expect_equal {
                bail!(
                    "{verb} stream mismatch\nexpected: {:?}\nactual:   {:?}",
                    want,
                    String::from_utf8_lossy(&drained)
                );
            } else {
                bail!("{verb} stream unexpectedly equal: {want:?}");
            }
        }
        return Ok(());
    }
    if let Some(sha) = hash {
        let actual_bytes: Vec<u8> = match actual {
            ResolvedAssertTarget::Value(v) => match v.as_str() {
                Some(s) => s.as_bytes().to_vec(),
                None => {
                    bail!("{verb} --hash needs a string actual, found {v:?}");
                }
            },
            ResolvedAssertTarget::Pipe(bytes) => bytes.clone(),
            ResolvedAssertTarget::Stdout => exact_stdout_bytes(cx, generation, verb)?,
            ResolvedAssertTarget::Stderr => {
                bail!(
                    "{verb} over stderr is not supported; use {} stderr ...",
                    Command::AssertContains.as_str()
                );
            }
        };
        let computed = sha256_hex(&actual_bytes);
        let is_equal = computed.eq_ignore_ascii_case(sha);
        if is_equal != expect_equal {
            if expect_equal {
                bail!("{verb} --hash mismatch: expected {sha}, computed {computed}");
            } else {
                bail!("{verb} --hash match: content matches {sha}");
            }
        }
        return Ok(());
    }
    match actual {
        ResolvedAssertTarget::Value(got) => {
            let Some(want) = expected else {
                bail!("{verb} requires an expected value");
            };
            let is_equal = got == want;
            if is_equal != expect_equal {
                if expect_equal {
                    bail!("{verb} mismatch\nexpected: {:?}\nactual:   {:?}", want, got);
                } else {
                    bail!(
                        "{verb} mismatch: values are equal\nexpected: {:?}\nactual:   {:?}",
                        want,
                        got
                    )
                }
            }
            Ok(())
        }
        ResolvedAssertTarget::Stdout => {
            let bytes = exact_stdout_bytes(cx, generation, verb)?;
            let Some(want) = expected.and_then(|v| v.as_str()) else {
                bail!(
                    "{verb} stream mismatch\nexpected: {:?}\nactual:   {:?}",
                    expected,
                    String::from_utf8_lossy(&bytes)
                );
            };
            let is_equal = bytes == want.as_bytes();
            if is_equal != expect_equal {
                if expect_equal {
                    bail!(
                        "{verb} stream mismatch\nexpected: {:?}\nactual:   {:?}",
                        want,
                        String::from_utf8_lossy(&bytes)
                    );
                } else {
                    bail!("{verb} stream unexpectedly equal: {want:?}");
                }
            }
            Ok(())
        }
        ResolvedAssertTarget::Stderr => {
            bail!(
                "{verb} over stderr is not supported; use {} stderr ...",
                Command::AssertContains.as_str()
            );
        }
        ResolvedAssertTarget::Pipe(bytes) => {
            let actual_str = String::from_utf8(bytes.clone())
                .with_context(|| format!("{verb} pipe content is not UTF-8"))?;
            let Some(want) = expected.and_then(|v| v.as_str()) else {
                bail!(
                    "{verb} pipe mismatch\nexpected: {:?}\nactual:   {:?}",
                    expected,
                    actual_str
                );
            };
            let is_equal = actual_str == want;
            if is_equal != expect_equal {
                if expect_equal {
                    bail!(
                        "{verb} pipe mismatch\nexpected: {:?}\nactual:   {:?}",
                        want,
                        actual_str
                    );
                } else {
                    bail!("{verb} pipe unexpectedly equal: {want:?}");
                }
            }
            Ok(())
        }
    }
}

/// Drain a piped stdin fully while enforcing the exact-match byte cap.
/// Shared by `ASSERT_EQ`/`ASSERT_NE stdout` Mode 1.
fn drain_stdin_bounded(input_stream: SharedInput, verb: &str) -> Result<Vec<u8>> {
    let mut guard = input_stream
        .lock()
        .map_err(|_| anyhow!("failed to lock stdin for {verb}"))?;
    let mut out = Vec::new();
    let mut buf = [0u8; super::io::CHUNK_SIZE];
    loop {
        let n = guard
            .read(&mut buf)
            .with_context(|| format!("failed to read from stdin for {verb}"))?;
        if n == 0 {
            break;
        }
        if out.len() + n > super::io::EXACT_STDOUT_CAP {
            bail!(
                "{verb} stdin exceeded the 8 MiB exact buffer; assert via pipe targets or harness expect.stdout"
            );
        }
        out.extend_from_slice(&buf[..n]);
    }
    Ok(out)
}

/// Read the trial-cumulative exact stdout bytes for this generation,
/// or bail with remediation guidance on overflow / missing capture.
fn exact_stdout_bytes<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    verb: &str,
) -> Result<Vec<u8>> {
    let captures = cx
        .state
        .exact_stdout
        .lock()
        .map_err(|_| anyhow!("exact_stdout poisoned"))?;
    match captures.get(&generation) {
        Some(entry) if entry.overflowed => bail!(
            "{verb} stdout overflowed the 8 MiB exact buffer; assert via pipe targets or harness expect.stdout",
        ),
        Some(entry) => Ok(entry.bytes.clone()),
        None => bail!("{verb} stdout has no exact capture registered"),
    }
}

/// Containment assertion over values, streams, and pipes: substring for
/// strings, exact-element match for lists, key presence for maps,
/// substring over stream and pipe buffers. Like `assert_eq`, files never
/// appear here; read them into variables first.
pub(super) fn assert_contains<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    idx_step: usize,
    haystack: &super::steps::ResolvedAssertTarget,
    needle: &Arg,
) -> Result<()> {
    use super::steps::ResolvedAssertTarget;
    let verb = Command::AssertContains.as_str();
    let needle_str = super::args::resolve_arg(needle, cx)?;
    match haystack {
        ResolvedAssertTarget::Value(v) => {
            if let Some(hay) = v.as_str() {
                if hay.contains(needle_str.as_str()) {
                    return Ok(());
                }
                bail!("{verb} did not contain '{}'; actual: {:?}", needle_str, hay);
            }
            if let Some(items) = v.as_list() {
                if items
                    .iter()
                    .any(|e| e.as_str() == Some(needle_str.as_str()))
                {
                    return Ok(());
                }
                bail!("{verb} did not contain '{}'; actual: {:?}", needle_str, v);
            }
            if let Some(map) = v.as_map() {
                if map.contains_key(needle_str.as_str()) {
                    return Ok(());
                }
                bail!("{verb} did not contain '{}'", needle_str);
            }
            bail!(
                "{verb} needs a string, list, or map haystack, found {:?}",
                v
            );
        }
        ResolvedAssertTarget::Stdout => {
            // Mode 1: piped stdin is consumed through a local window and
            // forwarded, exactly like the legacy substring check.
            if let CommandStdin::Stream(input_stream) = cx.stdin.clone() {
                let mut guard = input_stream
                    .lock()
                    .map_err(|_| anyhow!("failed to lock stdin for {verb}"))?;
                let mut window = super::io::SlidingWindow::new(needle_str.as_bytes().to_vec());
                let mut buf = [0u8; super::io::CHUNK_SIZE];
                let mut read_any = false;
                loop {
                    let n = guard
                        .read(&mut buf)
                        .context(format!("failed to read from stdin for {verb}"))?;
                    if n == 0 {
                        break;
                    }
                    read_any = true;
                    window.push_chunk(&buf[..n]);
                    super::io::write_stdout(cx.out.clone(), |w| {
                        w.write_all(&buf[..n])?;
                        Ok(())
                    })?;
                }
                if read_any {
                    if window.matched {
                        return Ok(());
                    }
                    let emitted = String::from_utf8_lossy(&window.ring_buffer()).into_owned();
                    bail!(
                        "{verb} did not contain '{}'; emitted:\n{}",
                        needle_str,
                        emitted.trim_end()
                    );
                }
            }
            // Mode 2: pre-registered stdout window for this step.
            let windows = cx
                .state
                .assert_windows
                .lock()
                .map_err(|_| anyhow!("assert_windows poisoned"))?;
            match windows.get(&(generation, idx_step)) {
                Some(w) if w.matched => Ok(()),
                Some(w) => {
                    let emitted = String::from_utf8_lossy(&w.ring_buffer()).into_owned();
                    bail!(
                        "{verb} did not contain '{}'; emitted:\n{}",
                        needle_str,
                        emitted.trim_end()
                    )
                }
                _ => bail!("{verb} did not contain '{}'", needle_str),
            }
        }
        ResolvedAssertTarget::Stderr => {
            // Stderr has no piped-stdin consumption mode: stdin bytes
            // belong to a different stream and are left alone.
            let windows = cx
                .state
                .assert_windows_stderr
                .lock()
                .map_err(|_| anyhow!("assert_windows_stderr poisoned"))?;
            match windows.get(&(generation, idx_step)) {
                Some(w) if w.matched => Ok(()),
                Some(w) => {
                    let emitted = String::from_utf8_lossy(&w.ring_buffer()).into_owned();
                    bail!(
                        "{verb} did not contain '{}'; emitted:\n{}",
                        needle_str,
                        emitted.trim_end()
                    )
                }
                _ => bail!("{verb} did not contain '{}'", needle_str),
            }
        }
        ResolvedAssertTarget::Pipe(bytes) => {
            let hay = String::from_utf8(bytes.clone())
                .with_context(|| format!("{verb} pipe content is not UTF-8"))?;
            if hay.contains(needle_str.as_str()) {
                Ok(())
            } else {
                bail!(
                    "{verb} did not contain '{}'; pipe held {:?}",
                    needle_str,
                    hay
                );
            }
        }
    }
}

pub(crate) fn with_io_block<P: ProcessManager>(
    _cx: &mut StepCtx<'_, P>,
    _generation: usize,
    _idx: usize,
    _bindings: &[IoBinding],
) -> Result<()> {
    bail!("WITH_IO block should have been expanded during parsing")
}

/// True when the wrapped command is a lone `RUN`: the only consumer or
/// producer shape that can hold an OS handle directly.
fn is_single_run(cmd: &StepKind) -> bool {
    matches!(cmd, StepKind::Run(_) | StepKind::RunExec { .. })
}

/// True when the wrapped command is an `ASYNC` block or task whose body is
/// exactly one `RUN`, guarded or not.
fn async_single_run_body(cmd: &StepKind) -> bool {
    match cmd {
        StepKind::AsyncBlock { body } | StepKind::AssignAsync { body, .. } => {
            matches!(body.as_slice(), [step] if is_single_run(&step.kind))
        }
        _ => false,
    }
}

/// Whether this binding resolves to a zero copy OS handle instead of a
/// bridged shared handle: the ultimate consumer or producer is a `RUN`.
/// Promotion itself is decided per handle by declaration scope
/// (`can_promote_to_os`); this only picks take vs bridge on OS-decided
/// handles.
fn run_terminated(cmd: &StepKind) -> bool {
    is_single_run(cmd) || async_single_run_body(cmd)
}

pub(crate) fn with_io<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    idx: usize,
    bindings: &[IoBinding],
    cmd: &StepKind,
) -> Result<Flow> {
    let (step_stdin, next_expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
        resolve_io_streams(cx, bindings, cmd)?;
    let tty = tty_request(bindings, cmd)?;

    super::steps::execute_single_step_with_generation(
        cx.state,
        cx.process,
        cmd,
        generation,
        idx,
        step_stdin,
        next_expose_stdin,
        step_stdout,
        step_stderr,
        out_pipe,
        stdin_pipe,
        tty,
    )
}

/// Extract the pty request from `WITH_IO` bindings, enforcing the
/// terminal rules every construction shares (direct steps and
/// block-expanded defaults alike reach this through `with_io`, so the
/// parser's span-carrying checks stay advisory while these decide).
/// Returns `None` for terminal-unaware steps, keeping hermetic pipes.
/// Geometry stays unresolved here: the spawn reads the host terminal
/// for unnamed sides, so a size change between steps is honored.
fn tty_request(bindings: &[IoBinding], cmd: &StepKind) -> Result<Option<TtyRequest>> {
    let mut tty = false;
    let mut rows = None;
    let mut cols = None;
    for binding in bindings {
        match binding.stream {
            IoStream::Tty => tty = true,
            IoStream::Rows(value) => rows = Some(value),
            IoStream::Cols(value) => cols = Some(value),
            IoStream::Stdin | IoStream::Stdout | IoStream::Stderr => {}
        }
    }
    if !tty {
        if rows.is_some() || cols.is_some() {
            bail!(
                "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size"
            );
        }
        return Ok(None);
    }
    if bindings
        .iter()
        .any(|b| matches!(b.stream, IoStream::Stderr))
    {
        bail!(
            "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex"
        );
    }
    match cmd {
        StepKind::Run(_) | StepKind::RunExec { .. } => Ok(Some(TtyRequest { rows, cols })),
        _ => bail!(
            "WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it",
        ),
    }
}

/// Resolve `WITH_IO` bindings against the active context handles, shared by
/// `with_io` and the `CALL` capture path (`LET`-capture) so a `CALL`
/// under `WITH_IO` layers observes identical stream wiring whether it
/// runs inline or for its return value.
///
/// Besides the runnable streams this returns the script backends behind
/// the stdin/stdout bindings, which enrich the step context for
/// timeout-bounded bridge reads and the socket-EOF force-close.
#[allow(clippy::type_complexity)]
fn resolve_io_streams<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    bindings: &[IoBinding],
    cmd: &StepKind,
) -> Result<(
    CommandStdin,
    bool,
    Option<StreamHandle>,
    Option<StreamHandle>,
    Option<Arc<PipeInner>>,
    Option<Arc<PipeInner>>,
)> {
    let mut step_stdin = CommandStdin::Null;
    let mut step_stdout = cx.out.clone();
    let mut step_stderr = cx.err.clone();
    let mut out_pipe = cx.out_pipe.clone();
    let mut stdin_pipe = cx.stdin_pipe.clone();
    let mut next_expose_stdin = false;
    let mut seen_stdin = false;
    let mut seen_stdout = false;
    let mut seen_stderr = false;
    let mut seen_tty = false;
    let mut seen_rows = false;
    let mut seen_cols = false;
    // `direct` (take vs bridged-shared) still judges by the ultimate
    // command: only RUN consumes raw descriptors. Promotion, in contrast,
    // is decided per handle below by declaration scope : and only on
    // worker threads. Main-flow bindings never promote: the main thread
    // is the universal sharer (it spawns every task), so anything it
    // decided could race a future share. Workers promote only their own
    // unshared pipes via the spawn-time pin walk.
    let direct = run_terminated(cmd);
    let allow_promote = cx.state.inside_async;
    // A pty master is one interleaved byte stream: its stdio stays on
    // script backends, never on zero copy OS descriptors. The pin walk
    // already skips terminal-bound handles; suppressing promotion here
    // as well keeps a handle an outer scope promoted usable through the
    // take-once bridge instead of a raw descriptor handoff.
    let tty_present = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
    // Under a terminal the pin walk leaves stdio undecided, so force
    // script backends here (`direct` only judges take vs bridge on
    // already-OS handles, which then bridge take-once like DSL
    // consumers instead of handing the child a raw descriptor).
    let direct = direct && !tty_present;

    for binding in bindings {
        if let Some(target) = &binding.pipe {
            let handle = resolve_pipe_handle(cx, target)?;
            // Main-flow bindings materialize here; task-body bindings were
            // decided by the spawn-time pin walk, making this a no-op
            // there. Either way the scope check, not the command, rules.
            let promote = allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
            cx.state.io.ensure_handle(&handle, promote)?;
        }
        match binding.stream {
            IoStream::Stdin => {
                if seen_stdin {
                    bail!("WITH_IO declared stdin more than once");
                }
                seen_stdin = true;
                next_expose_stdin = true;
                (step_stdin, stdin_pipe) = if let Some(target) = &binding.pipe {
                    let handle = resolve_pipe_handle(cx, target)?;
                    let promote =
                        allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
                    let (stdin, backend) = cx.state.io.resolve_stdin(&handle, direct, promote)?;
                    (stdin, backend)
                } else {
                    (cx.stdin.clone(), None)
                };
            }
            IoStream::Stdout => {
                if seen_stdout {
                    bail!("WITH_IO declared stdout more than once");
                }
                seen_stdout = true;
                (step_stdout, out_pipe) = if let Some(target) = &binding.pipe {
                    let handle = resolve_pipe_handle(cx, target)?;
                    let promote =
                        allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
                    let (stdout, backend) = cx.state.io.resolve_stdout(&handle, direct, promote)?;
                    (Some(stdout), backend)
                } else {
                    (cx.out.clone(), cx.out_pipe.clone())
                };
            }
            IoStream::Stderr => {
                if seen_stderr {
                    bail!("WITH_IO declared stderr more than once");
                }
                seen_stderr = true;
                step_stderr = if let Some(target) = &binding.pipe {
                    let handle = resolve_pipe_handle(cx, target)?;
                    let promote =
                        allow_promote && !tty_present && cx.state.can_promote_to_os(&handle);
                    Some(cx.state.io.resolve_stderr(&handle, direct, promote)?)
                } else {
                    cx.err.clone()
                };
            }
            IoStream::Tty => {
                if seen_tty {
                    bail!("WITH_IO declared tty more than once");
                }
                seen_tty = true;
            }
            IoStream::Rows(_) => {
                if seen_rows {
                    bail!("WITH_IO declared rows more than once");
                }
                seen_rows = true;
            }
            IoStream::Cols(_) => {
                if seen_cols {
                    bail!("WITH_IO declared cols more than once");
                }
                seen_cols = true;
            }
        }
    }

    Ok((
        step_stdin,
        next_expose_stdin,
        step_stdout,
        step_stderr,
        out_pipe,
        stdin_pipe,
    ))
}

/// Resolve a `WITH_IO` pipe endpoint to the owned backend cell. The
/// endpoint is always a `$var` holding a `PIPE` value; declaration never
/// pre-registers anything, and materialization happens at binding sites.
fn resolve_pipe_handle<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    target: &PipeTarget,
) -> Result<PipeHandle> {
    let PipeTarget::Var(var) = target;
    match cx.state.get_var_typed(var) {
        Some((kind, value)) if matches!(kind, TypeTag::Pipe) => {
            let Some(handle) = value.as_pipe_handle() else {
                bail!(
                    "TypeMismatch: expected PIPE, got {} ({:?})",
                    kind.name(),
                    value
                );
            };
            Ok(handle)
        }
        Some((kind, value)) => {
            bail!(
                "TypeMismatch: expected PIPE, got {} ({:?})",
                kind.name(),
                value
            );
        }
        None => {
            bail!("undeclared variable ${var}");
        }
    }
}

/// Peel a `LET $x: T = <command>` capture body to its value source,
/// mirroring the runtime binding rule: a `Call` (or single `IMPORT`)
/// binds its `RETURN` value; anything else binds captured stdout
/// text. `WITH_IO` layers merge outermost-first (inner wins per
/// stream); `TIMEOUT` layers peel through single-command bodies with
/// the tightest deadline winning, so a `TIMEOUT`-wrapped command
/// captures exactly what the bare command captures — the deadline
/// bounds the wait, never the value. Multi-step bodies stop the
/// peel and take the stdout-sink path with the `TIMEOUT` step
/// intact (deadline enforced there).
enum PeeledCapture<'a> {
    Call {
        bindings: Vec<IoBinding>,
        name: &'a str,
        args: &'a [Expr],
        deadline: Option<std::time::Duration>,
    },
    Import {
        bindings: Vec<IoBinding>,
        path: &'a str,
        alias: &'a str,
        deadline: Option<std::time::Duration>,
    },
    Sink,
}

fn merge_io_layers(layers: &[&Vec<IoBinding>]) -> Vec<IoBinding> {
    let mut merged: Vec<IoBinding> = Vec::new();
    for layer in layers {
        for binding in layer.iter() {
            match merged.iter_mut().find(|m| m.stream == binding.stream) {
                Some(slot) => *slot = binding.clone(),
                None => merged.push(binding.clone()),
            }
        }
    }
    merged
}

fn peel_capture_command<'a, P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    cmd: &'a StepKind,
) -> Result<PeeledCapture<'a>> {
    let mut layers: Vec<&Vec<IoBinding>> = Vec::new();
    let mut deadline: Option<std::time::Duration> = None;
    let mut current = cmd;
    loop {
        match current {
            StepKind::WithIo { bindings, cmd } => {
                layers.push(bindings);
                current = cmd;
            }
            StepKind::Timeout { duration, body } if body.len() == 1 => {
                let dur = super::args::resolve_arg_as_duration(duration, cx)?;
                deadline = Some(match deadline {
                    Some(d) => d.min(dur),
                    None => dur,
                });
                current = &body[0].kind;
            }
            StepKind::Call { name, args } => {
                return Ok(PeeledCapture::Call {
                    bindings: merge_io_layers(&layers),
                    name,
                    args,
                    deadline,
                });
            }
            StepKind::ImportFile { path, alias } => {
                return Ok(PeeledCapture::Import {
                    bindings: merge_io_layers(&layers),
                    path,
                    alias,
                    deadline,
                });
            }
            _ => return Ok(PeeledCapture::Sink),
        }
    }
}

pub(super) fn exit<P: ProcessManager>(cx: &mut StepCtx<'_, P>, code: i64) -> Result<()> {
    for child in cx.state.bg_children.iter_mut() {
        if let Ok(None) = child.handle.try_wait() {
            let _ = child.handle.kill();
            let _ = child.handle.try_wait();
        }
    }
    cx.state.bg_children.clear();
    Err(anyhow::Error::new(super::exit::ExitRequest(code)))
}

pub(crate) fn for_loop<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    key_var: Option<&str>,
    key_type: Option<String>,
    val_var: &str,
    val_type: String,
    in_expr: &Expr,
    body: &[Step],
) -> Result<Flow> {
    let iterable = super::args::evaluate_expr(in_expr, cx)?;
    let clean_val_var = val_var.trim_start_matches('$').to_string();
    let val_tag = cx.state.resolve_tag(&val_type)?;

    if let Some(items) = iterable.as_list() {
        for (i, item) in items.iter().enumerate() {
            // Each iteration is a scope (same rule as every other
            // block): loop vars live inside it, and ENV/WORKDIR/
            // WORKSPACE mutations revert on every iteration boundary.
            cx.state.push_scope();
            if let Some(idx_name) = key_var {
                let clean_idx = idx_name.trim_start_matches('$').to_string();
                let kt = match &key_type {
                    Some(name) => cx.state.resolve_tag(name)?,
                    None => TypeTag::Int,
                };
                cx.state.declare_var(
                    clean_idx,
                    kt.clone(),
                    super::args::coerce_value(Value::int(i as i64), &kt)?,
                )?;
            }
            cx.state.declare_var(
                clean_val_var.clone(),
                val_tag.clone(),
                super::args::coerce_value(item.clone(), &val_tag)?,
            )?;

            let res = super::steps::execute_steps(
                cx.state,
                cx.process,
                body,
                cx.stdin.clone(),
                false,
                cx.out.clone(),
                cx.err.clone(),
                cx.out_pipe.clone(),
                cx.stdin_pipe.clone(),
                false,
            );
            let pop_res = cx.state.pop_scope();
            let flow = match (res, pop_res) {
                (Ok(flow), Ok(())) => flow,
                (Err(e), _) => return Err(e),
                (Ok(_), Err(e)) => return Err(e),
            };
            match flow {
                Flow::Done | Flow::Continue { .. } => {}
                Flow::Break { .. } => return Ok(Flow::Done),
                Flow::Return { .. } => return Ok(flow),
            }
        }
        return Ok(Flow::Done);
    }
    if let Some(map) = iterable.as_map() {
        let key_name = key_var.ok_or_else(|| {
            anyhow!("FOR loop over Map requires key and value bindings: FOR $k: STRING, $v: TYPE IN $map")
        })?;
        let clean_key_var = key_name.trim_start_matches('$').to_string();
        let mut keys: Vec<_> = map.keys().cloned().collect();
        keys.sort();

        // Map keys are strings: only a STRING key binding is valid here.
        let kt = match &key_type {
            Some(name) => cx.state.resolve_tag(name)?,
            None => TypeTag::String,
        };
        if !matches!(kt, TypeTag::String) {
            anyhow::bail!(
                "FOR loop over MAP requires a STRING key variable, got {}",
                kt.name(),
            );
        }
        for k in keys {
            let v = map[&k].clone();
            cx.state.push_scope();
            cx.state.declare_var(
                clean_key_var.clone(),
                TypeTag::String,
                Value::string(k.clone()),
            )?;
            cx.state.declare_var(
                clean_val_var.clone(),
                val_tag.clone(),
                super::args::coerce_value(v, &val_tag)?,
            )?;

            let res = super::steps::execute_steps(
                cx.state,
                cx.process,
                body,
                cx.stdin.clone(),
                false,
                cx.out.clone(),
                cx.err.clone(),
                cx.out_pipe.clone(),
                cx.stdin_pipe.clone(),
                false,
            );
            let pop_res = cx.state.pop_scope();
            let flow = match (res, pop_res) {
                (Ok(flow), Ok(())) => flow,
                (Err(e), _) => return Err(e),
                (Ok(_), Err(e)) => return Err(e),
            };
            match flow {
                Flow::Done | Flow::Continue { .. } => {}
                Flow::Break { .. } => return Ok(Flow::Done),
                Flow::Return { .. } => return Ok(flow),
            }
        }
        return Ok(Flow::Done);
    }
    bail!(
        "FOR loop requires a List or Map iterable, found {:?}",
        iterable
    )
}

/// Define a user function (`FUNC NAME($p: TYPE, ...) { ... }}).
/// Copy-on-write into a fresh registry Arc so `fork()` sharers keep the
/// old view, while `push_scope`/`pop_scope` snapshots revert nested
/// definitions on block exit.
pub(crate) fn define_func<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    name: &str,
    params: &[(String, String, bool)],
    return_type: &str,
    is_async: bool,
    body: &[Step],
) -> Result<()> {
    // Resolve param and return type names where the directory lives, so the
    // registry only ever holds tags. Unknown names fail here naming
    // the function and every known type and schema.
    let resolved = super::resolve_script_params(cx.state, name, params)?;
    let return_tag = cx.state.resolve_tag(return_type)?;
    cx.state
        .check_return_tag(&format!("function `{name}` returns"), &return_tag)?;
    // Runtime counterpart of the parse-time scope validation; the single
    // registry owns the reserved, duplicate, and shadowing rules. The
    // owner is the innermost module on the stack (lexically enclosing
    // file), or `None` for entry definitions, which stay params-only.
    let owner = cx.state.current_module();
    cx.state.functions.define_script(
        name,
        &resolved,
        return_tag,
        return_type,
        is_async,
        body,
        owner.as_deref(),
    )
}

/// Invoke a function by UPPERCASE name and return its value. One lookup
/// against the unified registry, then gates, then effects: depth budget
/// and arity (mandatory metadata on every entry) validate before any
/// argument evaluates. Script bodies run in a fresh lexical scope
/// (LET/ENV/WORKDIR revert; pipes and files persist) with `declare_var`
/// coercion on parameter binding; `RETURN` inside yields the value and
/// fallthrough yields `""`. `BREAK`/`CONTINUE` escaping the body are
/// boundary errors (they must not reach a caller loop).
pub(crate) fn call_func_value<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    name: &str,
    args: &[Expr],
) -> Result<Value> {
    // 1. Registry lookup through the shared alias-target matcher.
    let canonical = cx
        .state
        .functions
        .resolve_file_call_key(&super::import::active_unit_alias_targets(cx.state), name)?;
    let lookup_name: &str = canonical.as_deref().unwrap_or(name);
    let Some(entry) = cx.state.functions.get(lookup_name) else {
        bail!("unknown function `{name}`");
    };
    // 2. Global recursion check.
    if cx.state.call_depth >= MAX_CALL_DEPTH {
        bail!(
            "recursion depth limit exceeded in FUNC {}",
            super::base_name(name)
        );
    }
    // 3. Pre-evaluation arity gate from the entry metadata. Trailing
    // optional MAP params widen exact counts to ranges; everything
    // else stays exact.
    if let Some(params) = entry.meta.params.as_deref() {
        let required = super::required_arity(params);
        if args.len() < required || args.len() > params.len() {
            if required == params.len() {
                bail!(
                    "{}() expects {} argument(s), got {}",
                    super::base_name(name),
                    params.len(),
                    args.len()
                );
            }
            bail!(
                "{}() expects {} to {} argument(s), got {}",
                super::base_name(name),
                required,
                params.len(),
                args.len()
            );
        }
    }
    // 4. Argument evaluation: only reachable for a valid invocation.
    // Omitted trailing optionals fill with zero values first, so
    // binding below always sees a full argument list. The arity gate
    // above guarantees every missing position is optional.
    let mut arg_vals = Vec::with_capacity(args.len());
    for arg in args {
        arg_vals.push(super::args::evaluate_expr(arg, cx)?);
    }
    // 5. Execution by body kind.
    match entry.body {
        FuncBody::Script(def) => {
            // Snapshot the caller's context first; module-owned bodies
            // then reset to their own below, and the pop restores the
            // caller on every path.
            let module_key = def.module.clone();
            let module_env = module_key.as_deref().and_then(|key| {
                cx.state.modules.get(key).and_then(|record| {
                    record
                        .init
                        .as_ref()
                        .map(|init| (init.envs.clone(), init.inherit_names.clone()))
                })
            });
            cx.state.call_depth += 1;
            // Module-owned calls observe nothing of the importer: the
            // whole variable stack swaps for a fresh one before the
            // call frame pushes, and restores after it pops (#115).
            // Own-module bindings stay visible through the
            // module-store fallback in every accessor, so this only
            // cuts importer frames, never module state.
            let saved_vars = if module_env.as_ref().is_some() {
                Some(std::mem::take(&mut cx.state.var_scopes))
            } else {
                None
            };
            cx.state.push_scope();
            // Module-owned bodies resolve their own file's TYPE aliases
            // first, shadowing globals for the call: a file's bodies
            // validate against the same view (see phase 1), so imports
            // never leak bare names yet self-contained files keep
            // working. Harvested types stay global by explicit request.
            let owner_aliases: Vec<(String, String)> = module_key
                .as_deref()
                .and_then(|key| cx.state.modules.get(key))
                .map(|record| super::typing::collect_type_aliases(&record.steps, cx.state))
                .transpose()?
                .unwrap_or_default()
                .into_iter()
                .collect();
            let saved_type_aliases = cx.state.type_aliases.clone();
            for (name, target) in &owner_aliases {
                cx.state.type_aliases.insert(name.clone(), target.clone());
            }
            // Module-owned bodies execute with their module on the
            // context stack, so name resolution falls back to the
            // module's shared store; entry bodies push `None`, keeping
            // entry functions params-only even when called from module
            // code. Balanced below on every exit path.
            cx.state.module_stack.push(module_key);
            // A module must not inherit its caller's namespace
            // (#115): env resets to the seed plus the module init's
            // own contributions. Workspace selection and cwd flow
            // through untouched, so module code observes the same
            // workspace its importer does. Declared `INHERIT_ENV`
            // names re-read from the host here (a re-inherit of an
            // already-present value leaves no init delta, yet must
            // still admit the name). A module that reads outside that
            // (e.g. the host checkout) declares its own
            // `WORKSPACE`/`WORKDIR` in-function. When the module is
            // still initializing (reentrant init-time self-call) there
            // is no stored env yet: the init scope stays as-is, since
            // it is the module's own in-progress context.
            if let Some((envs, inherit_names)) = module_env {
                cx.state.reset_module_env(envs);
                if !inherit_names.is_empty() {
                    inherit_env(cx, &inherit_names)?;
                }
            }
            // Omitted trailing optionals fill with zero values before
            // the body binds: the arity gate above guarantees every
            // missing position is optional, and registration rejects
            // unzeroable optionals, so the fill cannot fail here.
            for (pname, ptype, optional) in def.params.iter().skip(arg_vals.len()) {
                if !optional {
                    bail!(
                        "internal error: missing non-optional param `${pname}` in {}()",
                        super::base_name(name)
                    );
                }
                arg_vals.push(super::optional_zero_value(ptype).with_context(|| {
                    format!(
                        "function `{}` optional param `${pname}` has no zero value",
                        super::base_name(name)
                    )
                })?);
            }
            let outcome: Result<Value> = (|| {
                // Function-local imports scope to this invocation: push
                // a fresh frame for this unit so the body's imports
                // land here (never the shared unit-top map) and the
                // callee never sees the caller's locals. The pop below
                // runs on every path (the closure captures the outcome
                // as a value first), matching the `push_scope` /
                // `pop_scope` pattern with no unsafe.
                let unit_key = def
                    .module
                    .clone()
                    .unwrap_or_else(|| super::import::ENTRY_UNIT.to_string());
                cx.state.call_alias_frames.push((unit_key, HashMap::new()));
                let flow = (|| {
                    for ((pname, ptype, _), pval) in def.params.iter().zip(arg_vals) {
                        cx.state.declare_var(pname.clone(), ptype.clone(), pval)?;
                    }
                    super::steps::execute_steps(
                        cx.state,
                        cx.process,
                        &def.body,
                        cx.stdin.clone(),
                        false,
                        cx.out.clone(),
                        cx.err.clone(),
                        cx.out_pipe.clone(),
                        cx.stdin_pipe.clone(),
                        false,
                    )
                })();
                // Unconditional pop before `?` propagates: errors and
                // early boundary exits never leak the frame, matching
                // `pop_scope` below. (Panics propagate without popping,
                // exactly like the scope stack: no `catch_unwind`
                // anywhere unwraps them.)
                let _ = cx.state.call_alias_frames.pop();
                let flow = flow?;
                match flow {
                    Flow::Done => Ok(Value::string(String::new())),
                    Flow::Return { value, .. } => Ok(value),
                    Flow::Break { idx } => {
                        bail!(
                            "step {}: BREAK cannot cross function boundary (in {name}())",
                            idx + 1
                        );
                    }
                    Flow::Continue { idx } => {
                        bail!(
                            "step {}: CONTINUE cannot cross function boundary (in {name}())",
                            idx + 1
                        );
                    }
                }
            })();
            let pop_res = cx.state.pop_scope();
            if let Some(saved) = saved_vars {
                cx.state.var_scopes = saved;
            }
            cx.state.call_depth -= 1;
            let _ = cx.state.module_stack.pop();
            cx.state.type_aliases = saved_type_aliases;
            match (outcome, pop_res) {
                (Ok(value), Ok(())) => {
                    let _ = (&def.return_type, &def.return_spelling, def.is_async);
                    Ok(value)
                }
                (Err(e), _) => Err(e),
                (Ok(_), Err(e)) => Err(e),
            }
        }
        FuncBody::Pure(func) => {
            let value = func(arg_vals).with_context(|| format!("function `{name}` failed"))?;
            super::args::check_host_return_value(
                &format!("function `{}` returned", super::base_name(name)),
                &entry.meta.returns,
                &value,
            )?;
            Ok(value)
        }
        FuncBody::Ctx(func) | FuncBody::Both { ctx: func, .. } => {
            let value = func(cx, arg_vals).with_context(|| format!("function `{name}` failed"))?;
            super::args::check_host_return_value(
                &format!("function `{}` returned", super::base_name(name)),
                &entry.meta.returns,
                &value,
            )?;
            Ok(value)
        }
    }
}

/// Evaluate an inline block to a value (`LET $a: STRING = { ... }`): the
/// zero-arg sibling of [`call_func_value`]. The body runs inline on the
/// current thread with inherited stdio in a fresh variable scope; the
/// nearest `RETURN` is the block's value and fallthrough yields `""`
/// (both type-checked by the caller's `declare_var`/`mutate_var`).
/// `BREAK`/`CONTINUE` escaping the body are boundary errors, and inner
/// `CALL`s keep their own function boundary, so a `RETURN` inside one
/// never leaks into the block.
pub(crate) fn block_value<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    body: &[Step],
) -> Result<Value> {
    cx.state.push_scope();
    let outcome: Result<Value> = (|| {
        let flow = super::steps::execute_steps(
            cx.state,
            cx.process,
            body,
            cx.stdin.clone(),
            false,
            cx.out.clone(),
            cx.err.clone(),
            cx.out_pipe.clone(),
            cx.stdin_pipe.clone(),
            false,
        )?;
        match flow {
            Flow::Done => Ok(Value::string(String::new())),
            Flow::Return { value, .. } => Ok(value),
            Flow::Break { idx } => {
                bail!("step {}: BREAK cannot cross block boundary", idx + 1)
            }
            Flow::Continue { idx } => {
                bail!("step {}: CONTINUE cannot cross block boundary", idx + 1)
            }
        }
    })();
    let pop_res = cx.state.pop_scope();
    match (outcome, pop_res) {
        (Ok(value), Ok(())) => Ok(value),
        (Err(e), _) => Err(e),
        (Ok(_), Err(e)) => Err(e),
    }
}

/// Evaluate `RETURN <expr>` to the enclosing boundary's value: a function
/// call, an `ASYNC` task (bound by `LET $out: STRING = AWAIT $t`), or an inline
/// `LET` block. A `RETURN` with no enclosing boundary is rejected where
/// the flow reaches the pipeline top. Uniform everywhere.
pub(crate) fn handle_return<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    idx: usize,
    expr: &Expr,
) -> Result<Flow> {
    let value = super::args::evaluate_expr(expr, cx)?;
    Ok(Flow::Return { idx, value })
}

/// Run `WHILE <bool-expr> { ... }`: re-evaluate the condition in the
/// current scope each iteration (Bool-only, same `is_truthy` rule as `IF`),
/// execute the body in a fresh per-iteration scope, and honor
/// `BREAK`/`CONTINUE`. A `RETURN` inside propagates to the enclosing
/// `call_func`; anything else yields Done.
pub(crate) fn while_loop<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    cond: &Expr,
    body: &[Step],
) -> Result<Flow> {
    use std::sync::atomic::Ordering;
    loop {
        if cx.state.cancel_token.load(Ordering::SeqCst) {
            bail!("ASYNC task cancelled");
        }
        let val = super::args::evaluate_expr(cond, cx)?;
        if !super::args::is_truthy(&val)? {
            return Ok(Flow::Done);
        }
        cx.state.push_scope();
        let res = super::steps::execute_steps(
            cx.state,
            cx.process,
            body,
            cx.stdin.clone(),
            false,
            cx.out.clone(),
            cx.err.clone(),
            cx.out_pipe.clone(),
            cx.stdin_pipe.clone(),
            false,
        );
        let pop_res = cx.state.pop_scope();
        let flow = match (res, pop_res) {
            (Ok(flow), Ok(())) => flow,
            (Err(e), _) => return Err(e),
            (Ok(_), Err(e)) => return Err(e),
        };
        match flow {
            Flow::Done | Flow::Continue { .. } => {}
            Flow::Break { .. } => return Ok(Flow::Done),
            Flow::Return { .. } => return Ok(flow),
        }
    }
}

pub(crate) fn assign<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    var: &str,
    decl_type: String,
    expr: &Expr,
) -> Result<()> {
    let value = super::args::evaluate_expr(expr, cx)?;
    let clean_var = var.trim_start_matches('$').to_string();
    let tag = cx.state.resolve_tag(&decl_type)?;
    cx.state.declare_var(clean_var, tag, value)?;
    Ok(())
}

pub(crate) fn set_var_value<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    var: &str,
    expr: &Expr,
) -> Result<()> {
    let value = super::args::evaluate_expr(expr, cx)?;
    let clean_var = var.trim_start_matches('$').to_string();
    cx.state.mutate_var(&clean_var, value)?;
    Ok(())
}

/// Dispatch `LET $var: STRING = <sync command>` : run the command to completion with
/// a spillable capture sink as its stdout, then bind the exact bytes as a
/// string. Only stdout is captured (stderr keeps the parent wiring; stdin
/// passes through so `WITH_IO [stdin=$p]` still works). Captured bytes
/// never tee into the parent assertion windows. On command failure
/// nothing is bound.
///
/// When the captured command is `NAME(...)`, no sink is installed:
/// the callee's stdout keeps the active routing (observable via
/// `ASSERT_CONTAINS stdout`/pipes) and the bound value is the function's `RETURN`
/// payload (or `""` on fallthrough), coerced to the declared type.
/// A `TIMEOUT`-wrapped single command captures exactly what the bare
/// command captures, with the tightest deadline enforced around it.
pub(crate) fn assign_capture<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    generation: usize,
    idx: usize,
    var: &str,
    decl_type: String,
    cmd: &StepKind,
) -> Result<Flow> {
    use std::sync::Arc;

    match peel_capture_command(cx, cmd)? {
        PeeledCapture::Import {
            bindings,
            path,
            alias,
            deadline,
        } => {
            // `IMPORT` (possibly under `WITH_IO`/`TIMEOUT` layers): no
            // capture sink. The imported pipeline's stdout keeps its
            // routed streams; the bound value is the `RETURN` payload,
            // exactly like `CALL`.
            if bindings
                .iter()
                .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
            {
                bail!(
                    "LET capture cannot use WITH_IO [stdout=$var]; the capture binds the RETURN value"
                );
            }
            let guard = arm_deadline(cx, deadline);
            let result = if bindings.is_empty() {
                super::import::import_file(cx, path, alias)
            } else {
                (|| {
                    let (step_stdin, expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
                        resolve_io_streams(cx, &bindings, cmd)?;
                    let state = &mut *cx.state;
                    let process = &mut *cx.process;
                    let mut sub_cx = super::steps::StepCtx {
                        state,
                        process,
                        stdin: step_stdin,
                        expose_stdin,
                        out: step_stdout,
                        err: step_stderr,
                        out_pipe,
                        stdin_pipe,
                        // `IMPORT` layers never carry a terminal: lowering rejects
                        // `tty` outside `RUN` before execution reaches them.
                        tty: None,
                    };
                    super::import::import_file(&mut sub_cx, path, alias)
                })()
            };
            let value = disarm_deadline(cx, guard, deadline, result)?;
            let clean_var = var.trim_start_matches('$').to_string();
            let tag = cx.state.resolve_tag(&decl_type)?;
            cx.state.declare_var(clean_var, tag, value)?;
            return Ok(Flow::Done);
        }
        PeeledCapture::Call {
            bindings,
            name,
            args,
            deadline,
        } => {
            // `CALL` (possibly under `WITH_IO`/`TIMEOUT` layers): no
            // capture sink. The callee's stdout keeps its routed streams
            // (observable via `ASSERT_CONTAINS stdout`/pipes); the bound
            // value is the `RETURN` payload.
            if bindings
                .iter()
                .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
            {
                bail!(
                    "LET capture cannot use WITH_IO [stdout=$var]; the capture binds the RETURN value"
                );
            }
            let guard = arm_deadline(cx, deadline);
            let result = if bindings.is_empty() {
                call_func_value(cx, name, args)
            } else {
                (|| {
                    let (step_stdin, expose_stdin, step_stdout, step_stderr, out_pipe, stdin_pipe) =
                        resolve_io_streams(cx, &bindings, cmd)?;
                    // Reborrow state/process for the sub-context; `cx` is unused below.
                    let state = &mut *cx.state;
                    let process = &mut *cx.process;
                    let mut sub_cx = super::steps::StepCtx {
                        state,
                        process,
                        stdin: step_stdin,
                        expose_stdin,
                        out: step_stdout,
                        err: step_stderr,
                        out_pipe,
                        stdin_pipe,
                        // `CALL` layers never carry a terminal: lowering rejects
                        // `tty` outside `RUN` before execution reaches them.
                        tty: None,
                    };
                    call_func_value(&mut sub_cx, name, args)
                })()
            };
            let value = disarm_deadline(cx, guard, deadline, result)?;
            let clean_var = var.trim_start_matches('$').to_string();
            let tag = cx.state.resolve_tag(&decl_type)?;
            cx.state.declare_var(clean_var, tag, value)?;
            return Ok(Flow::Done);
        }
        PeeledCapture::Sink => {}
    }
    let sink = Arc::new(super::capture::new_spill_buffer());
    let capture_out = Some(StreamHandle::Stream(sink.writer()));
    let flow = super::steps::execute_single_step_with_generation(
        cx.state,
        cx.process,
        cmd,
        generation,
        idx,
        cx.stdin.clone(),
        cx.expose_stdin,
        capture_out,
        cx.err.clone(),
        // Capture owns stdout (parse rejects stdout pipes here), so there
        // is no backend to carry.
        None,
        None,
        // A `WITH_IO [tty]` capture re-resolves its own request when the
        // inner step runs through `with_io`; ambient carriage stays empty.
        cx.tty,
    )?;
    match flow {
        Flow::Done => {}
        Flow::Break { idx } => {
            bail!("step {}: BREAK outside loop (cannot be captured)", idx + 1);
        }
        Flow::Continue { idx } => {
            bail!(
                "step {}: CONTINUE outside loop (cannot be captured)",
                idx + 1
            );
        }
        Flow::Return { idx, .. } => {
            bail!(
                "step {}: RETURN outside function (cannot be captured)",
                idx + 1
            );
        }
    }
    let text = sink
        .drain_string_strict()
        .map_err(|e| anyhow!("LET ${var} capture is not valid UTF-8: {e}"))?;
    let clean_var = var.trim_start_matches('$').to_string();
    let tag = cx.state.resolve_tag(&decl_type)?;
    cx.state.declare_var(clean_var, tag, Value::string(text))?;
    Ok(Flow::Done)
}

pub(crate) fn if_then<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    cond: &Expr,
    then_body: &[Step],
    else_ifs: &[(Box<Expr>, Vec<Step>)],
    else_body: &Option<Vec<Step>>,
) -> Result<Flow> {
    let val = super::args::evaluate_expr(cond, cx)?;
    if super::args::is_truthy(&val)? {
        return super::steps::execute_scoped_steps(
            cx.state,
            cx.process,
            then_body,
            cx.stdin.clone(),
            false,
            cx.out.clone(),
            cx.err.clone(),
            cx.out_pipe.clone(),
            cx.stdin_pipe.clone(),
            false,
        );
    }
    for (else_cond, else_block) in else_ifs {
        let val = super::args::evaluate_expr(else_cond.as_ref(), cx)?;
        if super::args::is_truthy(&val)? {
            return super::steps::execute_scoped_steps(
                cx.state,
                cx.process,
                else_block,
                cx.stdin.clone(),
                false,
                cx.out.clone(),
                cx.err.clone(),
                cx.out_pipe.clone(),
                cx.stdin_pipe.clone(),
                false,
            );
        }
    }
    if let Some(body) = else_body {
        return super::steps::execute_scoped_steps(
            cx.state,
            cx.process,
            body,
            cx.stdin.clone(),
            false,
            cx.out.clone(),
            cx.err.clone(),
            cx.out_pipe.clone(),
            cx.stdin_pipe.clone(),
            false,
        );
    }
    Ok(Flow::Done)
}

// ── Dispatch functions ──────────────────────────────────────────────────────
// These extract fields from `StepKind` variants, resolve arguments, and
// forward to the actual handler functions. Used by `define_pipeline!`.

/// Collect the pipes a step subtree produces to (`stdout`/`stderr`
/// bindings), same-thread only. Endpoints are always `$var`, so every
/// producer resolves against live state at pin time; no static walk exists
/// by design : with no literals left to name, there is nothing to collect
/// without state. Nested `ASYNC` bodies run on other threads with their
/// own pins and are excluded; `Timeout`/`For`/`If`/`WithIo` bodies run
/// inline and are included. Only producers pin: a task that only reads a
/// pipe relies on EOF-from-detach to complete, so pinning it would
/// deadlock. Each entry pairs the pipe name with whether OS promotion
/// applies (OR-merged across occurrences). Unresolvable names are skipped
/// here (execution-time resolution reports the real error); promotion never
/// applies to dynamic endpoints.
/// One pipe binding sighted in an async body: the owned handle, whether
/// its ultimate consumer/producer is RUN-terminated, and whether this
/// occurrence produces (`stdout`/`stderr`) rather than consumes (`stdin`).
struct BodyBinding {
    handle: PipeHandle,
    produces: bool,
}

/// Resolve one binding endpoint to its handle, skipping unresolvable
/// variables here: execution-time resolution reports the real error.
fn binding_handle<P: ProcessManager>(
    state: &ExecState<P>,
    target: &PipeTarget,
) -> Option<PipeHandle> {
    let PipeTarget::Var(var) = target;
    match state.get_var_typed(var) {
        Some((TypeTag::Pipe, value)) => value.as_pipe_handle(),
        _ => None,
    }
}

/// Collect every pipe binding in a step subtree: producers and consumers
/// alike, same-thread inline bodies only. Nested `ASYNC` bodies run on
/// other threads with their own pins and are excluded, as are deferred
/// `FUNC` bodies and dynamic `Call` targets (they resolve where they run).
/// Unresolvable endpoints are skipped (execution reports the real error).
fn collect_body_bindings<P: ProcessManager>(
    kind: &StepKind,
    state: &ExecState<P>,
    out: &mut Vec<BodyBinding>,
) {
    match kind {
        StepKind::WithIo { bindings, cmd } => {
            // Terminal stdio never promotes: the pty master is one
            // interleaved byte stream pumped through script backends,
            // so its descriptors stay out of the OS-pipe walk even
            // inside `ASYNC` single-`RUN` bodies that would otherwise
            // promote them. Geometry bindings carry no pipes.
            let tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
            for binding in bindings {
                if tty
                    && matches!(
                        binding.stream,
                        IoStream::Stdin | IoStream::Stdout | IoStream::Stderr
                    )
                {
                    continue;
                }
                let Some(target) = &binding.pipe else {
                    continue;
                };
                let Some(handle) = binding_handle(state, target) else {
                    continue;
                };
                out.push(BodyBinding {
                    handle,
                    produces: !matches!(binding.stream, IoStream::Stdin),
                });
            }
            collect_body_bindings(cmd, state, out);
        }
        StepKind::Timeout { body, .. }
        | StepKind::Isolated { body }
        | StepKind::For { body, .. }
        | StepKind::While { body, .. } => {
            for step in body {
                collect_body_bindings(&step.kind, state, out);
            }
        }
        StepKind::If {
            then_body,
            else_ifs,
            else_body,
            ..
        } => {
            for step in then_body {
                collect_body_bindings(&step.kind, state, out);
            }
            for (_, branch) in else_ifs {
                for step in branch {
                    collect_body_bindings(&step.kind, state, out);
                }
            }
            if let Some(body) = else_body {
                for step in body {
                    collect_body_bindings(&step.kind, state, out);
                }
            }
        }
        StepKind::FuncDef { .. }
        | StepKind::Call { .. }
        | StepKind::AsyncBlock { .. }
        | StepKind::AssignAsync { .. } => {}
        _ => {}
    }
}

/// Ensure every pipe an async `body` binds (producers and consumers) is
/// materialized, and pin a keeper slot on each produced pipe : all
/// synchronously on the spawning thread, so backend decisions never
/// depend on thread scheduling.
///
/// Promotion is per-handle by declaration scope: only pipes this task
/// declared and never shared become OS pairs. Anything else stays
/// script-backed, so concurrent tasks can never disagree about EOF
/// propagation. Pins group by the top-level index of the final producer
/// step for each handle: the worker drops a handle's guard once that step
/// completes, so transient gaps between producers never signal EOF while
/// later consumer steps in the same task still observe it. Returns `None`
/// when the body produces to no pipe. A task that only reads a
/// pipe gets existence without a pin (consumers rely on EOF-from-detach,
/// so pinning them would deadlock).
fn pin_async_keepers<P: ProcessManager>(
    cx: &StepCtx<'_, P>,
    body: &[Step],
    worker_task_id: u64,
) -> Result<Option<super::state::KeeperExpiry>> {
    struct Acc {
        handle: PipeHandle,
        last_producer: Option<usize>,
    }
    let mut accs: Vec<Acc> = Vec::new();
    for (idx, step) in body.iter().enumerate() {
        let mut found = Vec::new();
        collect_body_bindings(&step.kind, cx.state, &mut found);
        for b in found {
            match accs.iter_mut().find(|a| a.handle.ptr_eq(&b.handle)) {
                Some(a) => {
                    if b.produces {
                        a.last_producer = Some(idx);
                    }
                }
                None => accs.push(Acc {
                    handle: b.handle,
                    last_producer: b.produces.then_some(idx),
                }),
            }
        }
    }
    // Decide every sighted handle first (consumers included: a consumer
    // arriving before any producer still finds the decided backend
    // instead of racing the producer's setup). Promotion is judged from
    // the worker's perspective: only pipes the worker itself declared and
    // never shared become OS pairs.
    for a in &accs {
        let promote = ExecState::<P>::can_promote_in_task(&a.handle, worker_task_id);
        cx.state.io.ensure_handle(&a.handle, promote)?;
    }
    let mut map: HashMap<usize, Vec<KeeperGuard>> = HashMap::new();
    for a in &accs {
        if let Some(idx) = a.last_producer
            && let Some(guard) = cx.state.io.pin_keeper(&a.handle)?
        {
            map.entry(idx).or_default().push(guard);
        }
    }
    if map.is_empty() {
        Ok(None)
    } else {
        Ok(Some(super::state::KeeperExpiry::new(body, map)))
    }
}

pub(crate) fn dispatch_run<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Run(arg) = step else {
        unreachable!()
    };
    let cmd = super::args::resolve_arg(arg, cx)?;
    let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
    run(cx, &cmd)
}

pub(crate) fn dispatch_run_exec<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::RunExec { argv } = step else {
        unreachable!()
    };
    let resolved = resolve_run_exec_argv(argv, cx)?;
    run_argv(cx, &resolved)
}

pub(crate) fn dispatch_async_block<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AsyncBlock { body } = step else {
        unreachable!()
    };

    // Pre-allocate keeper handles synchronously on this thread, before the
    // worker exists, so pipes the block produces to can never observe a
    // transient-only zero-writer window. Guards expire by step index as
    // the worker completes its final producer steps, then ride out the
    // thread in forked state.
    let body = body.clone();
    // Anonymous workers get an identity up front: the pin walk judges
    // promotion from the worker's perspective, and pipes the worker mints
    // carry this id as their declaration origin. Allocation runs the
    // retained-finished sweep so anonymous spawns share the single
    // capacity gate.
    let worker_task_id = cx.state.alloc_task_id()?;
    let expiry = pin_async_keepers(cx, &body, worker_task_id)?;

    // Fork the execution state for the child thread.
    // This clones the fs (via clone_box), envs, cwd, var_scopes, etc.
    // The child gets fresh bg_children and scope_stack.
    let mut forked_state = cx.state.fork();
    forked_state.keeper_expiry = expiry;
    forked_state.task_id = worker_task_id;
    cx.state.mark_captured_pipes_escaped();
    let forked_process = cx.process.clone();
    let stdin = cx.stdin.clone();
    let expose_stdin = cx.expose_stdin;
    let out = cx.out.clone();
    let err = cx.err.clone();
    // Live pipe backends travel with the worker: without them a REMOTE
    // step inside the task loses its streaming backend (session
    // accumulates, core flushes at completion) instead of delivering
    // bytes as they arrive.
    let out_pipe = cx.out_pipe.clone();
    let stdin_pipe = cx.stdin_pipe.clone();
    // Hold a keeper on the inherited stdout backend for the worker's
    // lifetime: transient writer churn would otherwise toggle the close
    // latch mid-flight, letting a concurrent drain observe EOF (and exit)
    // during a producer lull. Keepers never resurrect a closed pipe and
    // explicit close still wins, so drain-after-join is unaffected.
    let out_keepalive = out_pipe
        .as_ref()
        .map(|backend| KeeperGuard::new(std::sync::Arc::clone(backend)));
    let cancel_token = std::sync::Arc::clone(&forked_state.cancel_token);
    let cancel_hub = std::sync::Arc::clone(&forked_state.cancel_hub);
    let active_process = std::sync::Arc::clone(&forked_state.active_process);
    let worker: std::sync::Arc<std::sync::Mutex<Option<std::thread::ThreadId>>> =
        std::sync::Arc::new(std::sync::Mutex::new(None));
    let worker_child = std::sync::Arc::clone(&worker);

    // Spawn a thread that executes the block's steps with subshell isolation.
    // ENV/WORKDIR/etc mutations in the block do not leak to the parent.
    // Control flow never crosses the thread boundary: a stray BREAK,
    // CONTINUE, or RETURN becomes a step-numbered error here.
    let join = std::thread::spawn(move || {
        // Slot guard first: dropping on return or unwind releases the
        // global live-task count, so the cap tracks threads actually
        // alive rather than table entries.
        let _slot =
            super::state::TaskSlotGuard::new(std::sync::Arc::clone(&forked_state.live_tasks));
        *worker_child.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::thread::current().id());
        let _out_keepalive = out_keepalive;
        let mut child_state = forked_state;
        let mut child_process = forked_process;
        let flow = super::steps::execute_steps(
            &mut child_state,
            &mut child_process,
            &body,
            stdin,
            expose_stdin,
            out,
            err,
            out_pipe,
            stdin_pipe,
            true, // wait_at_end: child waits for its own bg_children
        )?;
        match flow {
            Flow::Done => Ok(()),
            Flow::Break { idx } => {
                anyhow::bail!("step {}: BREAK cannot cross ASYNC boundary", idx + 1);
            }
            Flow::Continue { idx } => {
                anyhow::bail!("step {}: CONTINUE cannot cross ASYNC boundary", idx + 1);
            }
            Flow::Return { idx, .. } => {
                anyhow::bail!("step {}: RETURN cannot cross ASYNC boundary", idx + 1);
            }
        }
    });

    // Store the thread handle as a background handle in the parent's state.
    cx.state.bg_children.push(super::state::BgChild {
        handle: Box::new(super::steps::ThreadJoinHandle::new(
            join,
            cancel_token,
            cancel_hub,
            active_process,
            worker,
        )),
        task_id: worker_task_id,
    });
    Ok(())
}

pub(crate) fn dispatch_echo<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Echo(arg) = step else {
        unreachable!()
    };
    let msg = super::args::resolve_arg(arg, cx)?;
    echo(cx, &msg)
}

pub(crate) fn dispatch_workdir<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Workdir(arg) = step else {
        unreachable!()
    };
    let path = super::args::resolve_arg(arg, cx)?;
    workdir(cx, &path)
}

pub(crate) fn dispatch_workspace<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Workspace(target) = step else {
        unreachable!()
    };
    workspace(cx, target)
}

pub(crate) fn dispatch_remote<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::RemoteBlock {
        target,
        vars,
        env,
        body,
    } = step
    else {
        unreachable!()
    };
    super::remote::run_remote_block(cx, target, vars, env, body)
}

pub(crate) fn dispatch_env<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Env { key, value } = step else {
        unreachable!()
    };
    let resolved = super::args::resolve_arg(value, cx)?;
    env(cx, key, &resolved)
}

pub(crate) fn dispatch_copy<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Copy {
        from_workspace,
        from_host,
        to_host,
        from,
        to,
    } = step
    else {
        unreachable!()
    };
    if *from_host || *to_host {
        return super::remote::copy_transfer(cx, *from_host, *to_host, from, to);
    }
    let from_resolved = super::args::resolve_arg(from, cx)?;
    let to_resolved = super::args::resolve_arg(to, cx)?;
    copy(cx, from_workspace.clone(), &from_resolved, &to_resolved)
}

pub(crate) fn dispatch_archive<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Archive { src, dst, raw } = step else {
        unreachable!()
    };
    let src_resolved = super::args::resolve_arg(src, cx)?;
    let dst_resolved = super::args::resolve_arg(dst, cx)?;
    archive(cx, &src_resolved, &dst_resolved, *raw)
}

pub(crate) fn dispatch_unarchive<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Unarchive {
        src,
        dst,
        max_bytes,
    } = step
    else {
        unreachable!()
    };
    let src_resolved = super::args::resolve_arg(src, cx)?;
    let dst_resolved = super::args::resolve_arg(dst, cx)?;
    let cap_resolved = super::args::resolve_arg_opt(max_bytes, cx)?;
    unarchive(cx, &src_resolved, &dst_resolved, cap_resolved.as_deref())
}

pub(crate) fn dispatch_copy_git<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::CopyGit {
        rev,
        from,
        to,
        include_dirty,
    } = step
    else {
        unreachable!()
    };
    let rev_resolved = super::args::resolve_arg(rev, cx)?;
    let from_resolved = super::args::resolve_arg(from, cx)?;
    let to_resolved = super::args::resolve_arg(to, cx)?;
    copy_git(
        cx,
        &rev_resolved,
        &from_resolved,
        &to_resolved,
        *include_dirty,
    )
}

pub(crate) fn dispatch_symlink<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Symlink {
        from_workspace,
        from,
        to,
    } = step
    else {
        unreachable!()
    };
    let from_resolved = super::args::resolve_arg(from, cx)?;
    let to_resolved = super::args::resolve_arg(to, cx)?;
    symlink(cx, from_workspace.clone(), &from_resolved, &to_resolved)
}

pub(crate) fn dispatch_mkdir<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Mkdir(arg) = step else {
        unreachable!()
    };
    let path = super::args::resolve_arg(arg, cx)?;
    mkdir(cx, &path)
}

pub(super) fn install<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    from: &str,
    to: &str,
) -> Result<()> {
    let from_abs = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, from)
        .with_context(|| format!("INSTALL {from} {to}"))?;
    let to_abs = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, to)
        .with_context(|| format!("INSTALL {from} {to}"))?;
    cx.state
        .fs
        .install_file_atomic(&from_abs, &to_abs, EXECUTABLE_MODE)
        .with_context(|| format!("INSTALL {from} {to}"))?;
    Ok(())
}

pub(crate) fn dispatch_install<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Install { from, to } = step else {
        unreachable!()
    };
    let from_resolved = super::args::resolve_arg(from, cx)?;
    let to_resolved = super::args::resolve_arg(to, cx)?;
    install(cx, &from_resolved, &to_resolved)
}

pub(crate) fn dispatch_set_executable<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::SetExecutable { path } = step else {
        unreachable!()
    };
    let resolved = super::args::resolve_arg(path, cx)?;
    set_executable(cx, &resolved)
}

pub(crate) fn dispatch_ls<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Ls(arg) = step else {
        unreachable!()
    };
    let resolved = super::args::resolve_arg_opt(arg, cx)?;
    ls(cx, &resolved)
}

pub(crate) fn dispatch_read<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Read(arg) = step else {
        unreachable!()
    };
    let resolved = super::args::resolve_arg_opt(arg, cx)?;
    read(cx, &resolved)
}

pub(crate) fn dispatch_read_line<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::ReadLine { var } = step else {
        unreachable!()
    };
    read_line(cx, var)
}

/// Render the terminal prompt: `{message} [{default}]: ` with a default,
/// `{message}: ` without one. Pure so unit tests pin it without a TTY.
#[cfg_attr(miri, allow(dead_code))]
pub(super) fn format_prompt(message: &str, default: Option<&str>) -> String {
    match default {
        Some(d) => format!("{message} [{d}]: "),
        None => format!("{message}: "),
    }
}

/// Map a trimmed answer line onto its binding: empty input yields the
/// default when one exists, else an empty string. Pure so unit tests pin
/// it without a TTY.
#[cfg_attr(miri, allow(dead_code))]
pub(super) fn apply_prompt_answer(line: &str, default: Option<&str>) -> String {
    if line.is_empty() {
        default.unwrap_or("").to_string()
    } else {
        line.to_string()
    }
}

pub(super) fn prompt<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    var: &str,
    message: &str,
    default: Option<&str>,
) -> Result<()> {
    // No Miri special-case: `SyntheticProcessManager::stdin_is_terminal`
    // reports false without touching a fd, so under Miri this always
    // takes the non-interactive branch below (default binds, else
    // bail). The terminal-reading tail is unreachable there.
    let clean_var = var.trim_start_matches('$').to_string();
    // Interactivity needs both a host TTY and an unredirected
    // stdin: a `WITH_IO [stdin=...]` pipe can never answer a
    // prompt, so PROMPT short-circuits instead of blocking on it.
    if !cx.process.stdin_is_terminal() || cx.stdin.is_redirected() {
        match default {
            Some(d) => {
                eprintln!("non-interactive: using default for {message}");
                let text = Value::string(d.to_string());
                bind_prompt_var(cx, &clean_var, text)?;
                return Ok(());
            }
            None => {
                bail!("PROMPT {message}: non-TTY stdin has no answer and no default",);
            }
        }
    }
    let rendered = format_prompt(message, default);
    {
        use std::io::Write;
        let mut err = std::io::stderr().lock();
        err.write_all(rendered.as_bytes())
            .with_context(|| format!("PROMPT {message}: failed to write prompt"))?;
        err.flush()
            .with_context(|| format!("PROMPT {message}: failed to flush prompt"))?;
    }
    let mut line = String::new();
    let n = std::io::stdin()
        .read_line(&mut line)
        .with_context(|| format!("PROMPT {message}: failed reading stdin"))?;
    if n == 0 && line.is_empty() {
        bail!("PROMPT {message}: EOF on stdin before any input",);
    }
    let trimmed = line
        .strip_suffix("\r\n")
        .or_else(|| line.strip_suffix('\n'))
        .unwrap_or(&line);
    let text = Value::string(apply_prompt_answer(trimmed, default));
    bind_prompt_var(cx, &clean_var, text)?;
    Ok(())
}

#[cfg_attr(miri, allow(dead_code))]
fn bind_prompt_var<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    clean_var: &str,
    text: Value,
) -> Result<()> {
    if cx.state.get_var_typed(clean_var).is_some() {
        cx.state
            .mutate_var(clean_var, text)
            .with_context(|| format!("PROMPT ${clean_var}"))?;
    } else {
        cx.state
            .declare_var(clean_var.to_string(), TypeTag::String, text)
            .with_context(|| format!("PROMPT ${clean_var}"))?;
    }
    Ok(())
}

pub(crate) fn dispatch_prompt<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Prompt {
        var,
        message,
        default,
    } = step
    else {
        unreachable!()
    };
    let message_resolved = super::args::resolve_arg(message, cx)?;
    let default_resolved = match default {
        Some(d) => Some(super::args::resolve_arg(d, cx)?),
        None => None,
    };
    prompt(cx, var, &message_resolved, default_resolved.as_deref())
}

/// Dispatch `LIST_APPEND $list <item>` : append to a LIST binding in
/// place (copy-on-write: sole owners mutate with no copy, aliases
/// detach). Touches no stream: like SLEEP it is a step effect, not an
/// IO filter, so pipeline bindings resolve but carry no bytes.
pub(super) fn push_into<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    var: &str,
    item: Value,
) -> Result<()> {
    cx.state
        .push_into_list(var, item)
        .with_context(|| format!("LIST_APPEND ${var}"))
}

pub(crate) fn dispatch_push_into_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::ListAppend { list, item } = step else {
        unreachable!()
    };
    let value = super::args::evaluate_assert_operand(item, cx)?;
    push_into(cx, list, value)
}

pub(crate) fn dispatch_write<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Write { path, contents } = step else {
        unreachable!()
    };
    let path_resolved = super::args::resolve_arg(path, cx)?;
    let contents_resolved = super::args::resolve_arg_opt(contents, cx)?;
    write(cx, &path_resolved, contents_resolved.as_deref())
}

pub(crate) fn dispatch_append<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Append { path, contents } = step else {
        unreachable!()
    };
    let path_resolved = super::args::resolve_arg(path, cx)?;
    let contents_resolved = super::args::resolve_arg_opt(contents, cx)?;
    append(cx, &path_resolved, contents_resolved.as_deref())
}

pub(crate) fn dispatch_append_line<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AppendLine { path, contents } = step else {
        unreachable!()
    };
    let path_resolved = super::args::resolve_arg(path, cx)?;
    let contents_resolved = super::args::resolve_arg(contents, cx)?;
    append_line(cx, &path_resolved, &contents_resolved)
}

pub(super) fn append_line<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path: &str,
    contents: &str,
) -> Result<()> {
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, path)
        .with_context(|| format!("APPEND_LINE {path}"))?;
    cx.state
        .fs
        .ensure_parent_dir(&target)
        .with_context(|| format!("failed to create parent for {}", target.display()))?;
    let mut line = contents.to_string();
    line.push('\n');
    cx.state
        .fs
        .append_file(&target, line.as_bytes())
        .with_context(|| format!("failed to append to {}", target.display()))?;
    Ok(())
}

pub(super) fn remove<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    path: &str,
    recursive: bool,
) -> Result<()> {
    // Removal resolves against the ambient cwd. The deletion guard
    // below compares against the real run cwd and roots, so a module
    // can never remove the caller's working directory out from
    // under it.
    let cwd = cx.state.cwd.clone();
    let target = cx
        .state
        .fs
        .resolve_write(&cwd, path)
        .with_context(|| format!("REMOVE {path}"))?;
    // Root and working-directory deletion guard: removing the cwd (or any
    // of its ancestors), the workspace root, or the effective root (`/`
    // under `WORKSPACE SYSTEM`) would destroy the execution context or
    // the host root, so fail closed before any filesystem driver runs.
    // Both sides compare canonicalized: symlinked prefixes would
    // otherwise defeat a lexical equality check. Guarded against the
    // ambient cwd, which is the same in every file.
    let guard_cwd = cx.state.cwd.clone();
    let cwd_canon = cx
        .state
        .fs
        .canonicalize(&guard_cwd)
        .unwrap_or_else(|_| guard_cwd.clone());
    if target == cwd_canon
        || cwd_canon.as_path().starts_with(target.as_path())
        || Some(&target) == cx.state.fs.workspace_root()
        || target == *cx.state.fs.root()
    {
        bail!("REMOVE {path}: cannot remove working directory or workspace root",);
    }
    // Lexical link probe: canonical resolution routes through the
    // final link, so a link would otherwise read as its target and the
    // target would be deleted instead of the link.
    if cx
        .state
        .fs
        .remove_link_if_symlink(&cwd, path)
        .with_context(|| format!("REMOVE {path}"))?
    {
        return Ok(());
    }
    match cx.state.fs.entry_kind_no_follow(&target) {
        Err(_) => bail!("REMOVE {path}: no such file or directory"),
        Ok(EntryKind::File) => {
            cx.state
                .fs
                .remove_file(&target)
                .with_context(|| format!("REMOVE {path}"))?;
            Ok(())
        }
        // A link reaching here appeared between the probe and the
        // resolve: fail closed rather than touch its target.
        Ok(EntryKind::Symlink) => bail!("REMOVE {path}: link changed during removal",),
        Ok(EntryKind::Dir) => {
            if recursive {
                cx.state
                    .fs
                    .remove_dir_all(&target)
                    .with_context(|| format!("REMOVE {path}"))?;
                Ok(())
            } else {
                cx.state.fs.remove_empty_dir(&target).with_context(|| {
                    format!("REMOVE {path}: directory not empty (use --recursive)",)
                })?;
                Ok(())
            }
        }
    }
}

pub(crate) fn dispatch_remove<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Remove { path, recursive } = step else {
        unreachable!()
    };
    let path_resolved = super::args::resolve_arg(path, cx)?;
    remove(cx, &path_resolved, *recursive)
}

pub(crate) fn dispatch_expand<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Expand { path, overrides } = step else {
        unreachable!()
    };
    let path_resolved = super::args::resolve_arg_opt(path, cx)?;
    let overrides_resolved = super::args::resolve_overrides(overrides, cx)?;
    replace(cx, &path_resolved, &overrides_resolved)
}

fn dispatch_assert_equality<P: ProcessManager>(
    hash: &Option<String>,
    actual: &oxdock_parser::AssertTarget,
    expected: &Option<Arg>,
    cx: &mut StepCtx<'_, P>,
    verb: &str,
    expect_equal: bool,
) -> Result<()> {
    let target = super::steps::resolve_assert_target(actual, cx)?;
    let expected_val = match expected {
        Some(e) => Some(super::args::evaluate_assert_operand(e, cx)?),
        None => None,
    };
    assert_equality(
        cx,
        0,
        verb,
        expect_equal,
        hash,
        &target,
        expected_val.as_ref(),
    )
}

pub(crate) fn dispatch_assert_eq<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AssertEq {
        hash,
        actual,
        expected,
    } = step
    else {
        unreachable!()
    };
    dispatch_assert_equality(hash, actual, expected, cx, Command::AssertEq.as_str(), true)
}

pub(crate) fn dispatch_assert_ne<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AssertNe {
        hash,
        actual,
        expected,
    } = step
    else {
        unreachable!()
    };
    dispatch_assert_equality(
        hash,
        actual,
        expected,
        cx,
        Command::AssertNe.as_str(),
        false,
    )
}

pub(crate) fn dispatch_assert_contains<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AssertContains { haystack, needle } = step else {
        unreachable!()
    };
    let target = super::steps::resolve_assert_target(haystack, cx)?;
    assert_contains(cx, 0, 0, &target, needle)
}

pub(crate) fn dispatch_exit<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Exit(code) = step else {
        unreachable!()
    };
    let code = super::args::resolve_arg_as_int(code, cx)?;
    exit(cx, code)
}

pub(crate) fn dispatch_inherit_env<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::InheritEnv { keys } = step else {
        unreachable!()
    };
    inherit_env(cx, keys)
}

pub(crate) fn dispatch_isolated_inherit_env<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::IsolatedInheritEnv { keys } = step else {
        unreachable!()
    };
    isolated_inherit_env(cx, keys)
}

// ── Structural dispatch wrappers ────────────────────────────────────────────

pub(crate) fn dispatch_for_loop<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::For {
        key_var,
        key_type,
        var,
        var_type,
        in_expr,
        body,
    } = step
    else {
        unreachable!()
    };
    top_level_flow(for_loop(
        cx,
        key_var.as_deref(),
        key_type.clone(),
        var,
        var_type.clone(),
        in_expr,
        body,
    )?)
}

pub(crate) fn dispatch_if_then<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::If {
        cond,
        then_body,
        else_ifs,
        else_body,
    } = step
    else {
        unreachable!()
    };
    top_level_flow(if_then(cx, cond, then_body, else_ifs, else_body)?)
}

pub(crate) fn dispatch_assign<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Assign {
        var,
        decl_type,
        expr,
    } = step
    else {
        unreachable!()
    };
    assign(cx, var, decl_type.clone(), expr)
}

pub(crate) fn dispatch_set<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Set { var, expr } = step else {
        unreachable!()
    };
    set_var_value(cx, var, expr)
}

pub(crate) fn dispatch_with_io<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::WithIo { bindings, cmd } = step else {
        unreachable!()
    };
    top_level_flow(with_io(cx, 0, 0, bindings, cmd)?)
}

pub(crate) fn dispatch_with_io_block<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::WithIoBlock { bindings } = step else {
        unreachable!()
    };
    with_io_block(cx, 0, 0, bindings)
}

pub(crate) fn dispatch_func_def<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::FuncDef {
        name,
        params,
        return_type,
        is_async,
        body,
        ..
    } = step
    else {
        unreachable!()
    };
    define_func(cx, name, params, return_type, *is_async, body)
}

pub(crate) fn dispatch_import_file<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::ImportFile { path, alias } = step else {
        unreachable!()
    };
    super::import::import_file(cx, path, alias).map(|_| ())
}

pub(crate) fn dispatch_import_funcs<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::ImportFuncs {
        path,
        alias,
        func_names,
        type_names,
    } = step
    else {
        unreachable!()
    };
    super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)
}

pub(crate) fn dispatch_call<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Call { name, args } = step else {
        unreachable!()
    };
    call_func_value(cx, name, args).map(|_| ())
}

pub(crate) fn dispatch_return<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Return { expr, .. } = step else {
        unreachable!()
    };
    top_level_flow(handle_return(cx, 0, expr)?)
}

pub(crate) fn dispatch_while_loop<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::While { cond, body } = step else {
        unreachable!()
    };
    top_level_flow(while_loop(cx, cond, body)?)
}

pub(crate) fn dispatch_break<P: ProcessManager>(
    step: &StepKind,
    _cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Break = step else {
        unreachable!()
    };
    bail!("BREAK outside loop");
}

pub(crate) fn dispatch_continue<P: ProcessManager>(
    step: &StepKind,
    _cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Continue = step else {
        unreachable!()
    };
    bail!("CONTINUE outside loop");
}

// ── AWAIT / AssignAsync handlers ─────────────────────────────────────────

/// Whether an ASYNC body can publish a value: true when any step in its
/// own scope is a `RETURN`. Nested `FUNC` definitions and nested `ASYNC`
/// bodies belong to inner scopes and never count, and bare `Call` and
/// bare `IMPORT` statements discard their values. A body that can return
/// but falls off the end fails its capture loudly, so a missing fallback
/// branch can never silently yield the void-task zero.
fn body_returns_value(body: &[Step]) -> bool {
    body.iter().any(|step| step_returns_value(&step.kind))
}

fn step_returns_value(kind: &StepKind) -> bool {
    match kind {
        StepKind::Return { .. } => true,
        // Bare `Call` and bare `IMPORT` statements discard their values
        // in every position, task bodies included: only `RETURN`
        // publishes.
        StepKind::WithIo { cmd, .. } => step_returns_value(cmd),
        StepKind::For { body, .. }
        | StepKind::While { body, .. }
        | StepKind::Timeout { body, .. }
        | StepKind::Isolated { body } => body_returns_value(body),
        StepKind::If {
            then_body,
            else_ifs,
            else_body,
            ..
        } => {
            body_returns_value(then_body)
                || else_ifs
                    .iter()
                    .any(|(_, branch)| body_returns_value(branch))
                || else_body
                    .as_ref()
                    .is_some_and(|body| body_returns_value(body))
        }
        StepKind::FuncDef { .. } | StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => {
            false
        }
        _ => false,
    }
}

/// Dispatch `LET $var: TYPE = ASYNC { ... }` : spawn a background task and store
/// the handle in the variable scope.
pub(crate) fn dispatch_assign_async<P: ProcessManager>(
    var: &str,
    decl_type: String,
    body: &[Step],
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    // Generate a unique task ID. Allocation refuses past the live-task
    // cap, so a spawn storm fails the step loudly instead of wedging
    // the host.
    let task_id = cx.state.alloc_task_id()?;

    // Pre-allocate keeper handles synchronously on this thread, before the
    // worker exists, so pipes the task produces to (e.g. keeper
    // `WITH_IO [stdout=$tx] ASYNC ...` bindings) can never observe a
    // transient-only zero-writer window. Guards expire by step index as
    // the worker completes its final producer steps. The pin walk judges
    // promotion from the worker's perspective (task_id is already drawn).
    let body = body.to_vec();
    let expiry = pin_async_keepers(cx, &body, task_id)?;

    // Fork the execution state for the child thread
    let mut forked_state = cx.state.fork();
    forked_state.keeper_expiry = expiry;
    // Stamp the worker identity before the thread starts, and mark every
    // pipe visible here as shared: forking copies the whole environment,
    // so each of them is capturable whether or not the body names it.
    // Either step keeps later promotion checks honest on every thread.
    forked_state.task_id = task_id;
    cx.state.mark_captured_pipes_escaped();
    let forked_process = cx.process.clone();
    let stdin = cx.stdin.clone();
    let expose_stdin = cx.expose_stdin;
    // Tasks share the parent writer: output streams live, exactly like the
    // main flow. A task's *value* (for `LET $out: STRING = AWAIT $t`) travels only
    // through an explicit `RETURN`, like a function call. A copy of every
    // default-routed byte also lands in the task's tail ring for
    // `TASK_POLL`. Stderr keeps parent wiring. Live pipe backends ride
    // along the same way, so a REMOTE step in the task keeps streaming.
    let tails = std::sync::Arc::new(std::sync::Mutex::new(super::state::TaskTails::new()));
    let out = TaskTee::wrap(cx.out.clone(), &tails, TeeStream::Stdout);
    let err = TaskTee::wrap(cx.err.clone(), &tails, TeeStream::Stderr);
    let out_pipe = cx.out_pipe.clone();
    let stdin_pipe = cx.stdin_pipe.clone();
    // Same lifetime hold as the block-task worker: a concurrent drain
    // must block through producer lulls, not observe a flickered EOF.
    let out_keepalive = out_pipe
        .as_ref()
        .map(|backend| KeeperGuard::new(std::sync::Arc::clone(backend)));
    let cancel_token = std::sync::Arc::clone(&forked_state.cancel_token);
    let cancel_hub = std::sync::Arc::clone(&forked_state.cancel_hub);
    let active_process = std::sync::Arc::clone(&forked_state.active_process);
    let worker: std::sync::Arc<std::sync::Mutex<Option<std::thread::ThreadId>>> =
        std::sync::Arc::new(std::sync::Mutex::new(None));
    let worker_child = std::sync::Arc::clone(&worker);

    // Spawn the task thread. Leftover guards unpin at thread termination.
    // Every body runs the block path below: a task publishes a value
    // only through an explicit `RETURN`, which the entry records for
    // `LET $out: STRING = AWAIT $t`. A body with no `RETURN` yields `INT` 0 on
    // success; a body that can return but fell off the end fails its
    // capture loudly. Control flow never crosses the thread boundary:
    // stray BREAK/CONTINUE become errors here.
    // A task publishes a value only through an explicit `RETURN`.
    // Recorded on the entry so a later capture can tell "void task"
    // (binds 0) from "fell off the end" (loud error).
    let returns_value = body_returns_value(&body);
    let (entry_tx, entry_rx) = std::sync::mpsc::channel::<Arc<super::state::TaskEntry>>();
    let join = std::thread::spawn(move || {
        // Slot guard first: dropping on return or unwind releases the
        // global live-task count, so the cap tracks threads actually
        // alive rather than table entries.
        let _slot =
            super::state::TaskSlotGuard::new(std::sync::Arc::clone(&forked_state.live_tasks));
        *worker_child.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::thread::current().id());
        let _out_keepalive = out_keepalive;
        let mut child_state = forked_state;
        let mut child_process = forked_process;
        let entry = entry_rx
            .recv()
            .map_err(|_| anyhow::anyhow!("ASYNC task entry unavailable"))?;
        let flow = super::steps::execute_steps(
            &mut child_state,
            &mut child_process,
            &body,
            stdin,
            expose_stdin,
            out,
            err,
            out_pipe,
            stdin_pipe,
            true,
        )?;
        match flow {
            Flow::Done => Ok(()),
            Flow::Break { idx } => {
                anyhow::bail!("step {}: BREAK cannot cross ASYNC boundary", idx + 1);
            }
            Flow::Continue { idx } => {
                anyhow::bail!("step {}: CONTINUE cannot cross ASYNC boundary", idx + 1);
            }
            Flow::Return { value, .. } => {
                // Only an explicit `RETURN` publishes a task value;
                // there is no stdout sniffing. `LET $out: STRING = AWAIT $t`
                // binds this value.
                entry
                    .state
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .return_value = Some(value);
                Ok(())
            }
        }
    });

    // Create the thread handle
    let handle =
        super::steps::ThreadJoinHandle::new(join, cancel_token, cancel_hub, active_process, worker);

    // Store in named_tasks as a synchronized entry. The handle lives inside
    // the entry so CANCEL can tear it down even under concurrent AWAIT.
    // Published to the child above so tasks store their RETURN value
    // under the entry lock. The entry also owns the tail ring fed by
    // the worker tee, so TASK_POLL can snapshot output mid-flight.
    {
        let mut named = cx
            .state
            .named_tasks
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let entry = Arc::new(super::state::TaskEntry::new(
            Box::new(handle),
            returns_value,
            Arc::clone(&tails),
        ));
        named.insert(task_id, Arc::clone(&entry));
        let _ = entry_tx.send(entry);
    }

    // Store the task handle in the variable scope
    let tag = cx.state.resolve_tag(&decl_type)?;
    cx.state
        .declare_var(var.to_string(), tag, Value::handle(task_id))?;
    Ok(())
}

/// Dispatch `AWAIT $var` : block until the named task completes, propagate
/// error if it failed.
///
/// State machine (`TaskEntry`): the first `AWAIT` transitions the entry
/// `Running -> Awaiting` and owns the bounded poll loop below. A concurrent
/// `CANCEL` (or a `TIMEOUT` deadline) transitions the entry to `Cancelled`;
/// this loop observes that within ~10ms and rendezvouses on teardown
/// completion before reporting cancellation.
/// Resolve a task-handle variable to its shared registry entry.
fn resolve_task_entry<P: ProcessManager>(
    var: &str,
    cx: &StepCtx<'_, P>,
) -> Result<Arc<super::state::TaskEntry>> {
    // Resolve the variable to a TaskHandle
    let val = cx
        .state
        .get_var(var)
        .ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
    let Some(task_id) = val.as_handle() else {
        bail!("variable '${var}' is not a task handle");
    };
    resolve_task_entry_by_id(task_id, &format!("${var}"), cx)
}

/// Resolve a task id to its shared registry entry. Backs single-handle
/// AWAIT plus the per-member path of LIST AWAIT so double-await and
/// already-reaped reporting never diverge. `TASK_POLL` reuses the same
/// lookup so deserialized ids resolve without a scope variable.
pub(crate) fn resolve_task_entry_by_id<P: ProcessManager>(
    task_id: u64,
    label: &str,
    cx: &StepCtx<'_, P>,
) -> Result<Arc<super::state::TaskEntry>> {
    // Clone the shared entry under a short map lock.
    let entry = {
        let named = cx
            .state
            .named_tasks
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        named.get(&task_id).cloned()
    };
    let Some(entry) = entry else {
        bail!("task handle for '{label}' was not found or has already been awaited");
    };
    Ok(entry)
}

/// Claim a task entry and run the bounded await poll loop to completion.
/// Shared by bare `AWAIT` and `LET $o: TYPE = AWAIT $t` so cancellation, timeout,
/// double-await, and failure semantics never diverge. Returns the child's
/// exit status. Task output already streamed live during the run; there is
/// nothing to forward or bind here.
fn await_task_entry(
    entry: &Arc<super::state::TaskEntry>,
    cancel_token: &Arc<std::sync::atomic::AtomicBool>,
    var: &str,
) -> Result<std::process::ExitStatus> {
    use super::state::TaskPhase;

    // Claim the entry for awaiting.
    {
        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
        match guard.phase {
            TaskPhase::Cancelled => {
                drop(guard);
                // Teardown barrier: never outrun the killer's join.
                entry.wait_reaped();
                bail!("AWAIT task '${var}' was cancelled");
            }
            TaskPhase::Completed | TaskPhase::Awaiting => {
                bail!("task handle for '${var}' was not found or has already been awaited");
            }
            TaskPhase::Running => {
                guard.phase = TaskPhase::Awaiting;
            }
        }
    }

    // Bounded poll loop. Every iteration runs under a short entry lock and
    // then sleeps ~10ms, so concurrent CANCEL and TIMEOUT preemption land
    // within one tick without holding any mutex across blocking calls.
    loop {
        enum Decision {
            Pending,
            /// Entry was cancelled externally; rendezvous then report.
            Cancelled,
            /// Deadline fired while awaiting: this thread owns the kill.
            KillOnTimeout,
            /// Natural completion with the child's exit status.
            Done(std::process::ExitStatus),
        }
        // Stage the blocking work (if any) under a short lock, then act
        // outside the lock.
        let mut timeout_kill: Option<Box<dyn BackgroundHandle>> = None;
        let decision = {
            let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
            if matches!(guard.phase, TaskPhase::Cancelled) {
                Decision::Cancelled
            } else if cancel_token.load(std::sync::atomic::Ordering::SeqCst) {
                // Parent TIMEOUT watcher fired while awaiting: the named
                // child's OS process lives on the child's own
                // `active_process`, unreachable from the watcher, so this
                // thread performs the kill via the shared entry.
                match guard.handle.take() {
                    Some(handle) => {
                        guard.phase = TaskPhase::Cancelled;
                        timeout_kill = Some(handle);
                        Decision::KillOnTimeout
                    }
                    // Lost the race with CANCEL's take: fall through to the
                    // teardown barrier below.
                    None => Decision::Cancelled,
                }
            } else {
                match guard.handle.as_mut() {
                    Some(handle) => match handle.try_wait() {
                        Ok(Some(status)) => {
                            let _ = guard.handle.take();
                            guard.phase = TaskPhase::Completed;
                            Decision::Done(status)
                        }
                        Ok(None) => Decision::Pending,
                        Err(err) => {
                            let _ = guard.handle.take();
                            guard.phase = TaskPhase::Completed;
                            // Surface the child failure after marking the
                            // terminal state below.
                            drop(guard);
                            entry.finish_teardown();
                            return Err(err);
                        }
                    },
                    // No handle while still active: another thread took it
                    // and flipped the phase; re-observe on the next tick.
                    None => Decision::Cancelled,
                }
            }
        };
        match decision {
            Decision::Pending => {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            Decision::Cancelled => {
                entry.wait_reaped();
                bail!("AWAIT task '${var}' was cancelled");
            }
            Decision::KillOnTimeout => {
                if let Some(mut handle) = timeout_kill {
                    let _ = handle.kill();
                }
                entry.finish_teardown();
                bail!("AWAIT task '${var}' interrupted by TIMEOUT");
            }
            Decision::Done(status) => {
                entry.finish_teardown();
                if !status.success() {
                    bail!("AWAIT task '${var}' failed with status {status}");
                }
                return Ok(status);
            }
        }
    }
}

/// Dispatch `AWAIT $var` : block until the named task completes, propagate
/// error if it failed, and forward the task's captured stdout to the parent
/// stdout.
///
/// State machine (`TaskEntry`): the first `AWAIT` transitions the entry
/// `Running -> Awaiting` and owns the bounded poll loop below. A concurrent
/// `CANCEL` (or a `TIMEOUT` deadline) transitions the entry to `Cancelled`;
/// this loop observes that within ~10ms and rendezvouses on teardown
/// completion before reporting cancellation.
pub(crate) fn dispatch_await<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<()> {
    let val = cx
        .state
        .get_var(var)
        .ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
    // A LIST of HANDLEs awaits every member in order, so worker pools
    // collected with PUSH join as a group; an empty LIST is a no-op. The
    // first failing member bails like sequential single AWAITs would.
    // `LET $out: STRING = AWAIT $t` stays single-handle: capture needs one output.
    // Bare AWAIT is join-only: task output already streamed live during
    // the run, so there is nothing to forward.
    if let Some(items) = val.as_list().cloned() {
        for (idx, item) in items.iter().enumerate() {
            // `member` feeds callees whose templates add the `$`
            // themselves (`await_task_entry`); `label` feeds this
            // function's own `'{label}'` messages. Splitting the two
            // keeps every rendering at exactly one `$`.
            let member = format!("{var}[{idx}]");
            let label = format!("${member}");
            let Some(task_id) = item.as_handle() else {
                bail!(
                    "AWAIT '{label}' is not a task handle, got {}",
                    item.type_name()
                );
            };
            let entry = resolve_task_entry_by_id(task_id, &label, cx)?;
            await_task_entry(&entry, &cx.state.cancel_token, &member)?;
        }
        return Ok(());
    }
    let entry = resolve_task_entry(var, cx)?;
    await_task_entry(&entry, &cx.state.cancel_token, var)?;
    Ok(())
}

/// Dispatch `LET $out: TYPE = AWAIT $task` : join like bare `AWAIT` (identical
/// cancellation/timeout/double-await semantics via [`await_task_entry`]),
/// then bind the task's explicit `RETURN` value (coerced to the declared
/// type). A task whose body cannot return yields `INT` 0 on success, like
/// a process exit status; a task that can return but fell off the end
/// without one fails loudly, so a missing fallback branch can never
/// silently bind zero. Failed tasks bail above, so a bound value always
/// means success. Task stdout streams live and is never sniffed.
pub(crate) fn dispatch_await_capture<P: ProcessManager>(
    out_var: &str,
    out_type: String,
    task_var: &str,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let entry = resolve_task_entry(task_var, cx)?;
    await_task_entry(&entry, &cx.state.cancel_token, task_var)?;
    let (return_value, returns_value) = {
        let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
        (guard.return_value.clone(), guard.returns_value)
    };
    if let Some(value) = return_value {
        let tag = cx.state.resolve_tag(&out_type)?;
        cx.state
            .declare_var(out_var.trim_start_matches('$').to_string(), tag, value)?;
        return Ok(());
    }
    if returns_value {
        anyhow::bail!(
            "LET ${out_var} = AWAIT ${task_var} fell off the end without RETURN: the task body can return a value on some path but this run produced none"
        );
    }
    let tag = cx.state.resolve_tag(&out_type)?;
    cx.state.declare_var(
        out_var.trim_start_matches('$').to_string(),
        tag,
        Value::int(0),
    )?;
    Ok(())
}

/// Dispatch `CANCEL $var` : synchronously kill a named background task.
///
/// Blocking and deterministic: this function itself takes the handle from
/// the shared entry and joins the task thread, so return implies the OS
/// process is dead and no residual filesystem/stream mutation can follow.
/// A concurrent `AWAIT` rendezvouses on teardown completion and reports
/// cancellation.
pub(crate) fn dispatch_cancel<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<()> {
    use super::state::TaskPhase;

    let val = cx
        .state
        .get_var(var)
        .ok_or_else(|| anyhow::anyhow!("variable '${var}' is not defined"))?;
    let Some(task_id) = val.as_handle() else {
        bail!("variable '${var}' is not a task handle");
    };

    let entry = {
        let named = cx
            .state
            .named_tasks
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        named.get(&task_id).cloned()
    };
    let Some(entry) = entry else {
        bail!("CANCEL: task '${var}' has already been awaited or does not exist");
    };

    // Transition to Cancelled and take the handle under a short lock.
    let handle = {
        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
        match guard.phase {
            TaskPhase::Cancelled => {
                bail!("CANCEL: task '${var}' was already cancelled");
            }
            TaskPhase::Completed => {
                bail!("CANCEL: task '${var}' has already been awaited or does not exist");
            }
            TaskPhase::Running | TaskPhase::Awaiting => {
                guard.phase = TaskPhase::Cancelled;
                guard.handle.take()
            }
        }
    };

    // Synchronous teardown outside every lock: signal the child token,
    // SIGKILL the active process, join the thread.
    if let Some(mut handle) = handle {
        handle.kill()?;
    }
    entry.finish_teardown();
    Ok(())
}

/// Pipeline dispatch wrapper for `AssignAsync`
pub(crate) fn dispatch_assign_async_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AssignAsync {
        var,
        decl_type,
        body,
    } = step
    else {
        unreachable!()
    };
    dispatch_assign_async(var, decl_type.clone(), body, cx)
}

/// Pipeline dispatch wrapper for `Await`
pub(crate) fn dispatch_await_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Await { var } = step else {
        unreachable!()
    };
    dispatch_await(var, cx)
}

/// Pipeline dispatch wrapper for `AssignCapture`
pub(crate) fn dispatch_assign_capture_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AssignCapture {
        var,
        decl_type,
        cmd,
    } = step
    else {
        unreachable!()
    };
    top_level_flow(assign_capture(
        cx,
        super::steps::allocate_assert_generation(),
        0,
        var,
        decl_type.clone(),
        cmd,
    )?)
}

/// Pipeline dispatch wrapper for `AwaitCapture`
pub(crate) fn dispatch_await_capture_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::AwaitCapture {
        out_var,
        out_type,
        task_var,
    } = step
    else {
        unreachable!()
    };
    dispatch_await_capture(out_var, out_type.clone(), task_var, cx)
}

/// Pipeline dispatch wrapper for `Cancel`
pub(crate) fn dispatch_cancel_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Cancel { var } = step else {
        unreachable!()
    };
    dispatch_cancel(var, cx)
}

/// Pipeline dispatch wrapper for `Timeout`
pub(crate) fn dispatch_timeout_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Timeout { duration, body } = step else {
        unreachable!()
    };
    let duration = super::args::resolve_arg_as_duration(duration, cx)?;
    top_level_flow(timeout(cx, &duration, body)?)
}

/// Pipeline dispatch wrapper for `Isolated`
pub(crate) fn dispatch_isolated_step<P: ProcessManager>(
    step: &StepKind,
    cx: &mut StepCtx<'_, P>,
) -> Result<()> {
    let StepKind::Isolated { body } = step else {
        unreachable!()
    };
    top_level_flow(isolated(cx, body)?)
}

/// Owned deadline watch shared by `TIMEOUT` steps and deadline-bound
/// captures: arming spawns the watchdog, marks the state cancellable,
/// and floors the task-id counter so the scope-end reaper joins only
/// workers this scope spawns; disarming joins the watchdog and
/// restores everything, turning a fired deadline into the standard
/// deadline error even when the guarded operation succeeded.
struct DeadlineGuard {
    done: Arc<std::sync::atomic::AtomicBool>,
    fired: Arc<std::sync::atomic::AtomicBool>,
    watcher: Option<std::thread::JoinHandle<()>>,
    prev_cancellable: bool,
    prev_floor: Option<u64>,
    initial_cancel: bool,
}

/// Arm a deadline watch around the work that follows. `None` is a
/// no-op returning `None`, so call sites with an optional deadline
/// need no branching.
fn arm_deadline<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    duration: Option<std::time::Duration>,
) -> Option<DeadlineGuard> {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Instant;

    let duration = duration?;
    let initial_cancel = cx.state.cancel_token.load(Ordering::SeqCst);
    let deadline = Instant::now() + duration;
    let done = Arc::new(AtomicBool::new(false));
    let fired = Arc::new(AtomicBool::new(false));
    let cancel_token = Arc::clone(&cx.state.cancel_token);
    let cancel_hub = Arc::clone(&cx.state.cancel_hub);
    let active_process = Arc::clone(&cx.state.active_process);

    // Deadline watcher: enforces the timeout while the guarded work
    // runs on this thread. Exits as soon as `done` is set; joined on
    // disarm, so no thread outlives the guard.
    let watcher_done = Arc::clone(&done);
    let watcher_fired = Arc::clone(&fired);
    let watcher = std::thread::spawn(move || {
        loop {
            if watcher_done.load(Ordering::SeqCst) {
                return;
            }
            if Instant::now() >= deadline {
                watcher_fired.store(true, Ordering::SeqCst);
                cancel_token.store(true, Ordering::SeqCst);
                cancel_hub.mark_cancelled();
                if let Ok(mut guard) = active_process.lock()
                    && let Some(proc) = guard.as_mut()
                {
                    let _ = proc.kill();
                }
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    });

    // Deadline enforcement for nested RUNs: a blocking foreground
    // process registers in active_process, where the watcher can
    // reach it. Restored afterwards (nesting-safe: an outer TIMEOUT
    // already sets this, and the restore preserves it).
    //
    // Scope-bounded join: snapshot the task-id counter so the scope-end
    // reaper joins only workers this scope spawns. A worker the scope
    // leaves running gets up to the deadline, then the fail-fast
    // teardown stops it. Pre-existing tasks keep running past the scope
    // instead of holding it open: without the floor, a long-lived
    // server task turns every later TIMEOUT into a wait for its
    // deadline.
    let prev_cancellable = cx.state.cancellable;
    cx.state.cancellable = true;
    let floor = cx.state.next_task_id.load(Ordering::SeqCst);
    let prev_floor = cx.state.reap_floor.replace(floor);
    Some(DeadlineGuard {
        done,
        fired,
        watcher: Some(watcher),
        prev_cancellable,
        prev_floor,
        initial_cancel,
    })
}

/// Disarm a deadline watch, joining the watchdog and restoring state.
/// A fired deadline becomes the standard deadline error, wrapping the
/// guarded result when it erred. `None` passes the result through, so
/// deadline-free call sites share the same code path.
fn disarm_deadline<T, P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    mut guard: Option<DeadlineGuard>,
    duration: Option<std::time::Duration>,
    result: Result<T>,
) -> Result<T> {
    use std::sync::atomic::Ordering;

    let Some(guard) = guard.as_mut() else {
        return result;
    };
    cx.state.cancellable = guard.prev_cancellable;
    cx.state.reap_floor = guard.prev_floor.take();

    guard.done.store(true, Ordering::SeqCst);
    if let Some(watcher) = guard.watcher.take() {
        let _ = watcher.join();
    }

    // Restore pre-existing cancellation state if deadline watcher did not fire
    if !guard.fired.load(Ordering::SeqCst) {
        cx.state
            .cancel_token
            .store(guard.initial_cancel, Ordering::SeqCst);
    }

    let budget = oxdock_parser::command::format_duration(
        &duration.expect("disarm with a guard always carries a duration"),
    );
    match result {
        Ok(value) => {
            if guard.fired.load(Ordering::SeqCst) {
                bail!("TIMEOUT after {} — deadline exceeded", budget);
            }
            Ok(value)
        }
        Err(err) => {
            if guard.fired.load(Ordering::SeqCst) {
                Err(err).with_context(|| format!("TIMEOUT after {} — deadline exceeded", budget))
            } else {
                Err(err)
            }
        }
    }
}

/// Dispatch `TIMEOUT <duration> <body>`: run `body` on the current thread
/// with a deadline. If the deadline elapses first, cancel the state,
/// `kill()` the active foreground process (when one is registered), and
/// return a deadline error wrapping the body result; a body error with
/// time still left returns unwrapped.
///
/// `idx` is the 0-based step index used for error attribution.
pub(crate) fn timeout<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    duration: &std::time::Duration,
    body: &[Step],
) -> Result<Flow> {
    let guard = arm_deadline(cx, Some(*duration));
    let result = super::steps::execute_scoped_steps(
        cx.state,
        cx.process,
        body,
        cx.stdin.clone(),
        cx.expose_stdin,
        cx.out.clone(),
        cx.err.clone(),
        cx.out_pipe.clone(),
        cx.stdin_pipe.clone(),
        true,
    );
    disarm_deadline(cx, guard, Some(*duration), result)
}

/// RAII scope for `ISOLATED` bodies: snapshots the script env, clears it,
/// and restores both on drop across every exit path (`?`, `bail!`, early
/// return). Wraps `&mut StepCtx` (not `&mut ExecState`): holding the state
/// borrow directly would collide with the mutable borrow
/// `execute_scoped_steps` needs (E0499), so the body executes through the
/// `DerefMut` reborrow instead.
struct IsolatedScopeGuard<'a, 'b, P: ProcessManager> {
    cx: &'a mut StepCtx<'b, P>,
}

impl<'a, 'b, P: ProcessManager> IsolatedScopeGuard<'a, 'b, P> {
    fn enter(cx: &'a mut StepCtx<'b, P>) -> Self {
        cx.state.isolated_stack.push(Arc::clone(&cx.state.envs));
        cx.state.envs = Arc::clone(&cx.state.seed);
        Self { cx }
    }
}

impl<'a, 'b, P: ProcessManager> std::ops::Deref for IsolatedScopeGuard<'a, 'b, P> {
    type Target = StepCtx<'b, P>;

    fn deref(&self) -> &Self::Target {
        self.cx
    }
}

impl<'a, 'b, P: ProcessManager> std::ops::DerefMut for IsolatedScopeGuard<'a, 'b, P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.cx
    }
}

impl<P: ProcessManager> Drop for IsolatedScopeGuard<'_, '_, P> {
    fn drop(&mut self) {
        // Tolerant pop: imbalance is unreachable by construction (entry
        // always pushes before body code runs), and a panicking `Drop`
        // during unwind would abort the process. Worst case the live
        // envs stay as the body left them, exactly like a normal scope
        // whose pop failed.
        if let Some(snapshot) = self.cx.state.isolated_stack.pop() {
            self.cx.state.envs = snapshot;
        }
    }
}

/// Execute an `ISOLATED` body with the seeded script environment:
/// the map resets to the session seed, and only names the block
/// re-adds through its leading allowlist reach spawned children on
/// top of that seed. Variables, pipes, and files flow through
/// untouched; scope exit restores the prior environment via the
/// guard, on every path.
pub(crate) fn isolated<P: ProcessManager>(cx: &mut StepCtx<'_, P>, body: &[Step]) -> Result<Flow> {
    let mut guard = IsolatedScopeGuard::enter(cx);
    // Reborrow through the guard once: field borrows off a direct `&mut`
    // place stay disjoint (unlike repeated `DerefMut` autorefs), so the
    // ten borrows below coexist. The guard outlives the call and its
    // `Drop` restores on every exit path, including `Err` returns.
    let scoped: &mut StepCtx<'_, P> = &mut guard;
    let result = super::steps::execute_scoped_steps(
        scoped.state,
        scoped.process,
        body,
        scoped.stdin.clone(),
        scoped.expose_stdin,
        scoped.out.clone(),
        scoped.err.clone(),
        scoped.out_pipe.clone(),
        scoped.stdin_pipe.clone(),
        false,
    );
    drop(guard);
    // Inner steps number from the block, not the script: name the
    // boundary so `step 1: RUN ...` inside ISOLATED never reads as the
    // script's first step.
    result.with_context(|| "inside ISOLATED block".to_string())
}

/// Resolve a block allowlist against the enclosing `ISOLATED` snapshot
/// only: never host env, never host-provided overrides. Absent names stay
/// absent silently (matching top-level `INHERIT_ENV`), so optional tokens
/// stay expressible. Outside any block this is unreachable by
/// construction (the parser only produces the node inside `ISOLATED`,
/// and the static pass rejects strays); the bail is defense in depth.
pub(crate) fn isolated_inherit_env<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    keys: &[String],
) -> Result<()> {
    let Some(snapshot) = cx.state.isolated_stack.last().cloned() else {
        bail!("isolated allowlist outside ISOLATED");
    };
    let envs = Arc::make_mut(&mut cx.state.envs);
    for key in keys {
        let matched = snapshot
            .iter()
            .find(|(k, _)| oxdock_process::names_eq(k, key));
        if let Some((_, value)) = matched {
            // De-duplicate casing variants before inserting, so the map
            // never carries two spellings of one name into dispatch.
            envs.retain(|k, _| !oxdock_process::names_eq(k, key));
            envs.insert(key.clone(), value.clone());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{apply_prompt_answer, format_prompt};

    #[test]
    fn prompt_format_shows_default_in_brackets() {
        assert_eq!(
            format_prompt("Install destination?", Some("/tmp/bin")),
            "Install destination? [/tmp/bin]: "
        );
        assert_eq!(
            format_prompt("Install destination?", None),
            "Install destination?: "
        );
    }

    #[test]
    fn prompt_answer_prefers_input_over_default() {
        assert_eq!(
            apply_prompt_answer("/custom/bin", Some("/tmp/bin")),
            "/custom/bin"
        );
        assert_eq!(apply_prompt_answer("", Some("/tmp/bin")), "/tmp/bin");
        assert_eq!(apply_prompt_answer("", None), "");
    }
}