oxdock-core 0.28.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
use anyhow::{Result, bail};
use oxdock_fs::EntryKind;
use oxdock_parser::{Arg, ArgPart, ArithOp, CompareOp, Expr, LogicalOp, MathOp, TypeTag, Value};
use oxdock_pipe::{SharedInput, SharedOutput, SpillBuffer};
use oxdock_process::{ProcessManager, format_value_for_string};
use std::sync::atomic::{AtomicBool, Ordering};

use super::state::ExecState;
use super::steps::StepCtx;

/// Single mismatch constructor for the coercion path: names the
/// expected tag structurally and the word the value holds. All
/// coercion arms report through here so message drift cannot hide
/// a new admission.
pub(crate) fn type_mismatch(ctx: &str, expected: &TypeTag, value: &Value) -> anyhow::Error {
    anyhow::anyhow!(
        "{ctx}: TypeMismatch: expected {}, got {}",
        oxdock_parser::render_structural(expected),
        value.type_name()
    )
}

/// Strict return-slot check for host functions: the value a host body
/// hands back must satisfy its declared `returns` tag exactly. No
/// coercion applies on this path: a mismatch is an implementation
/// bug, so it fails loudly naming the function instead of reshaping
/// the value. Script bodies carry no declared slot (their type is
/// inferred by unification), so they never reach here. Shared by the
/// expression call path here and the statement call path in
/// `handlers::call_func_value`.
pub(crate) fn check_host_return_value(
    ctx: &str,
    returns: &Option<TypeTag>,
    value: &Value,
) -> Result<()> {
    let Some(slot) = returns else {
        return Ok(());
    };
    oxdock_parser::check_value_at(slot, value, ctx)
}

/// Narrow a `STRING|PATH` word to display text: strings verbatim,
/// paths lossy-rendered. The caller guarantees admission (macro
/// `#[union]` extractor or an explicit check), so anything else is
/// a bug, not a user error.
pub(crate) fn string_or_path_text(value: &Value) -> Result<String> {
    if let Some(s) = value.as_str() {
        return Ok(s.to_string());
    }
    if let Some(p) = value.as_path() {
        return Ok(p.to_string_lossy().to_string());
    }
    Err(type_mismatch(
        "string-or-path position",
        &oxdock_parser::union_tag!(String, Path),
        value,
    ))
}

/// Coerce a runtime [`Value`] word into a declared type name. Single
/// coercion point. Type references are plain names resolved against the
/// run's name directory here (not at parse time, where host descriptors
/// are not visible). Pipe targets validate against the live PipeRegistry
/// via ExecState.
pub(crate) fn coerce_value(value: Value, expected: &TypeTag) -> Result<Value> {
    // `ANY` accepts every word: the boundary already let it through,
    // so coercion is a passthrough, never a second opinion.
    if matches!(expected, TypeTag::Any) {
        return Ok(value);
    }
    // Exact conformance first: passthrough when the value already
    // satisfies the tag, including shaped records and typed lists.
    // A shaped violation returns here with its indexed path: no
    // scalar or string ever coerces into a composite, so the shape
    // error is the honest one (call boundaries already report it
    // through `check_value_at`; declarations match them now).
    if let Err(err) = oxdock_parser::check_value(expected, &value) {
        if matches!(expected, TypeTag::ListOf(_) | TypeTag::Record(_)) {
            return Err(err);
        }
    } else {
        return Ok(value);
    }
    // Unions coerce member-wise, first success in written order: a
    // union admits everything its members admit, so `LET $u:
    // INT|FLOAT = "123"` coerces exactly like `LET $x: INT = "123"`.
    // Static `check_arg` admits the same member pairs, so both layers
    // agree by construction instead of one promising what the other
    // rejects. Total failure falls through to the arms below, which
    // name the set.
    if let TypeTag::Union(_, members) = expected {
        for member in members.iter() {
            if let Ok(coerced) = coerce_value(value.clone(), member) {
                return Ok(coerced);
            }
        }
    }
    // Values of other shapes never cross-coerce; the mismatch below
    // reports both names through the tag.
    if let Some(s) = value.as_str() {
        let name = expected.name();
        return match expected {
            // Strict integer slots: strings never parse here. The
            // explicit `INT()` converter owns string parsing, so a
            // string at an `INT` position fails naming both instead
            // of silently re-parsing at every consumer.
            TypeTag::Bool => match s.trim() {
                "true" => Ok(Value::bool(true)),
                "false" => Ok(Value::bool(false)),
                _ => Err(type_mismatch("coercion", expected, &value)),
            },
            TypeTag::Pipe => {
                // Strict: plain strings never coerce to pipes, so a handle is
                // always created explicitly via `LET $p: PIPE`. Anything else
                // is a TypeMismatch.
                Err(anyhow::anyhow!(
                    "TypeMismatch: expected {name}, got STRING ({s:?}); declare LET $x: PIPE and pass $x"
                ))
            }
            TypeTag::Duration => oxdock_parser::command::parse_duration(s.trim())
                .map(Value::duration)
                .map_err(|_| type_mismatch("coercion", expected, &value)),
            TypeTag::Path => {
                // Narrow exception: materializing the PATH payload. Guard checks
                // still run through oxdock-fs at use time.
                #[allow(clippy::disallowed_types)]
                let path = std::path::PathBuf::from(s.trim());
                Ok(Value::path(path))
            }
            // Every other tag rejects strings here: values that
            // already conform returned through `check_value` above,
            // so this arm only sees genuine mismatches. Each tag is
            // listed so a new word kind fails to compile until its
            // string-coercion rule is explicit. `INT` and `FLOAT`
            // stay in this list deliberately: string parsing belongs
            // to the explicit converters, never to coercion.
            TypeTag::String
            | TypeTag::Int
            | TypeTag::Float
            | TypeTag::List
            | TypeTag::Map
            | TypeTag::Handle
            | TypeTag::Semaphore
            | TypeTag::Permit
            | TypeTag::Any
            | TypeTag::Custom(_)
            | TypeTag::ListOf(_)
            | TypeTag::Record(_)
            | TypeTag::MapOf(_)
            | TypeTag::Union(..) => Err(type_mismatch("coercion", expected, &value)),
        };
    }
    coerce_scalar(&value, expected)
}

/// Scalar cross-coercions between numeric, boolean, duration, path, and
/// pipe-name words. Anything else is a `TypeMismatch`. Admissions are
/// explicit `if`s; the fallthrough rejects closed, so a new tag is
/// refused here until its coercion rule is written.
fn coerce_scalar(value: &Value, expected: &TypeTag) -> Result<Value> {
    if let Some(n) = value.as_i64() {
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(n.to_string()));
        }
        if matches!(expected, TypeTag::Float) {
            return Ok(Value::float(n as f64));
        }
        return Err(mismatch(expected, value));
    }
    if let Some(f) = value.as_f64() {
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(f.to_string()));
        }
        // Strict: floats never narrow to integers here. Whole floats
        // pass through the explicit `INT()` converter instead, so an
        // `INT` slot names the mismatch rather than truncating.
        return Err(mismatch(expected, value));
    }
    if let Some(b) = value.as_bool() {
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(b.to_string()));
        }
        return Err(mismatch(expected, value));
    }
    if let Some(d) = value.as_duration() {
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(oxdock_parser::command::format_duration(&d)));
        }
        return Err(mismatch(expected, value));
    }
    if let Some(p) = value.as_path() {
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(p.to_string_lossy().to_string()));
        }
        return Err(mismatch(expected, value));
    }
    if value.as_pipe_handle().is_some() {
        // Opaque rendering: stringifying a handle was already
        // meaningless with names; `<pipe>` keeps the totality.
        if matches!(expected, TypeTag::String) {
            return Ok(Value::string(format!("{value}")));
        }
        return Err(mismatch(expected, value));
    }
    Err(mismatch(expected, value))
}

fn mismatch(expected: &TypeTag, value: &Value) -> anyhow::Error {
    type_mismatch("coercion", expected, value)
}

/// Resolve an [`Arg`] using an [`ExecState`] directly (no [`StepCtx`] needed).
/// Handles `Arg::String` and all-`Text` `Arg::Parts` : `Arg::Expr` requires a
/// `StepCtx` and must go through `resolve_arg`. Filesystem-free by design
/// (issue #131): assertion-needle pre-registration runs before step dispatch
/// while the snapshot is still pending, so this must never touch the snapshot
/// choke point (`command_ctx` / `resolve_write` would materialize it).
pub(crate) fn resolve_arg_state<P: ProcessManager>(
    arg: &Arg,
    state: &ExecState<P>,
) -> Result<String> {
    match arg {
        Arg::String(s, _) => Ok(expand_string(s, &state.envs, state)?),
        Arg::Expr(e) => bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e),
        Arg::Parts(parts) => {
            let mut out = String::new();
            for part in parts {
                match part {
                    ArgPart::Text(s, _) => {
                        out.push_str(&expand_string(s, &state.envs, state)?);
                    }
                    ArgPart::Expr(e) => {
                        bail!("Arg::Expr cannot be resolved without StepCtx: {:?}", e)
                    }
                }
            }
            Ok(out)
        }
    }
}

/// Resolve an [`Arg`] : handles all variants.
pub(crate) fn resolve_arg<P: ProcessManager>(arg: &Arg, cx: &mut StepCtx<'_, P>) -> Result<String> {
    match arg {
        Arg::String(s, _) => Ok(expand_string(s, &cx.state.envs, cx.state)?),
        Arg::Expr(e) => {
            let val = evaluate_expr(e, cx)?;
            Ok(format_value_for_string(&val))
        }
        Arg::Parts(parts) => {
            let mut out = String::new();
            for part in parts {
                match part {
                    ArgPart::Text(s, _) => {
                        out.push_str(&expand_string(s, &cx.state.envs, cx.state)?);
                    }
                    ArgPart::Expr(e) => {
                        let val = evaluate_expr(e, cx)?;
                        out.push_str(&format_value_for_string(&val));
                    }
                }
            }
            Ok(out)
        }
    }
}

/// Resolve an optional [`Arg`]. Returns `Ok(None)` when `None` is passed.
pub(crate) fn resolve_arg_opt<P: ProcessManager>(
    arg: &Option<Arg>,
    cx: &mut StepCtx<'_, P>,
) -> Result<Option<String>> {
    match arg {
        Some(a) => resolve_arg(a, cx).map(Some),
        None => Ok(None),
    }
}

/// Evaluate an assertion operand to a typed [`Value`]: expressions
/// evaluate (variables, key-paths, calls, pre-typed literals); strings,
/// templates, and parts render to `String`. This is what makes
/// `ASSERT_EQ` strict: no coercion happens here.
pub(crate) fn evaluate_assert_operand<P: ProcessManager>(
    arg: &Arg,
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    match arg {
        Arg::Expr(expr) => evaluate_expr(expr, cx),
        _ => Ok(Value::string(resolve_arg(arg, cx)?)),
    }
}

/// Resolve a list of `(name, Arg)` override pairs.
pub(crate) fn resolve_overrides<P: ProcessManager>(
    overrides: &[(String, Arg)],
    cx: &mut StepCtx<'_, P>,
) -> Result<Vec<(String, String)>> {
    overrides
        .iter()
        .map(|(k, v)| resolve_arg(v, cx).map(|val| (k.clone(), val)))
        .collect()
}

/// Resolve an [`Arg`] to an integer, enforcing the declared `int` type
/// on the interpolated value. Dynamics (`$var`, templates) validate
/// here : lower time only sees their unevaluated form.
pub(crate) fn resolve_arg_as_int<P: ProcessManager>(
    arg: &Arg,
    cx: &mut StepCtx<'_, P>,
) -> Result<i64> {
    let resolved = resolve_arg(arg, cx)?;
    oxdock_parser::command::strip_digit_separators(&resolved)
        .parse::<i64>()
        .map_err(|_| anyhow::anyhow!("expected int, got {resolved:?}"))
}

/// Resolve an [`Arg`] to a duration, enforcing the declared `duration`
/// type on the interpolated value. Same lower/runtime split as ints.
pub(crate) fn resolve_arg_as_duration<P: ProcessManager>(
    arg: &Arg,
    cx: &mut StepCtx<'_, P>,
) -> Result<std::time::Duration> {
    let resolved = resolve_arg(arg, cx)?;
    oxdock_parser::command::parse_duration(&resolved)
}

/// Evaluate an [`Expr`] to a [`Value`].
pub(crate) fn evaluate_expr<P: ProcessManager>(
    expr: &Expr,
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    match expr {
        Expr::Literal(v) => {
            if let Some(s) = v.as_str() {
                // Expand {{ $var }} and {{ env:KEY }} in string literals
                return Ok(Value::string(expand_string(s, &cx.state.envs, cx.state)?));
            }
            Ok(v.clone())
        }
        Expr::Var(name) => cx
            .state
            .get_var(name)
            .ok_or_else(|| anyhow::anyhow!("undefined variable ${name}")),
        Expr::Env(key) => match cx.state.envs.get(key) {
            Some(v) => Ok(Value::string(v.clone())),
            None => anyhow::bail!("undefined environment variable `env:{key}`"),
        },
        Expr::KeyPath { base, keys } => resolve_key_path_value(cx, base, keys),
        Expr::List(items) => {
            let mut result = Vec::new();
            for item in items {
                result.push(evaluate_expr(item, cx)?);
            }
            Ok(Value::list(result))
        }
        Expr::Map(entries) => {
            let mut result = std::collections::BTreeMap::new();
            for (key, val_expr) in entries {
                let val = evaluate_expr(val_expr, cx)?;
                result.insert(key.clone(), val);
            }
            Ok(Value::map(result))
        }
        // Inline block (`LET $a: STRING = { ... }`): run the steps in a
        // fresh scope and yield the boundary value, mirroring a zero-arg
        // function body (see `handlers::block_value`).
        Expr::Block(body) => super::handlers::block_value(cx, body),
        Expr::Call { name, args } => {
            // DSL-defined functions run through the call path so arity,
            // depth budget, and scoping apply uniformly.
            if cx.state.functions.contains_script(name.as_str()) {
                return super::handlers::call_func_value(cx, 0, name, args);
            }
            // Native entries gate before effects too: existence, the depth
            // budget, and the registry arity are all known without
            // evaluating anything. Messages match the wrapper format (no
            // step context exists at this layer); DSL-routed calls above
            // keep their step prefix.
            let Some(meta) = cx.state.native_meta(name.as_str()) else {
                bail!("unknown function {name}");
            };
            if cx.state.call_depth >= super::state::MAX_CALL_DEPTH {
                bail!(
                    "recursion depth limit exceeded in FUNC {}",
                    super::base_name(name)
                );
            }
            if let Some(params) = &meta.params {
                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()
                    );
                }
            }
            let mut vals = Vec::with_capacity(args.len());
            for arg in args {
                vals.push(evaluate_expr(arg, cx)?);
            }
            // Stateful/IO fns first (full behavior where step IO
            // exists), then pure scalar fns. Dual entries answer with
            // their ctx arm here and their template arm only where no
            // context exists; single-arm entries are unaffected either
            // way, since one lookup always misses for them.
            // Each clone ends the registry borrow before invoking user code.
            // Both arms verify the declared return slot: a host body
            // handing back a word outside its tag fails here, at the
            // call boundary, with no coercion to rescue it.
            if let Some(func) = cx.state.clone_native_ctx(name.as_str()) {
                let value = func(cx, vals)?;
                check_host_return_value(
                    &format!("function `{}` returned", super::base_name(name)),
                    &meta.returns,
                    &value,
                )?;
                Ok(value)
            } else if let Some(func) = cx.state.clone_native_pure(name.as_str()) {
                let value = func(vals)?;
                check_host_return_value(
                    &format!("function `{}` returned", super::base_name(name)),
                    &meta.returns,
                    &value,
                )?;
                Ok(value)
            } else {
                bail!("unknown function {name}")
            }
        }
        // Variable inspection carries the binding name unevaluated (see
        // `Expr::Inspect`): no function-name matching happens here.
        Expr::Inspect(var) => evaluate_inspect_var(var, cx),
        // Bare `LET $p: PIPE`: mint a fresh unbound handle tagged with
        // the declaring task. Backends materialize lazily on first
        // binding, so declaration never pre-commits a backend type with
        // zero usage context.
        Expr::FreshPipe => Ok(Value::pipe_fresh_in_task(cx.state.task_id)),
        Expr::Arithmetic { op, left, right } => {
            let left_val = evaluate_expr(left, cx)?;
            let right_val = evaluate_expr(right, cx)?;
            apply_arith(*op, left_val, right_val)
        }
        Expr::CompiledMath(ops) => evaluate_compiled_math(ops, cx),
        Expr::UnsignedIntBoundary(n) => {
            bail!("internal error: unstaged integer boundary {n}")
        }
        Expr::Compare { op, left, right } => {
            let lv = evaluate_expr(left, cx)?;
            let rv = evaluate_expr(right, cx)?;
            apply_compare(*op, &lv, &rv)
        }
        Expr::Logical { op, left, right } => {
            let left_val = evaluate_expr(left, cx)?;
            let left_truthy = is_truthy(&left_val)?;
            match op {
                LogicalOp::Or => {
                    if left_truthy {
                        Ok(Value::bool(true))
                    } else {
                        Ok(Value::bool(is_truthy(&evaluate_expr(right, cx)?)?))
                    }
                }
                LogicalOp::And => {
                    if !left_truthy {
                        Ok(Value::bool(false))
                    } else {
                        Ok(Value::bool(is_truthy(&evaluate_expr(right, cx)?)?))
                    }
                }
            }
        }
        Expr::Not(inner) => Ok(Value::bool(!is_truthy(&evaluate_expr(inner, cx)?)?)),
    }
}

/// Check if a value is truthy. Only `BOOL` words are accepted; all other types produce a TypeError.
pub(crate) fn is_truthy(val: &Value) -> Result<bool> {
    match val.as_bool() {
        Some(b) => Ok(b),
        None => bail!("Type Error: condition must be a Bool, found {:?}", val),
    }
}

/// Evaluate an `INSPECT($var)` node to a MAP snapshot: declared type and
/// value plus live details (pipe backend stats, task phase). Like
/// `LOAD_JSON`/`LOAD_TOML`, this evaluates to a value without running
/// script steps. The parser guarantees the argument is a `$variable`, so
/// the snapshot can name what it describes.
fn evaluate_inspect_var<P: ProcessManager>(var: &str, cx: &mut StepCtx<'_, P>) -> Result<Value> {
    super::handlers::inspect_var_map(cx, var).map(Value::map)
}

/// Value-semantics core of `PATH_TYPE()`: operates on an already-evaluated
/// path value so the registry can dispatch without re-evaluating.
pub(crate) fn path_type_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let path_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("PATH_TYPE requires a path argument"))?;
    let path_str = match path_val.as_str() {
        Some(s) => s.to_string(),
        None => bail!("PATH_TYPE path argument must evaluate to a string"),
    };
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve path '{}': {}", path_str, e))?;
    let kind = match cx.state.fs.entry_kind_no_follow(&target) {
        Ok(EntryKind::Symlink) => "symlink",
        Ok(EntryKind::File) => "file",
        Ok(EntryKind::Dir) => "dir",
        Err(_) => "absent",
    };
    Ok(Value::string(kind.to_string()))
}

/// Value-semantics core of `IS_EXEC()` (#100): true iff the name
/// resolves to an executable file on the current platform. Bare
/// command names search `env:PATH` (plus a `.exe` spelling on
/// Windows); spellings containing a separator check that file
/// directly. The empty string is immediately false. Paths resolve
/// through the workspace like everything else: absolute `PATH`
/// entries need `WORKSPACE SYSTEM` to be visible, and scripts only
/// see a `PATH` they inherit. Only [`WorkspaceFs`](oxdock_fs::WorkspaceFs)
/// trait methods are used; backends without metadata (mocks) simply
/// report false. TOCTOU races are inherent and accepted.
pub(crate) fn is_exec_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let name_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("IS_EXEC requires a name argument"))?;
    let name = match name_val.as_str() {
        Some(s) => s.to_string(),
        None => bail!("IS_EXEC name argument must evaluate to a string"),
    };
    if name.is_empty() {
        return Ok(Value::bool(false));
    }
    Ok(Value::bool(is_exec_name(cx, &name)))
}

/// Resolve one tool spelling: direct files by path, bare names by
/// `PATH` search.
fn is_exec_name<P: ProcessManager>(cx: &StepCtx<'_, P>, name: &str) -> bool {
    let exts = platform_exts(cx);
    if name.contains('/') || name.contains('\\') {
        return exe_candidates(name, &exts)
            .iter()
            .any(|candidate| is_executable_candidate(cx, candidate, &exts));
    }
    let path_var = cx.state.envs.get("PATH").cloned().unwrap_or_default();
    for dir in std::env::split_paths(&path_var) {
        let dir = dir.to_string_lossy();
        let base = dir.trim_end_matches(['/', '\\']);
        // Empty segments traditionally mean the working directory;
        // probing it implicitly would surprise, so skip them.
        if base.is_empty() {
            continue;
        }
        for candidate in exe_candidates(name, &exts) {
            if is_executable_candidate(cx, &format!("{base}/{candidate}"), &exts) {
                return true;
            }
        }
    }
    false
}

/// Split a `PATHEXT` value into dotted extensions (`.EXE`, `.BAT`,
/// ...): `;`-separated, trimmed, empties skipped, missing dots added,
/// duplicates dropped case-insensitively. Only an unset variable falls
/// back to the Windows default; an explicitly empty one probes nothing,
/// matching what the shell itself resolves.
#[cfg(windows)]
pub(crate) fn parse_pathext(raw: Option<&str>) -> Vec<String> {
    const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
    let mut exts = Vec::new();
    for piece in raw.unwrap_or(DEFAULT_PATHEXT).split(';') {
        let stem = piece.trim().trim_start_matches('.');
        if stem.is_empty() {
            continue;
        }
        let dotted = format!(".{stem}");
        if !exts
            .iter()
            .any(|seen: &String| seen.eq_ignore_ascii_case(&dotted))
        {
            exts.push(dotted);
        }
    }
    exts
}

/// Extension list for candidate probing: the script's `PATHEXT` on
/// Windows, empty elsewhere (Unix probes the bare name only). Read
/// from the script environment like `PATH`, never the host's, so the
/// answer matches the world the script runs in.
#[cfg(windows)]
fn platform_exts<P: ProcessManager>(cx: &StepCtx<'_, P>) -> Vec<String> {
    parse_pathext(cx.state.envs.get("PATHEXT").map(String::as_str))
}

/// Extension list for candidate probing: the script's `PATHEXT` on
/// Windows, empty elsewhere (Unix probes the bare name only).
#[cfg(not(windows))]
fn platform_exts<P: ProcessManager>(cx: &StepCtx<'_, P>) -> Vec<String> {
    let _ = cx;
    Vec::new()
}

/// Candidate spellings for one tool name: the bare name everywhere,
/// plus one per executable extension on Windows. A name already
/// carrying an extension probes as-is: appending again (`tool.bat.exe`)
/// would never match what the shell resolves.
fn exe_candidates(name: &str, exts: &[String]) -> Vec<String> {
    #[cfg(windows)]
    {
        let lower = name.to_ascii_lowercase();
        if exts
            .iter()
            .any(|ext| lower.ends_with(&ext.to_ascii_lowercase()))
        {
            vec![name.to_string()]
        } else {
            let mut out = vec![name.to_string()];
            out.extend(exts.iter().map(|ext| format!("{name}{ext}")));
            out
        }
    }
    #[cfg(not(windows))]
    {
        let _ = exts;
        vec![name.to_string()]
    }
}

/// True iff the candidate guards to a runnable file: a real file
/// everywhere, plus an executable bit on Unix or a `PATHEXT` extension
/// on Windows. Unresolvable spellings (missing files, paths outside
/// the selected roots) read false, never error.
fn is_executable_candidate<P: ProcessManager>(
    cx: &StepCtx<'_, P>,
    candidate: &str,
    exts: &[String],
) -> bool {
    let Ok(guard) = cx.state.fs.resolve_read(&cx.state.cwd, candidate) else {
        return false;
    };
    if !matches!(
        cx.state.fs.entry_kind(&guard),
        Ok(oxdock_fs::EntryKind::File)
    ) {
        return false;
    }
    #[cfg(unix)]
    {
        let _ = exts;
        use std::os::unix::fs::PermissionsExt;
        cx.state
            .fs
            .metadata(&guard)
            .map(|meta| meta.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
    }
    #[cfg(windows)]
    {
        let lower = candidate.to_ascii_lowercase();
        exts.iter()
            .any(|ext| lower.ends_with(&ext.to_ascii_lowercase()))
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (candidate, &guard, exts);
        return false;
    }
}
/// Value-semantics core of `PATH_WRITABLE()`: true iff an ordinary file
/// can be created at the path, decided WITHOUT creating anything
/// permanent. The empty string is immediately false (it would otherwise
/// alias the working directory and yield a false positive). Otherwise
/// walks up to the nearest existing ancestor, requires it be a directory,
/// and probes writability by creating and deleting a randomized probe
/// file behind an RAII drop-guard. Only [`WorkspaceFs`](oxdock_fs::WorkspaceFs)
/// trait methods are used, so native runs probe the real path while Miri
/// runs probe the synthetic backend. TOCTOU races are inherent and
/// accepted; `INSTALL` stays fail-closed regardless.
pub(crate) fn path_writable_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let path_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("PATH_WRITABLE requires a path argument"))?;
    let path_str = match path_val.as_str() {
        Some(s) => s.to_string(),
        None => bail!("PATH_WRITABLE path argument must evaluate to a string"),
    };
    if path_str.is_empty() {
        return Ok(Value::bool(false));
    }
    let target = cx
        .state
        .fs
        .resolve_write(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve path '{}': {}", path_str, e))?;
    let mut current = target;
    loop {
        match cx.state.fs.entry_kind_no_follow(&current) {
            Ok(EntryKind::Dir) => {
                return Ok(Value::bool(probe_dir_writable(cx, &current)));
            }
            Ok(EntryKind::File) | Ok(EntryKind::Symlink) => {
                return Ok(Value::bool(false));
            }
            Err(_) => {
                let Some(parent) = current.parent() else {
                    return Ok(Value::bool(false));
                };
                if parent.as_path().as_os_str().is_empty() {
                    let cwd = cx.state.cwd.clone();
                    let anchor =
                        cx.state.fs.resolve_write(&cwd, ".").map_err(|e| {
                            anyhow::anyhow!("failed to resolve working directory: {e}")
                        })?;
                    return Ok(Value::bool(probe_dir_writable(cx, &anchor)));
                }
                current = parent;
            }
        }
    }
}

/// Probe whether a file can be created inside `dir` by creating and
/// deleting `.oxdock_probe_<rand>`. The [`ProbeGuard`] removes the probe
/// on drop, so early returns cannot litter. Any failure to create reads
/// as not-writable, never as an error.
fn probe_dir_writable<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    dir: &oxdock_fs::GuardedPath,
) -> bool {
    use std::sync::atomic::{AtomicU64, Ordering};
    static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0);
    let id = PROBE_COUNTER.fetch_add(1, Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0)
        ^ (std::process::id() as u128)
        ^ ((id as u128) << 64);
    let name = format!(".oxdock_probe_{nanos:x}");
    let Ok(probe) = dir.join(&name) else {
        return false;
    };
    if cx.state.fs.write_file(&probe, b"").is_err() {
        return false;
    }
    let _guard = ProbeGuard {
        fs: cx.state.fs.clone_box(),
        path: probe,
    };
    true
}

/// Best-effort probe cleanup: removes the probe file when the probe
/// scope exits, so retry loops cannot litter orphan files.
struct ProbeGuard {
    fs: Box<dyn oxdock_fs::WorkspaceFs>,
    path: oxdock_fs::GuardedPath,
}

impl Drop for ProbeGuard {
    fn drop(&mut self) {
        let _ = self.fs.remove_file(&self.path);
    }
}

/// Pop one operand off the RPN stack with a structured error instead of a
/// panic on malformed/truncated `CompiledMath` vectors.
fn pop_stack(stack: &mut Vec<Value>) -> Result<Value> {
    stack
        .pop()
        .ok_or_else(|| anyhow::anyhow!("compiled math stack underflow"))
}

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

/// Shared integer/float arithmetic: `Int x Int -> Int` (checked, integer
/// division, div-by-zero and overflow bail); any `Float` operand promotes
/// (`Int as f64`) to `Float`; float div-by-zero bails; non-finite results
/// bail rather than storing; anything else is a Type Error.
fn apply_arith(op: ArithOp, left: Value, right: Value) -> Result<Value> {
    if let (Some(a), Some(b)) = (left.as_i64(), right.as_i64()) {
        let v = match op {
            ArithOp::Add => a.checked_add(b),
            ArithOp::Sub => a.checked_sub(b),
            ArithOp::Mul => a.checked_mul(b),
            ArithOp::Div => a.checked_div(b),
        };
        return v.map(Value::int).ok_or_else(|| {
            anyhow::anyhow!("arithmetic error: integer overflow or division by zero")
        });
    }
    {
        let (Some(a), Some(b)) = (as_f64_value(&left), as_f64_value(&right)) else {
            bail!("Type Error: arithmetic requires Int or Float, found {left:?} and {right:?}");
        };
        if matches!(op, ArithOp::Div) && b == 0.0 {
            bail!("arithmetic error: float division by zero");
        }
        let v = match op {
            ArithOp::Add => a + b,
            ArithOp::Sub => a - b,
            ArithOp::Mul => a * b,
            ArithOp::Div => a / b,
        };
        if v.is_finite() {
            Ok(Value::float(v))
        } else {
            bail!("arithmetic error: non-finite float result")
        }
    }
}

fn apply_neg(val: Value) -> Result<Value> {
    if let Some(n) = val.as_i64() {
        return n
            .checked_neg()
            .map(Value::int)
            .ok_or_else(|| anyhow::anyhow!("arithmetic error: integer overflow"));
    }
    if let Some(f) = val.as_f64() {
        if f.is_finite() {
            return Ok(Value::float(-f));
        }
        bail!("arithmetic error: non-finite float result");
    }
    bail!("Type Error: unary '-' requires Int or Float, found {val:?}")
}

/// Shared comparison: both `Int`/`Float` compare numerically (`1 == 1.0` is
/// true, exact equality, no epsilon). Exactness follows binary fractions:
/// decimals whose reduced denominator is a power of 2 (0.5, 0.25, 0.75)
/// compare cleanly, while denominators containing factor 5 (0.1, 0.2, 0.3)
/// are repeating fractions in binary, so `0.1 + 0.2 == 0.3` is false.
/// The LET reference documents this with examples; otherwise `==`/`!=`
/// keep the stringified behavior and ordering on non-numerics bails.
fn apply_compare(op: CompareOp, left: &Value, right: &Value) -> Result<Value> {
    if let (Some(a), Some(b)) = (as_f64_value(left), as_f64_value(right)) {
        // Both numeric (finite floats; ints always qualify).
        if left.as_i64().is_some() && right.as_i64().is_some() {
            let (a, b) = (left.as_i64().unwrap_or(0), right.as_i64().unwrap_or(0));
            let result = match op {
                CompareOp::Eq => a == b,
                CompareOp::Ne => a != b,
                CompareOp::Lt => a < b,
                CompareOp::Le => a <= b,
                CompareOp::Gt => a > b,
                CompareOp::Ge => a >= b,
            };
            return Ok(Value::bool(result));
        }
        let result = match op {
            CompareOp::Eq => a == b,
            CompareOp::Ne => a != b,
            CompareOp::Lt => a < b,
            CompareOp::Le => a <= b,
            CompareOp::Gt => a > b,
            CompareOp::Ge => a >= b,
        };
        return Ok(Value::bool(result));
    }
    match op {
        CompareOp::Eq | CompareOp::Ne => {
            let ls = format_value_for_string(left);
            let rs = format_value_for_string(right);
            let result = match op {
                CompareOp::Eq => ls == rs,
                CompareOp::Ne => ls != rs,
                _ => bail!("internal error: equality shape"),
            };
            Ok(Value::bool(result))
        }
        CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
            bail!(
                "Type Error: ordering comparison requires Int or Float, found {left:?} and {right:?}"
            );
        }
    }
}

fn trim_ascii(s: &str) -> &str {
    s.trim_matches(|c: char| c.is_ascii_whitespace())
}

/// `INT(x)`: trims ASCII whitespace and parses `i64`. Passes `Int`
/// through; `Float` only when integral and finite; `Bool` as 1/0;
/// anything else bails. The explicit converter owns every admission:
/// callers convert here, never at consumer slots.
pub(crate) fn int_from_value(val: Value) -> Result<Value> {
    if val.as_i64().is_some() {
        return Ok(val);
    }
    if let Some(f) = val.as_f64() {
        if f.is_finite() && f.fract() == 0.0 && f >= i64::MIN as f64 && f <= i64::MAX as f64 {
            return Ok(Value::int(f as i64));
        }
        bail!("INT() requires an integer value, found FLOAT ({f:?})");
    }
    if let Some(b) = val.as_bool() {
        return Ok(Value::int(i64::from(b)));
    }
    if let Some(s) = val.as_str() {
        let trimmed = trim_ascii(s);
        let clean = oxdock_parser::command::strip_digit_separators(trimmed);
        return clean
            .parse::<i64>()
            .map(Value::int)
            .map_err(|_| anyhow::anyhow!("INT() requires an integer string, found {s:?}"));
    }
    bail!("INT() requires an Int, Float, Bool, or String, found {val:?}")
}

/// `FLOAT(x)`: parses `f64` (accepts int strings), bails on non-finite or
/// non-numeric. Passes `Float`/`Int as f64` through.
pub(crate) fn float_from_value(val: Value) -> Result<Value> {
    if let Some(f) = val.as_f64() {
        if f.is_finite() {
            return Ok(Value::float(f));
        }
        bail!("FLOAT() requires a finite value, found FLOAT ({f:?})");
    }
    if let Some(n) = val.as_i64() {
        return Ok(Value::float(n as f64));
    }
    if let Some(s) = val.as_str() {
        let trimmed = trim_ascii(s);
        let parsed: f64 = trimmed
            .parse()
            .map_err(|_| anyhow::anyhow!("FLOAT() requires a numeric string, found {s:?}"))?;
        if parsed.is_finite() {
            return Ok(Value::float(parsed));
        }
        bail!("FLOAT() requires a finite value, found {s:?}");
    }
    bail!("FLOAT() requires an Int, Float, or String, found {val:?}")
}

/// Value-semantics core of `HAS_KEY()`: report whether a map holds a key
/// so scripts can branch on optional fields without tripping the strict
/// missing-key error.
pub(crate) fn has_key_from_value(map: Value, key: &str) -> Result<Value> {
    let entries = map.as_map().ok_or_else(|| {
        anyhow::anyhow!(
            "HAS_KEY expects a MAP as its first argument, got {}",
            map.type_name()
        )
    })?;
    Ok(Value::bool(entries.contains_key(key)))
}

/// Value-semantics core of `MAP_SET()`: insert one key into a map,
/// failing on duplicates so two entries sharing a key fail the run
/// instead of silently shadowing each other.
pub(crate) fn map_set_from_value(map: Value, key: String, value: Value) -> Result<Value> {
    let entries = map.as_map().ok_or_else(|| {
        anyhow::anyhow!(
            "MAP_SET expects a MAP as its first argument, got {}",
            map.type_name()
        )
    })?;
    if entries.contains_key(&key) {
        bail!("MAP_SET duplicate key '{key}'");
    }
    let mut next = entries.clone();
    next.insert(key, value);
    Ok(Value::map(next))
}

/// Value-semantics core of `MERGE_MAPS()`: merge a LIST of MAPs in
/// order. `policy` must be one of the values the DSL extractor
/// enforces (`fail_on_duplicate`, `overwrite`); the core compares
/// against `fail_on_duplicate` only and treats anything else as
/// overwrite, so all production traffic enters through the checked
/// boundary.
pub(crate) fn merge_maps_from_value(maps: Value, policy: String) -> Result<Value> {
    let items = maps.as_list().ok_or_else(|| {
        anyhow::anyhow!(
            "MERGE_MAPS expects a LIST of MAPs, got {}",
            maps.type_name()
        )
    })?;
    let mut merged = std::collections::BTreeMap::new();
    for (index, item) in items.iter().enumerate() {
        let entries = item.as_map().ok_or_else(|| {
            anyhow::anyhow!(
                "MERGE_MAPS element {index} is {}, not MAP",
                item.type_name()
            )
        })?;
        for (key, value) in entries {
            if merged.contains_key(key) && policy == "fail_on_duplicate" {
                bail!(
                    "duplicate values key '{key}'; later files must not repeat it under fail_on_duplicate"
                );
            }
            merged.insert(key.clone(), value.clone());
        }
    }
    Ok(Value::map(merged))
}

/// Value-semantics core of `TYPE_OF()`: name the word a value holds.
///
/// Returns the registered descriptor name, the same string arity and
/// coercion errors print, so scripts branch on config shapes with the
/// vocabulary the errors already teach.
pub(crate) fn type_of_from_value(value: Value) -> Result<Value> {
    Ok(Value::string(value.type_name().to_string()))
}

/// Value-semantics core of `RAND()`: draw a FLOAT uniformly from
/// `[0, 1)`. Without a seed the draw comes from the thread RNG;
/// with one it is the first draw of a `StdRng` stream, so the same
/// seed draws the same value on every run. Impure by design either
/// way: unseeded calls differ, so this never rides the pure
/// placeholder or RPN paths.
pub(crate) fn rand_float_from_value(seed: Option<i64>) -> Result<Value> {
    use rand::{RngExt, SeedableRng};
    let draw = match seed {
        Some(n) => rand::rngs::StdRng::seed_from_u64(n as u64).random_range(0.0..1.0),
        None => rand::random::<f64>(),
    };
    Ok(Value::float(draw))
}

/// Value-semantics core of `BASE64_ENCODE()`: standard-alphabet
/// base64 with padding. Rejects non-STRING input naming the type
/// instead of rendering a silent empty.
pub(crate) fn base64_encode_from_value(text: Value) -> Result<Value> {
    use base64::Engine as _;
    let input = text.as_str().ok_or_else(|| {
        anyhow::anyhow!("BASE64_ENCODE expects a STRING, got {}", text.type_name())
    })?;
    Ok(Value::string(
        base64::engine::general_purpose::STANDARD.encode(input.as_bytes()),
    ))
}

/// Value-semantics core of `BASE64_DECODE()`: standard-alphabet
/// base64 back to UTF-8 text. Invalid alphabet characters and
/// non-UTF-8 payloads fail naming the input instead of rendering a
/// silent empty.
pub(crate) fn base64_decode_from_value(text: Value) -> Result<Value> {
    use base64::Engine as _;
    let input = text.as_str().ok_or_else(|| {
        anyhow::anyhow!("BASE64_DECODE expects a STRING, got {}", text.type_name())
    })?;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(input)
        .map_err(|e| anyhow::anyhow!("BASE64_DECODE cannot decode {input:?}: {e}"))?;
    let decoded = String::from_utf8(bytes)
        .map_err(|_| anyhow::anyhow!("BASE64_DECODE decoded bytes are not UTF-8"))?;
    Ok(Value::string(decoded))
}

/// Value-semantics core of `TO_JSON()`: encode a script value as JSON
/// with one trailing newline. Only template-safe shapes survive;
/// anything else fails here instead of rendering as a silent empty.
pub(crate) fn to_json_from_value(value: Value) -> Result<Value> {
    let json = value_to_json(&value)?;
    let mut out = serde_json::to_string(&json).map_err(|e| anyhow::anyhow!("encode JSON: {e}"))?;
    out.push('\n');
    Ok(Value::string(out))
}

/// Script values to JSON. Maps stay sorted (the word holds a BTreeMap);
/// only template-safe shapes survive: STRING, INT, FLOAT, BOOL, LIST,
/// and MAP. Anything else fails naming the type instead of rendering
/// a silent empty. Shared by `TO_JSON` and any host bridging values
/// across a JSON boundary (sentinel payloads, wire frames).
pub fn value_to_json(value: &Value) -> Result<serde_json::Value> {
    if let Some(map) = value.as_map() {
        return map
            .iter()
            .map(|(key, item)| value_to_json(item).map(|v| (key.clone(), v)))
            .collect::<Result<serde_json::Map<_, _>>>()
            .map(serde_json::Value::Object);
    }
    if let Some(list) = value.as_list() {
        return list
            .iter()
            .map(value_to_json)
            .collect::<Result<Vec<_>>>()
            .map(serde_json::Value::Array);
    }
    if let Some(s) = value.as_str() {
        return Ok(serde_json::Value::String(s.to_string()));
    }
    if let Some(i) = value.as_i64() {
        return Ok(serde_json::Value::Number(serde_json::Number::from(i)));
    }
    if let Some(f) = value.as_f64() {
        let number = serde_json::Number::from_f64(f)
            .ok_or_else(|| anyhow::anyhow!("TO_JSON cannot encode non-finite float {f}"))?;
        return Ok(serde_json::Value::Number(number));
    }
    if let Some(b) = value.as_bool() {
        return Ok(serde_json::Value::Bool(b));
    }
    bail!(
        "TO_JSON cannot encode {} values; use STRING, INT, FLOAT, BOOL, LIST, or MAP",
        value.type_name()
    )
}

/// Resolve `$base.key...` against the scope chain (shared by the AST
/// `KeyPath` arm and the RPN `LoadKeyPath` op).
fn resolve_key_path_value<P: ProcessManager>(
    cx: &StepCtx<'_, P>,
    base: &str,
    keys: &[String],
) -> Result<Value> {
    let mut current = cx
        .state
        .get_var(base)
        .ok_or_else(|| anyhow::anyhow!("undefined variable ${base}"))?;
    for key in keys {
        if let Some(map) = current.as_map() {
            current = map
                .get(key)
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("Key '{}' not found in map", key))?;
        } else if let Some(list) = current.as_list() {
            let idx: usize = key
                .parse()
                .map_err(|_| anyhow::anyhow!("Invalid array index '{}'", key))?;
            current = list
                .get(idx)
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("Index {} out of bounds", idx))?;
        } else {
            bail!("Cannot traverse into scalar value at key '{}'", key);
        }
    }
    Ok(current)
}

/// Execute flat `CompiledMath` RPN with a local stack loop. All pops are
/// checked (`pop_stack`); `Call` args are popped then reversed to restore
/// left-to-right order before dispatch.
fn evaluate_compiled_math<P: ProcessManager>(
    ops: &[MathOp],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let mut stack: Vec<Value> = Vec::with_capacity(8);
    for op in ops {
        match op {
            MathOp::PushConst(v) => {
                if let Some(s) = v.as_str() {
                    stack.push(Value::string(expand_string(s, &cx.state.envs, cx.state)?));
                } else {
                    stack.push(v.clone());
                }
            }
            MathOp::LoadVar(name) => {
                let val = cx
                    .state
                    .get_var(name)
                    .ok_or_else(|| anyhow::anyhow!("undefined variable ${name}"))?;
                stack.push(val);
            }
            MathOp::LoadEnv(key) => match cx.state.envs.get(key) {
                Some(v) => stack.push(Value::string(v.clone())),
                None => anyhow::bail!("undefined environment variable `env:{key}`"),
            },
            MathOp::LoadKeyPath { base, keys } => {
                stack.push(resolve_key_path_value(cx, base, keys)?);
            }
            MathOp::Call { name, arity } => {
                let mut args = Vec::with_capacity(*arity);
                for _ in 0..*arity {
                    args.push(pop_stack(&mut stack)?);
                }
                args.reverse();
                // RPN math path: stateful fns opted into `rpn` first
                // (full behavior where step IO exists), then pure
                // scalar fns; anything else (PATH_TYPE, FUNCTIONS,
                // DESCRIBE, TYPES, TYPE_DESCRIBE) is AST-only by
                // design. Dual entries answer with their ctx arm here,
                // like every other context carrying cx.
                let val = if cx
                    .state
                    .native_meta(name.as_str())
                    .is_some_and(|meta| meta.rpn)
                    && let Some(func) = cx.state.clone_native_ctx(name.as_str())
                {
                    func(cx, args)?
                } else if let Some(func) = cx.state.clone_native_pure(name.as_str()) {
                    func(args)?
                } else {
                    bail!("unknown function {name}")
                };
                stack.push(val);
            }
            MathOp::Inspect(name) => {
                stack.push(Value::map(super::handlers::inspect_var_map(cx, name)?));
            }
            MathOp::Neg => {
                let val = pop_stack(&mut stack)?;
                stack.push(apply_neg(val)?);
            }
            MathOp::Add => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_arith(ArithOp::Add, left, right)?);
            }
            MathOp::Sub => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_arith(ArithOp::Sub, left, right)?);
            }
            MathOp::Mul => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_arith(ArithOp::Mul, left, right)?);
            }
            MathOp::Div => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_arith(ArithOp::Div, left, right)?);
            }
            MathOp::Lt => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Lt, &left, &right)?);
            }
            MathOp::Le => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Le, &left, &right)?);
            }
            MathOp::Gt => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Gt, &left, &right)?);
            }
            MathOp::Ge => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Ge, &left, &right)?);
            }
            MathOp::Eq => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Eq, &left, &right)?);
            }
            MathOp::Ne => {
                let right = pop_stack(&mut stack)?;
                let left = pop_stack(&mut stack)?;
                stack.push(apply_compare(CompareOp::Ne, &left, &right)?);
            }
        }
    }
    if stack.len() != 1 {
        bail!("compiled math left {} values on the stack", stack.len());
    }
    pop_stack(&mut stack)
}

/// Value-semantics core of `GLOB()`: operates on an already-evaluated
/// pattern value so both the AST and RPN paths share one implementation.
pub(crate) fn glob_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let pattern_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("GLOB requires a pattern argument"))?;
    let Some(raw_pattern) = pattern_val.as_str() else {
        bail!("GLOB pattern argument must evaluate to a string");
    };
    let raw_pattern = raw_pattern.to_string();

    // Up-front sandbox gate (mirrors `GuardedPath::glob_paths`): patterns are
    // sandbox-root-relative, so any `..` component escapes. Return empty
    // without traversing : the same empty-on-no-match GLOB semantics.
    if raw_pattern
        .replace('\\', "/")
        .split('/')
        .any(|seg| seg == "..")
    {
        return Ok(Value::list(Vec::new()));
    }

    // GLOB lists the current root: ride the snapshot choke point so a
    // pending snapshot materializes here (a snapshot read), while local
    // roots resolve with zero I/O. The listing below then runs on concrete
    // paths in both cases.
    let _ = cx.state.fs.resolve_read(&cx.state.cwd, ".")?;
    let root = cx.state.fs.root().clone();
    let root_path = root.as_path().to_path_buf();
    let mut entries: Vec<Value> = root
        .glob_paths(&raw_pattern)?
        .into_iter()
        .filter_map(|p| {
            p.strip_prefix(&root_path)
                .ok()
                .map(|rel| Value::string(rel.to_string_lossy().replace('\\', "/")))
        })
        .collect();

    entries.sort_by(|a, b| format!("{}", a).cmp(&format!("{}", b)));
    Ok(Value::list(entries))
}

/// Value-semantics core of `LOAD_TOML()`.
pub(crate) fn load_toml_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let path_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("LOAD_TOML requires a path argument"))?;
    let Some(path_str) = path_val.as_str() else {
        bail!("LOAD_TOML path argument must evaluate to a string");
    };
    let path_str = path_str.to_string();
    let target = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve TOML path '{}': {}", path_str, e))?;
    let content = cx
        .state
        .fs
        .read_file(&target)
        .map_err(|e| anyhow::anyhow!("failed to read TOML file '{}': {}", path_str, e))?;
    let content_str = std::str::from_utf8(&content)
        .map_err(|e| anyhow::anyhow!("invalid UTF-8 in TOML file '{}': {}", path_str, e))?;
    load_toml_value(content_str)
}

/// Value-semantics core of `LOAD_JSON()`.
pub(crate) fn load_json_from_value<P: ProcessManager>(
    args: &[Value],
    cx: &mut StepCtx<'_, P>,
) -> Result<Value> {
    let path_val = args
        .first()
        .ok_or_else(|| anyhow::anyhow!("LOAD_JSON requires a path argument"))?;
    let Some(path_str) = path_val.as_str() else {
        bail!("LOAD_JSON path argument must evaluate to a string");
    };
    let path_str = path_str.to_string();
    let target = cx
        .state
        .fs
        .resolve_read(&cx.state.cwd, &path_str)
        .map_err(|e| anyhow::anyhow!("failed to resolve JSON path '{}': {}", path_str, e))?;
    let content = cx
        .state
        .fs
        .read_file(&target)
        .map_err(|e| anyhow::anyhow!("failed to read JSON file '{}': {}", path_str, e))?;
    let content_str = std::str::from_utf8(&content)
        .map_err(|e| anyhow::anyhow!("invalid UTF-8 in JSON file '{}': {}", path_str, e))?;
    load_json_value(content_str)
}

/// Parse TOML content into a DSL `Value`.
pub fn load_toml_value(content: &str) -> Result<Value> {
    let json_val: serde_json::Value =
        toml::from_str(content).map_err(|e| anyhow::anyhow!("TOML parse error: {}", e))?;
    Ok(json_to_value(json_val))
}

/// Value-semantics core of `PARSE_TOML()`: parse TOML text already held
/// in memory, using the same conversion as file loading.
pub(crate) fn parse_toml_from_value(value: Value) -> Result<Value> {
    let Some(text) = value.as_str() else {
        bail!("PARSE_TOML expects a STRING, got {}", value.type_name());
    };
    load_toml_value(text)
}

/// Parse JSON content into a DSL `Value`.
pub fn load_json_value(content: &str) -> Result<Value> {
    let json_val: serde_json::Value =
        serde_json::from_str(content).map_err(|e| anyhow::anyhow!("JSON parse error: {}", e))?;
    Ok(json_to_value(json_val))
}

/// Value-semantics core of `PARSE_JSON()`: parse JSON text already held
/// in memory, using the same conversion as file loading.
pub(crate) fn parse_json_from_value(value: Value) -> Result<Value> {
    let Some(text) = value.as_str() else {
        bail!("PARSE_JSON expects a STRING, got {}", value.type_name());
    };
    load_json_value(text)
}

/// Convert a `serde_json::Value` to a DSL `Value`. The strict inverse
/// of [`value_to_json`] over the shapes it emits: numbers that fit
/// `i64` bind INT, the rest bind FLOAT. Lenient leftovers from foreign
/// JSON degrade gracefully (unrepresentable numbers and null bind
/// STRING), matching `PARSE_JSON` file loading. Shared by `PARSE_JSON`
/// and any host decoding values back across a JSON boundary.
pub fn json_to_value(v: serde_json::Value) -> Value {
    match v {
        serde_json::Value::String(s) => Value::string(s),
        serde_json::Value::Bool(b) => Value::bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::int(i)
            } else if let Some(f) = n.as_f64() {
                Value::float(f)
            } else {
                Value::string(n.to_string())
            }
        }
        serde_json::Value::Array(arr) => Value::list(arr.into_iter().map(json_to_value).collect()),
        serde_json::Value::Object(map) => Value::map(
            map.into_iter()
                .map(|(k, v)| (k, json_to_value(v)))
                .collect(),
        ),
        serde_json::Value::Null => Value::string(String::new()),
    }
}

/// Single-pass string expansion: handles escapes and `{{ }}` template tags.
///
/// `{{ $var }}` : interpolates script variable (supports key-paths: `{{ $d.name.0 }}`).
/// `{{ env:KEY }}` : interpolates environment variable.
/// Bare `$` is literal text : `{{ }}` is the ONLY interpolation trigger.
///
/// Escape rules:
/// - `\\` → literal `\`
/// - `\{{` → literal `{{` (skip template expansion)
/// - `\n`, `\t`, `\r`, `\"` → control characters
/// - Unrecognized `\X` → literal `\X`
pub(crate) fn expand_string<P: ProcessManager>(
    input: &str,
    env: &std::collections::HashMap<String, String>,
    state: &ExecState<P>,
) -> Result<String> {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' => match chars.peek() {
                Some(&'\\') => {
                    output.push('\\');
                    chars.next();
                }
                Some(&'{') => {
                    // Check for \{{ (literal {{)
                    let mut lookahead = chars.clone();
                    lookahead.next(); // skip first {
                    if lookahead.next() == Some('{') {
                        output.push_str("{{");
                        chars.next(); // skip first {
                        chars.next(); // skip second {
                    } else {
                        output.push('\\');
                    }
                }
                Some(&'n') => {
                    output.push('\n');
                    chars.next();
                }
                Some(&'t') => {
                    output.push('\t');
                    chars.next();
                }
                Some(&'r') => {
                    output.push('\r');
                    chars.next();
                }
                Some(&'"') => {
                    output.push('"');
                    chars.next();
                }
                _ => {
                    output.push('\\');
                }
            },
            '{' if chars.peek() == Some(&'{') => {
                chars.next(); // consume second {
                let mut template_key = String::new();
                let mut found_close = false;
                while let Some(ch) = chars.next() {
                    if ch == '}' && chars.peek() == Some(&'}') {
                        chars.next(); // consume second }
                        found_close = true;
                        break;
                    }
                    template_key.push(ch);
                }
                if found_close {
                    let key = template_key.trim();
                    if let Some(var_expr) = key.strip_prefix('$') {
                        // {{ $var }} or {{ $var.path.0 }} : look up in scope chain.
                        // Parse key-path from the extracted string, NOT from chars.
                        // Trim whitespace from segments to tolerate spaces around dots.
                        // Bare $var never reads the environment; use {{ env:KEY }}.
                        let mut parts = var_expr.split('.');
                        if let Some(base_var) = parts.next() {
                            let base_trim = base_var.trim();
                            let mut current = state.get_var(base_trim);
                            for part in parts {
                                let part_trim = part.trim();
                                current = match current {
                                    Some(v) => {
                                        if let Some(map) = v.as_map() {
                                            map.get(part_trim).cloned()
                                        } else if let Some(list) = v.as_list() {
                                            part_trim
                                                .parse::<usize>()
                                                .ok()
                                                .and_then(|idx| list.get(idx).cloned())
                                        } else {
                                            None
                                        }
                                    }
                                    None => None,
                                };
                                if current.is_none() {
                                    break;
                                }
                            }
                            if let Some(v) = current {
                                output.push_str(&format_value_for_string(&v));
                            }
                            // Missing → emit empty
                        }
                    } else {
                        // {{ env:KEY }} : look up in env (script + process)
                        // {{ script_env:KEY }} : explicit script env
                        // {{ bare_key }} : DSL variable only, NOT env
                        if let Some(env_key) = key
                            .strip_prefix("env:")
                            .or_else(|| key.strip_prefix("script_env:"))
                        {
                            if let Some(val) = env.get(env_key) {
                                output.push_str(val);
                            }
                            // Missing → emit empty
                        } else if let Some(val) = state.get_var(key) {
                            output.push_str(&format_value_for_string(&val));
                        } else if let Some((module, func, args_src)) =
                            oxdock_process::parse_placeholder_call(key)
                        {
                            // `{{ MODULE::FUNC(args) }}` through the shared
                            // pure table: the same registry EXPAND
                            // templates resolve, so ordinary strings and
                            // file templates agree. Unknown functions and
                            // bad args fail here instead of rendering
                            // empty; keys that are not call shaped keep
                            // the empty below (no variable can spell
                            // `::` plus parens).
                            let table = state.pure_function_table();
                            let callee = table
                                .get(module.as_str())
                                .and_then(|entries| entries.get(func.as_str()))
                                .ok_or_else(|| {
                                    let mut known: Vec<String> = table
                                        .iter()
                                        .flat_map(|(m, entries)| {
                                            entries.keys().map(move |f| format!("{m}::{f}"))
                                        })
                                        .collect();
                                    known.sort();
                                    anyhow::anyhow!(
                                        "unknown placeholder function '{module}::{func}'; known functions: {}",
                                        known.join(", ")
                                    )
                                })?;
                            let vars = state.all_vars();
                            let mut args = Vec::with_capacity(args_src.len());
                            for src in args_src {
                                args.push(oxdock_process::resolve_placeholder_arg(&src, &vars)?);
                            }
                            let result = callee(args)?;
                            output.push_str(&format_value_for_string(&result));
                        }
                        // Bare key not in DSL vars → emit empty
                    }
                } else {
                    // Unclosed template : preserve verbatim
                    output.push_str("{{");
                    output.push_str(&template_key);
                }
            }
            _ => {
                output.push(c);
            }
        }
    }
    Ok(output)
}

/// Expand bare `$var` references in a string using DSL scope.
/// Used by RUN commands to expand DSL variables before passing to shell.
/// Undefined variables are left as-is (shell will handle them).
/// Two escape hatches pass text through to the shell untouched:
/// `\$` emits a literal `$` (backslash consumed, no expansion), and `$`
/// inside a `{{ ... }}` span is never expanded (such spans are literal by
/// construction : real templates were already interpolated upstream, and
/// `\{{` escapes arrive here with their braces intact).
/// Note: `\\$var` (literal backslash plus interpolation) is indistinguishable
/// from `\$var` at this stage (`expand_string` already collapsed `\\`), so it
/// also yields a literal `$var`; prefer `{{ $var }}`-adjacent forms when a
/// literal backslash must precede an interpolated value.
pub(crate) fn expand_dsl_vars<P: ProcessManager>(input: &str, state: &ExecState<P>) -> String {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\' && chars.peek() == Some(&'$') {
            output.push('$');
            chars.next();
            continue;
        }
        if c == '{' && chars.peek() == Some(&'{') {
            output.push('{');
            output.push(chars.next().unwrap_or('{'));
            while let Some(ch) = chars.next() {
                output.push(ch);
                if ch == '}' && chars.peek() == Some(&'}') {
                    output.push(chars.next().unwrap_or('}'));
                    break;
                }
            }
            continue;
        }
        if c == '$' {
            let mut var_name = String::new();
            while let Some(&ch) = chars.peek() {
                if ch.is_ascii_alphanumeric() || ch == '_' {
                    var_name.push(ch);
                    chars.next();
                } else {
                    break;
                }
            }
            if var_name.is_empty() {
                output.push('$');
                continue;
            }
            if let Some(val) = state.get_var(&var_name) {
                output.push_str(&format_value_for_string(&val));
            } else {
                output.push('$');
                output.push_str(&var_name);
            }
        } else {
            output.push(c);
        }
    }
    output
}

/// Compile size limit for `TEXT_*` regex patterns. Bounds automata
/// construction so a hostile pattern fails closed at compile time.
pub(crate) const TEXT_REGEX_SIZE_LIMIT: usize = 1_000_000;

/// Bound on cached compiled patterns. Loops reusing a few patterns (a
/// per-line `TEXT_MATCH` over many lines) compile once; adversarial
/// pattern churn clears instead of growing without bound. Keyed by the
/// pattern text alone: compilation is a pure function of it.
const TEXT_PATTERN_CACHE_MAX: usize = 64;

static TEXT_PATTERN_CACHE: std::sync::OnceLock<
    std::sync::Mutex<std::collections::HashMap<String, regex::Regex>>,
> = std::sync::OnceLock::new();

fn text_pattern_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, regex::Regex>>
{
    TEXT_PATTERN_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

/// Compile a `TEXT_*` regex pattern, failing closed with position
/// info on bad patterns. The `regex` crate is automata backed with
/// linear-time matching and no backtracking. Compiled successes cache
/// by pattern text so repeated calls skip reconstruction; a poisoned
/// cache degrades to recompiling instead of failing.
pub(crate) fn text_compile_pattern(func: &str, pattern: &str) -> Result<regex::Regex> {
    if let Some(hit) = text_pattern_cache()
        .lock()
        .map(|guard| guard.get(pattern).cloned())
        .unwrap_or(None)
    {
        return Ok(hit);
    }
    let re = regex::RegexBuilder::new(pattern)
        .size_limit(TEXT_REGEX_SIZE_LIMIT)
        .build()
        .map_err(|e| anyhow::anyhow!("{func} invalid pattern {pattern:?}: {e}"))?;
    if let Ok(mut guard) = text_pattern_cache().lock() {
        if guard.len() >= TEXT_PATTERN_CACHE_MAX {
            guard.clear();
        }
        guard.insert(pattern.to_string(), re.clone());
    }
    Ok(re)
}

/// Trim Unicode whitespace from both ends.
pub(crate) fn text_trim_str(s: &str) -> String {
    s.trim().to_string()
}

/// Strip one leading `prefix`, returning the input unchanged when absent.
pub(crate) fn text_trim_prefix_str(s: &str, prefix: &str) -> String {
    s.strip_prefix(prefix).unwrap_or(s).to_string()
}

/// Strip one trailing `suffix`, returning the input unchanged when absent.
pub(crate) fn text_trim_suffix_str(s: &str, suffix: &str) -> String {
    s.strip_suffix(suffix).unwrap_or(s).to_string()
}

/// Split on a literal delimiter. An empty delimiter splits into chars.
pub(crate) fn text_split_str(s: &str, delimiter: &str) -> Vec<String> {
    if delimiter.is_empty() {
        return s.chars().map(|c| c.to_string()).collect();
    }
    s.split(delimiter).map(str::to_string).collect()
}

/// Split into whitespace-separated fields, ignoring empties.
pub(crate) fn text_fields_str(s: &str) -> Vec<String> {
    s.split_whitespace().map(str::to_string).collect()
}

/// Split into lines with universal newline handling: normalize through
/// the line-ending crate first so LF, CRLF, CR, and mixed endings all
/// split, then delegate the split itself to `LineEnding::split` rather
/// than hand-rolling the scan. Bare `LineEnding::split` alone only
/// splits the predominant ending, leaving mixed breaks joined.
pub(crate) fn text_lines_str(s: &str) -> Vec<String> {
    line_ending::LineEnding::split(&line_ending::LineEnding::normalize(s))
}

/// Literal replacement, failing closed on an empty search string:
/// `str::replace` with an empty needle injects between every char.
pub(crate) fn text_replace_literal_str(
    s: &str,
    from: &str,
    to: &str,
    func: &str,
) -> Result<String> {
    if from.is_empty() {
        bail!("{func} needs a non-empty search string");
    }
    Ok(s.replace(from, to))
}

/// Regex replacement with `$1` and `$name` capture expansion over every
/// match. Bad patterns fail closed through the shared compiler.
pub(crate) fn text_replace_regex_str(
    s: &str,
    pattern: &str,
    replacement: &str,
    func: &str,
) -> Result<String> {
    let re = text_compile_pattern(func, pattern)?;
    Ok(re.replace_all(s, replacement).into_owned())
}

/// Count non-overlapping literal occurrences, failing closed on an
/// empty needle: `str` matching with an empty needle binds every
/// character boundary, which is never the caller's intent.
pub(crate) fn text_count_str(s: &str, needle: &str, func: &str) -> Result<i64> {
    if needle.is_empty() {
        bail!("{func} needs a non-empty needle");
    }
    Ok(s.match_indices(needle).count() as i64)
}

/// Lines matching a pattern, splitting with universal newline
/// handling like `TEXT_LINES`: the `grep` shape (matching lines out, a
/// miss binds an empty list, never an error). `invert` flips the
/// filter to the `grep -v` shape: every non-matching line comes back
/// in order. Case follows the pattern: an inline `(?i)` flag makes
/// uppercase and lowercase letters match each other.
pub(crate) fn text_grep_str(
    s: &str,
    pattern: &str,
    invert: bool,
    func: &str,
) -> Result<Vec<String>> {
    let re = text_compile_pattern(func, pattern)?;
    Ok(text_lines_str(s)
        .into_iter()
        .filter(|line| re.is_match(line) != invert)
        .collect())
}

/// Count lines matching a pattern: the `grep -c` shape over
/// [`text_grep_str`], so one line counts once no matter how many times
/// it hits.
pub(crate) fn text_count_matches_str(s: &str, pattern: &str, func: &str) -> Result<i64> {
    Ok(text_grep_str(s, pattern, false, func)?.len() as i64)
}

/// Read the `invert` flag from a `TEXT_GREP` options MAP: missing
/// means keep matching lines, `true` flips to the `grep -v` shape.
/// `check_options` verified the shape above; the read below narrows
/// infallibly after.
pub(crate) fn text_invert_flag(options: &std::collections::BTreeMap<String, Value>) -> bool {
    options
        .get("invert")
        .map(|value| value.as_bool().expect("check_options verified BOOL"))
        .unwrap_or(false)
}

/// Slice universal lines 1-based inclusive, clamping past the end
/// like `sed -n 'A,Bp'`: a start past the last line binds an empty
/// list, and an end past it stops at the last line. `from < 1` or
/// `from > to` fails closed, since no line reading satisfies it.
pub(crate) fn text_lines_range_str(s: &str, from: i64, to: i64, func: &str) -> Result<Vec<String>> {
    if from < 1 {
        bail!("{func} needs a 1-based start line, got {from}");
    }
    if from > to {
        bail!("{func} needs start <= end, got {from}..={to}");
    }
    let lines = text_lines_str(s);
    let start = (from - 1) as usize;
    if start >= lines.len() {
        return Ok(Vec::new());
    }
    let end = (to as usize).min(lines.len());
    Ok(lines[start..end].to_vec())
}

/// Capture groups for the first match: index 0 is the full match,
/// following indexes are groups in order. Non-participating groups
/// bind empty so indexes stay stable. No match binds an empty list.
pub(crate) fn text_extract_str(s: &str, pattern: &str, func: &str) -> Result<Vec<String>> {
    let re = text_compile_pattern(func, pattern)?;
    let Some(caps) = re.captures(s) else {
        return Ok(Vec::new());
    };
    let mut out = Vec::with_capacity(caps.len());
    for i in 0..caps.len() {
        out.push(
            caps.get(i)
                .map(|m| m.as_str().to_string())
                .unwrap_or_default(),
        );
    }
    Ok(out)
}

/// One streaming text transform over a pipe. String inputs apply
/// eagerly through `apply_str` with identical semantics; pipe inputs
/// stream chunk by chunk on a pump thread with O(chunk) memory plus
/// op-bounded windows, spilling through `SpillBuffer` where a
/// hold-back can grow (trim's trailing whitespace). Backpressure rides
/// the pipe substrate: a stalled reader stalls the pump, and output
/// past the spill backlog cap fails its write and ends the stream.
pub(crate) enum TextPump {
    Trim,
    TrimPrefix(String),
    TrimSuffix(String),
    ToUpper,
    ToLower,
    ReplaceLiteral { from: String, to: String },
}

impl TextPump {
    /// Eager string application with the exact semantics the pump
    /// produces chunk by chunk, so string and pipe inputs agree.
    /// Shared by the stateful body and the template projection.
    pub(crate) fn apply_str(&self, s: &str, func: &str) -> Result<String> {
        match self {
            TextPump::Trim => Ok(text_trim_str(s)),
            TextPump::TrimPrefix(prefix) => Ok(text_trim_prefix_str(s, prefix)),
            TextPump::TrimSuffix(suffix) => Ok(text_trim_suffix_str(s, suffix)),
            TextPump::ToUpper => Ok(s.to_uppercase()),
            TextPump::ToLower => Ok(s.to_lowercase()),
            TextPump::ReplaceLiteral { from, to } => text_replace_literal_str(s, from, to, func),
        }
    }
}

/// String-only projection of a mirror op for `{{ }}` placeholder
/// expansion: strings apply eagerly through the shared pump semantics,
/// pipes bail naming the step IO they need (placeholder evaluation
/// has no step context to pump through).
pub(crate) fn mirror_string(func: &str, value: &Value, pump: TextPump) -> Result<Value> {
    if let Some(s) = value.as_str() {
        return pump.apply_str(s, func).map(Value::string);
    }
    Err(pipe_needs_step_io(func))
}

/// Refusal for pipe words reaching a template projection: one message
/// for every mirror op, so the boundary cannot drift per function.
pub(crate) fn pipe_needs_step_io(func: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "{func} on PIPE input needs step IO, unavailable to placeholder calls; pass a STRING there"
    )
}

/// Mirror a `STRING|PIPE` input through a transform: strings apply
/// eagerly, pipes stream on a named pump thread while the output
/// handle returns immediately. Argument validation that can fail
/// (empty search strings) runs before spawning so misuses bail at the
/// call site instead of truncating a stream.
pub(crate) fn mirror_stream<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    func: &str,
    value: &Value,
    pump: TextPump,
) -> Result<Value> {
    if let Some(s) = value.as_str() {
        return pump.apply_str(s, func).map(Value::string);
    }
    if value.as_pipe_handle().is_none() {
        return Err(type_mismatch(
            &format!("{func} text position"),
            &oxdock_parser::union_tag!(String, Pipe),
            value,
        ));
    }
    if let TextPump::ReplaceLiteral { from, .. } = &pump
        && from.is_empty()
    {
        bail!("{func} needs a non-empty search string");
    }
    let reader = cx
        .pipe_reader(value)
        .map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e:#}"))?;
    let output = cx.new_pipe();
    let writer = cx
        .pipe_writer(&output)
        .map_err(|e| anyhow::anyhow!("{func} cannot create PIPE output: {e:#}"))?;
    let cancelled = cx.cancel_token();
    let thread_name = format!("oxdock-text-{func}-pump");
    std::thread::Builder::new()
        .name(thread_name)
        .spawn(move || run_text_pump(reader, writer, pump, &cancelled))
        .map_err(|e| anyhow::anyhow!("{func} cannot spawn pump thread: {e}"))?;
    Ok(output)
}

/// Pump stop signal: the downstream read end closed early (Unix
/// short-circuit, e.g. a consumer that took one line and left). Not a
/// failure: the pump exits cleanly without tripping cancellation, so a
/// disconnected consumer never aborts the run.
#[derive(Debug)]
struct PumpDownstreamClosed;

impl std::fmt::Display for PumpDownstreamClosed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("text pump downstream closed its read end")
    }
}

impl std::error::Error for PumpDownstreamClosed {}

/// Pump body: move bytes from `reader` to `writer` through one
/// transform until input EOF, cancellation, or failure. The writer
/// drops on every exit path, so the output pipe closes and downstream
/// readers observe EOF instead of hanging. Mid-stream failures
/// (undecodable bytes in a char-interpreting op, a spill write past
/// the backlog cap) trip the shared cancellation flag before exiting:
/// the pump thread owns no call-site error channel, so tripping cancel
/// fails the run loudly at the next step boundary instead of letting
/// consumers proceed on truncated bytes. A downstream disconnect
/// (`BrokenPipe`) stops cleanly with no trip: short-circuiting a
/// pipeline must never read as an engine abort.
fn run_text_pump(
    reader: SharedInput,
    writer: SharedOutput,
    pump: TextPump,
    cancelled: &AtomicBool,
) {
    let fail_closed = |cancelled: &AtomicBool| {
        cancelled.store(true, Ordering::SeqCst);
    };
    let mut state = TextPumpState::new(pump);
    let mut chunk = [0u8; super::io::CHUNK_SIZE];
    loop {
        if cancelled.load(Ordering::SeqCst) {
            break;
        }
        let n = match reader.lock() {
            Ok(mut guard) => match guard.read(&mut chunk) {
                Ok(n) => n,
                Err(_) => {
                    fail_closed(cancelled);
                    break;
                }
            },
            Err(_) => {
                fail_closed(cancelled);
                break;
            }
        };
        if n == 0 {
            if let Err(e) = state.flush(&writer)
                && e.downcast_ref::<PumpDownstreamClosed>().is_none()
            {
                fail_closed(cancelled);
            }
            break;
        }
        if let Err(e) = state.push(&chunk[..n], &writer) {
            if e.downcast_ref::<PumpDownstreamClosed>().is_none() {
                fail_closed(cancelled);
            }
            break;
        }
    }
}

/// Per-op streaming state behind `run_text_pump`. `push` transforms one
/// input chunk and writes output promptly; `flush` emits the trailing
/// remainder at input EOF. Either fails on undecodable bytes (char
/// interpreting ops), poisoned locks, or spill writes past the backlog
/// cap; the pump ends the stream on any failure.
enum TextPumpState {
    Case {
        upper: bool,
        carry: Vec<u8>,
    },
    Trim {
        leading: bool,
        carry: Vec<u8>,
        held: SpillBuffer,
    },
    Prefix {
        prefix: Vec<u8>,
        buf: Vec<u8>,
        decided: bool,
    },
    Suffix {
        suffix: Vec<u8>,
        window: Vec<u8>,
    },
    Replace {
        from: Vec<u8>,
        to: Vec<u8>,
        buf: Vec<u8>,
    },
}

impl TextPumpState {
    fn new(pump: TextPump) -> Self {
        match pump {
            TextPump::Trim => Self::Trim {
                leading: false,
                carry: Vec::new(),
                held: SpillBuffer::new(),
            },
            TextPump::TrimPrefix(prefix) => Self::Prefix {
                prefix: prefix.into_bytes(),
                buf: Vec::new(),
                decided: false,
            },
            TextPump::TrimSuffix(suffix) => Self::Suffix {
                suffix: suffix.into_bytes(),
                window: Vec::new(),
            },
            TextPump::ToUpper => Self::Case {
                upper: true,
                carry: Vec::new(),
            },
            TextPump::ToLower => Self::Case {
                upper: false,
                carry: Vec::new(),
            },
            TextPump::ReplaceLiteral { from, to } => Self::Replace {
                from: from.into_bytes(),
                to: to.into_bytes(),
                buf: Vec::new(),
            },
        }
    }

    fn push(&mut self, data: &[u8], writer: &SharedOutput) -> Result<()> {
        match self {
            Self::Case { upper, carry } => Self::push_case(*upper, carry, data, writer),
            Self::Trim {
                leading,
                carry,
                held,
            } => Self::push_trim(leading, carry, held, data, writer),
            Self::Prefix {
                prefix,
                buf,
                decided,
            } => Self::push_prefix(prefix, buf, decided, data, writer),
            Self::Suffix { suffix, window } => Self::push_suffix(suffix, window, data, writer),
            Self::Replace { from, to, buf } => Self::push_replace(from, to, buf, data, writer),
        }
    }

    fn flush(&mut self, writer: &SharedOutput) -> Result<()> {
        match self {
            Self::Case { upper, carry } => {
                let text = std::str::from_utf8(carry)
                    .map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
                let mapped = if *upper {
                    text.to_uppercase()
                } else {
                    text.to_lowercase()
                };
                Self::write(writer, mapped.as_bytes())
            }
            Self::Trim {
                leading,
                carry,
                held,
            } => {
                if !*leading {
                    return Ok(());
                }
                // Trailing whitespace stays held: drop the spill
                // without draining, then emit the decoded tail minus
                // its own trailing run.
                let _ = held;
                let text = std::str::from_utf8(carry)
                    .map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
                let head = text.trim_end_matches(char::is_whitespace);
                Self::write(writer, head.as_bytes())
            }
            Self::Prefix { buf, decided, .. } => {
                if *decided {
                    return Ok(());
                }
                *decided = true;
                let rest = std::mem::take(buf);
                Self::write(writer, &rest)
            }
            Self::Suffix { suffix, window } => {
                let rest = std::mem::take(window);
                if !suffix.is_empty() && rest.as_slice() == suffix.as_slice() {
                    return Ok(());
                }
                Self::write(writer, &rest)
            }
            Self::Replace { from, to, buf } => {
                let (out, consumed) = Self::replace_scan(from, to, buf, buf.len());
                buf.drain(..consumed);
                Self::write(writer, &out)
            }
        }
    }

    /// Write one output segment, skipping empties so the pipe never
    /// observes a zero-length write. A broken downstream read end
    /// carries the typed stop signal instead of a failure, so the pump
    /// exits cleanly without tripping cancellation.
    fn write(writer: &SharedOutput, bytes: &[u8]) -> Result<()> {
        if bytes.is_empty() {
            return Ok(());
        }
        writer
            .lock()
            .map_err(|_| anyhow::anyhow!("text pump writer lock poisoned"))?
            .write_all(bytes)
            .map_err(|e| {
                if e.kind() == std::io::ErrorKind::BrokenPipe {
                    anyhow::Error::new(PumpDownstreamClosed)
                } else {
                    anyhow::anyhow!("text pump write failed: {e}")
                }
            })?;
        Ok(())
    }

    /// Drain a spill hold-back into the output (spill failures past the
    /// backlog cap end the stream through the caller).
    fn drain_into(held: &SpillBuffer, writer: &SharedOutput) -> Result<()> {
        let bytes = held
            .drain_bytes()
            .map_err(|e| anyhow::anyhow!("text pump spill drain failed: {e}"))?;
        Self::write(writer, &bytes)
    }

    /// Split staged bytes into a char-boundary valid head plus an
    /// incomplete tail to carry, so multibyte characters split across
    /// pipe chunks never misdecode.
    fn head_tail(staged: &[u8]) -> (&[u8], &[u8]) {
        let hold = trailing_incomplete_len(staged);
        staged.split_at(staged.len() - hold)
    }

    fn push_case(
        upper: bool,
        carry: &mut Vec<u8>,
        data: &[u8],
        writer: &SharedOutput,
    ) -> Result<()> {
        let mut staged = std::mem::take(carry);
        staged.extend_from_slice(data);
        let (head, tail) = Self::head_tail(&staged);
        let text = std::str::from_utf8(head)
            .map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
        let mapped = if upper {
            text.to_uppercase()
        } else {
            text.to_lowercase()
        };
        Self::write(writer, mapped.as_bytes())?;
        *carry = tail.to_vec();
        Ok(())
    }

    fn push_trim(
        leading: &mut bool,
        carry: &mut Vec<u8>,
        held: &SpillBuffer,
        data: &[u8],
        writer: &SharedOutput,
    ) -> Result<()> {
        let mut staged = std::mem::take(carry);
        staged.extend_from_slice(data);
        let (head, tail) = Self::head_tail(&staged);
        let mut text = std::str::from_utf8(head)
            .map_err(|_| anyhow::anyhow!("text pump input is not valid UTF-8"))?;
        if !*leading {
            text = text.trim_start_matches(char::is_whitespace);
            if text.is_empty() {
                *carry = tail.to_vec();
                return Ok(());
            }
            *leading = true;
        }
        let content = text.trim_end_matches(char::is_whitespace);
        let ws = &text[content.len()..];
        if !content.is_empty() {
            Self::drain_into(held, writer)?;
            Self::write(writer, content.as_bytes())?;
        }
        held.push_bytes(ws.as_bytes())
            .map_err(|e| anyhow::anyhow!("text pump spill failed: {e}"))?;
        *carry = tail.to_vec();
        Ok(())
    }

    fn push_prefix(
        prefix: &[u8],
        buf: &mut Vec<u8>,
        decided: &mut bool,
        data: &[u8],
        writer: &SharedOutput,
    ) -> Result<()> {
        if *decided {
            return Self::write(writer, data);
        }
        buf.extend_from_slice(data);
        if buf.len() < prefix.len() {
            return Ok(());
        }
        *decided = true;
        let taken = std::mem::take(buf);
        match taken.strip_prefix(prefix) {
            Some(rest) => Self::write(writer, rest),
            None => Self::write(writer, &taken),
        }
    }

    fn push_suffix(
        suffix: &[u8],
        window: &mut Vec<u8>,
        data: &[u8],
        writer: &SharedOutput,
    ) -> Result<()> {
        if suffix.is_empty() {
            return Self::write(writer, data);
        }
        window.extend_from_slice(data);
        if window.len() > suffix.len() {
            let emit = window.len() - suffix.len();
            Self::write(writer, &window[..emit])?;
            window.drain(..emit);
        }
        Ok(())
    }

    fn push_replace(
        from: &[u8],
        to: &[u8],
        buf: &mut Vec<u8>,
        data: &[u8],
        writer: &SharedOutput,
    ) -> Result<()> {
        buf.extend_from_slice(data);
        let retain = (from.len() - 1).min(buf.len());
        let emit_until = buf.len() - retain;
        let (out, consumed) = Self::replace_scan(from, to, buf, emit_until);
        buf.drain(..consumed);
        Self::write(writer, &out)
    }

    /// Scan `buf[..limit]` for non-overlapping literal matches,
    /// returning the rewritten bytes plus the consumed length. Matches
    /// crossing `limit` stay buffered: their visible part is a needle
    /// prefix that future bytes may complete.
    fn replace_scan(from: &[u8], to: &[u8], buf: &[u8], limit: usize) -> (Vec<u8>, usize) {
        let mut out = Vec::with_capacity(limit);
        let mut i = 0;
        while i < limit {
            if buf[i..].starts_with(from) {
                out.extend_from_slice(to);
                i += from.len();
            } else {
                out.push(buf[i]);
                i += 1;
            }
        }
        (out, i)
    }
}

/// Length of a possibly-incomplete UTF-8 sequence at the end of `buf`:
/// a lead byte plus fewer continuations than it needs. Complete tails
/// validate immediately (return 0); anything strictly invalid is left
/// for `from_utf8` to reject rather than hidden in the hold-back.
fn trailing_incomplete_len(buf: &[u8]) -> usize {
    for n in 1..=3 {
        if n > buf.len() {
            break;
        }
        let b = buf[buf.len() - n];
        if b < 0x80 {
            break;
        }
        if b >= 0xC0 {
            // 0xF5-0xFF never leads a valid sequence: fail now
            // instead of holding bytes no future read can redeem.
            if b > 0xF4 {
                break;
            }
            let need = if b < 0xE0 {
                2
            } else if b < 0xF0 {
                3
            } else {
                4
            };
            if n < need {
                return n;
            }
            break;
        }
    }
    0
}

/// Eager pipe read for ops whose framing needs the whole content at
/// once (regex replacement: matches span chunks). Stages through the
/// spill substrate (memory then disk, failing closed past its backlog
/// cap) instead of one heap buffer, with incremental UTF-8 validation
/// per chunk so a bad lead byte fails on arrival.
pub(crate) fn read_pipe_eager<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    func: &str,
    value: &Value,
) -> Result<String> {
    if value.as_pipe_handle().is_none() {
        return Err(type_mismatch(
            &format!("{func} text position"),
            &oxdock_parser::union_tag!(String, Pipe),
            value,
        ));
    }
    let reader = cx
        .pipe_reader(value)
        .map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e:#}"))?;
    let spill = SpillBuffer::new();
    let mut carry = Vec::new();
    let mut chunk = [0u8; super::io::CHUNK_SIZE];
    loop {
        let n = reader.lock().map(|mut guard| guard.read(&mut chunk));
        let n = n
            .map_err(|_| anyhow::anyhow!("{func} pipe reader lock poisoned"))?
            .map_err(|e| anyhow::anyhow!("{func} cannot read PIPE input: {e}"))?;
        if n == 0 {
            break;
        }
        let mut staged = std::mem::take(&mut carry);
        staged.extend_from_slice(&chunk[..n]);
        let hold = trailing_incomplete_len(&staged);
        let valid_len = staged.len() - hold;
        std::str::from_utf8(&staged[..valid_len])
            .map_err(|_| anyhow::anyhow!("{func} PIPE input is not valid UTF-8"))?;
        spill
            .push_bytes(&staged[..valid_len])
            .map_err(|e| anyhow::anyhow!("{func} PIPE input exceeds the spill backlog: {e}"))?;
        carry = staged[valid_len..].to_vec();
    }
    spill
        .push_bytes(&carry)
        .map_err(|e| anyhow::anyhow!("{func} PIPE input exceeds the spill backlog: {e}"))?;
    spill
        .drain_string_strict()
        .map_err(|_| anyhow::anyhow!("{func} PIPE input is not valid UTF-8"))
}

/// Completed pipe for eager pipe-out: mints a task-owned handle, writes
/// the bytes, and closes by dropping the writer, so readers drain the
/// content then observe EOF exactly like a finished pump.
pub(crate) fn write_completed_pipe<P: ProcessManager>(
    cx: &mut StepCtx<'_, P>,
    func: &str,
    text: String,
) -> Result<Value> {
    let pipe = cx.new_pipe();
    let writer = cx
        .pipe_writer(&pipe)
        .map_err(|e| anyhow::anyhow!("{func} cannot create PIPE output: {e:#}"))?;
    {
        let mut guard = writer
            .lock()
            .map_err(|_| anyhow::anyhow!("{func} pipe writer lock poisoned"))?;
        guard
            .write_all(text.as_bytes())
            .map_err(|e| anyhow::anyhow!("{func} cannot write PIPE output: {e}"))?;
        guard
            .flush()
            .map_err(|e| anyhow::anyhow!("{func} cannot write PIPE output: {e}"))?;
    }
    Ok(pipe)
}

/// Lift a string list into a `LIST<STRING>` word.
pub(crate) fn text_list_value(items: Vec<String>) -> Value {
    Value::list(items.into_iter().map(Value::string).collect())
}

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

    #[test]
    fn pop_stack_underflow_returns_error() {
        let mut stack: Vec<Value> = Vec::new();
        assert!(
            pop_stack(&mut stack).is_err(),
            "empty pop must error, not panic"
        );
        stack.push(Value::int(1));
        assert_eq!(pop_stack(&mut stack).unwrap(), Value::int(1));
        assert!(pop_stack(&mut stack).is_err());
    }

    #[test]
    fn type_of_names_words_for_branching() {
        use std::collections::BTreeMap;
        // Table-driven over the startup registry itself: a new word
        // without a sampler below fails here naming the word, so the
        // table can never silently shrink behind a hand list.
        fn sample(name: &str) -> Option<Value> {
            match name {
                "INT" => Some(Value::int(1)),
                "FLOAT" => Some(Value::float(1.5)),
                "STRING" => Some(Value::string("x".to_string())),
                "BOOL" => Some(Value::bool(true)),
                "LIST" => Some(Value::list(vec![])),
                "MAP" => Some(Value::map(BTreeMap::new())),
                "PATH" => {
                    #[allow(clippy::disallowed_types)]
                    let path = std::path::PathBuf::from("x");
                    Some(Value::path(path))
                }
                "DURATION" => Some(Value::duration(std::time::Duration::from_secs(1))),
                "PIPE" => Some(Value::pipe_fresh()),
                "HANDLE" => Some(Value::handle(1)),
                "SEMAPHORE" => Some(Value::semaphore(1)),
                "PERMIT" => {
                    let sem = Value::semaphore(1);
                    let backend = sem.as_semaphore().expect("semaphore backend");
                    Some(Value::permit(&backend))
                }
                _ => None,
            }
        }
        for (name, _) in oxdock_parser::startup_descriptors() {
            let value =
                sample(name).unwrap_or_else(|| panic!("no sampler for startup word {name}"));
            let word = type_of_from_value(value).expect("type_of runs");
            assert_eq!(word.as_str(), Some(name), "TYPE_OF must name {name}");
        }
    }

    #[test]
    fn map_set_inserts_and_rejects_duplicates() {
        use std::collections::BTreeMap;
        let empty = Value::map(BTreeMap::new());
        let one = map_set_from_value(empty, "a".to_string(), Value::string("x".to_string()))
            .expect("insert");
        assert_eq!(
            one.as_map().expect("map").get("a").expect("key").as_str(),
            Some("x")
        );
        assert!(map_set_from_value(one, "a".to_string(), Value::string("y".to_string())).is_err());
        assert!(
            map_set_from_value(
                Value::string("nope".to_string()),
                "a".to_string(),
                Value::int(1)
            )
            .is_err()
        );
    }

    #[test]
    fn has_key_reports_presence() {
        use std::collections::BTreeMap;
        let mut entries = BTreeMap::new();
        entries.insert("name".to_string(), Value::string("mary".to_string()));
        let mary = Value::map(entries);
        assert_eq!(
            has_key_from_value(mary.clone(), "name")
                .expect("has")
                .as_bool(),
            Some(true)
        );
        assert_eq!(
            has_key_from_value(mary, "globs").expect("has").as_bool(),
            Some(false)
        );
        assert!(has_key_from_value(Value::int(1), "name").is_err());
    }

    #[test]
    fn parse_text_matches_file_load_shapes() {
        let json = parse_json_from_value(Value::string("{\"a\": 1}".to_string())).expect("parse");
        assert_eq!(
            json.as_map().expect("map").get("a").expect("key").as_i64(),
            Some(1)
        );
        let toml = parse_toml_from_value(Value::string("a = 2\n".to_string())).expect("parse");
        assert_eq!(
            toml.as_map().expect("map").get("a").expect("key").as_i64(),
            Some(2)
        );
        // Any-shape inputs stay any-shape: arrays parse to LIST, which is
        // why PARSE_JSON returns ANY instead of MAP.
        let list = parse_json_from_value(Value::string("[1, 2]".to_string())).expect("parse");
        assert_eq!(list.as_list().expect("list").len(), 2);
        assert!(parse_json_from_value(Value::string("{bad".to_string())).is_err());
        assert!(parse_toml_from_value(Value::string("a = ".to_string())).is_err());
        assert!(parse_json_from_value(Value::int(1)).is_err());
        assert!(parse_toml_from_value(Value::bool(true)).is_err());
    }

    #[test]
    fn merge_maps_layers_in_order() {
        use std::collections::BTreeMap;
        let mut base_entries = BTreeMap::new();
        base_entries.insert("a".to_string(), Value::string("1".to_string()));
        let mut overlay_entries = BTreeMap::new();
        overlay_entries.insert("b".to_string(), Value::string("2".to_string()));
        overlay_entries.insert("c".to_string(), Value::int(3));
        let merged = merge_maps_from_value(
            Value::list(vec![Value::map(base_entries), Value::map(overlay_entries)]),
            "overwrite".to_string(),
        )
        .expect("merge")
        .as_map()
        .expect("map")
        .clone();
        assert_eq!(merged.get("a").expect("a").as_str(), Some("1"));
        assert_eq!(merged.get("c").expect("c").as_i64(), Some(3));
    }

    #[test]
    fn merge_maps_fail_on_duplicate_names_the_key() {
        use std::collections::BTreeMap;
        let mut first_entries = BTreeMap::new();
        first_entries.insert("name".to_string(), Value::string("base".to_string()));
        let mut second_entries = BTreeMap::new();
        second_entries.insert("name".to_string(), Value::string("overlay".to_string()));
        let err = merge_maps_from_value(
            Value::list(vec![Value::map(first_entries), Value::map(second_entries)]),
            "fail_on_duplicate".to_string(),
        )
        .expect_err("duplicate must fail");
        assert!(
            format!("{err:#}").contains("name"),
            "error names the key: {err:#}"
        );
    }

    #[test]
    fn merge_maps_rejects_bad_shapes() {
        assert!(
            merge_maps_from_value(Value::string("nope".to_string()), "overwrite".to_string())
                .is_err(),
            "non LIST fails",
        );
        for (element, word) in [
            (Value::int(1), "INT"),
            (Value::string("nope".to_string()), "STRING"),
            (Value::list(vec![Value::int(1)]), "LIST"),
            (Value::bool(true), "BOOL"),
        ] {
            let err = merge_maps_from_value(Value::list(vec![element]), "overwrite".to_string())
                .expect_err("non MAP element must fail");
            let text = format!("{err:#}");
            assert!(
                text.contains("element 0") && text.contains(word),
                "error names position and offending shape: {text}"
            );
        }
    }

    #[test]
    fn rand_draws_stay_in_unit_interval() {
        for _ in 0..1000 {
            let draw = rand_float_from_value(None)
                .expect("draw")
                .as_f64()
                .expect("float");
            assert!((0.0..1.0).contains(&draw), "draw out of [0, 1): {draw}");
        }
    }

    #[test]
    fn rand_seed_is_deterministic() {
        let first = rand_float_from_value(Some(7))
            .expect("seeded")
            .as_f64()
            .expect("float");
        let second = rand_float_from_value(Some(7))
            .expect("seeded")
            .as_f64()
            .expect("float");
        assert_eq!(first, second, "same seed draws the same value");
        assert!(
            (0.0..1.0).contains(&first),
            "seeded draw out of [0, 1): {first}"
        );
    }

    #[test]
    fn base64_round_trips_standard_alphabet() {
        let encoded = base64_encode_from_value(Value::string("hello".to_string()))
            .expect("encode")
            .as_str()
            .expect("string")
            .to_string();
        assert_eq!(encoded, "aGVsbG8=");
        let decoded = base64_decode_from_value(Value::string(encoded))
            .expect("decode")
            .as_str()
            .expect("string")
            .to_string();
        assert_eq!(decoded, "hello");
        assert!(base64_decode_from_value(Value::string("!!!".to_string())).is_err());
        assert!(base64_encode_from_value(Value::int(1)).is_err());
        assert!(base64_decode_from_value(Value::int(1)).is_err());
    }

    #[test]
    fn to_json_sorts_keys_and_appends_newline() {
        use std::collections::BTreeMap;
        let mut entries = BTreeMap::new();
        entries.insert("b".to_string(), Value::int(2));
        entries.insert(
            "a".to_string(),
            Value::list(vec![Value::string("x".to_string()), Value::bool(true)]),
        );
        let encoded = to_json_from_value(Value::map(entries))
            .expect("encode")
            .as_str()
            .expect("string")
            .to_string();
        assert_eq!(encoded, "{\"a\":[\"x\",true],\"b\":2}\n");
        assert!(to_json_from_value(Value::handle(1)).is_err());
    }

    #[test]
    fn apply_arith_int_and_errors() {
        assert_eq!(
            apply_arith(ArithOp::Add, Value::int(2), Value::int(3)).unwrap(),
            Value::int(5)
        );
        assert!(apply_arith(ArithOp::Div, Value::int(1), Value::int(0)).is_err());
        assert!(
            apply_arith(ArithOp::Add, Value::int(i64::MAX), Value::int(1)).is_err(),
            "int overflow must bail"
        );
        assert!(
            apply_arith(ArithOp::Add, Value::string("a".to_string()), Value::int(1)).is_err(),
            "string arithmetic must be a Type Error"
        );
        assert!(apply_neg(Value::int(i64::MIN)).is_err());
    }

    #[test]
    fn apply_arith_float_promotion() {
        assert_eq!(
            apply_arith(ArithOp::Add, Value::int(1), Value::float(2.5)).unwrap(),
            Value::float(3.5)
        );
        assert!(apply_arith(ArithOp::Div, Value::float(1.0), Value::float(0.0)).is_err());
    }

    #[test]
    fn apply_compare_numeric_and_fallback() {
        assert_eq!(
            apply_compare(CompareOp::Eq, &Value::int(1), &Value::float(1.0)).unwrap(),
            Value::bool(true)
        );
        assert_eq!(
            apply_compare(CompareOp::Lt, &Value::int(3), &Value::float(4.5)).unwrap(),
            Value::bool(true)
        );
        assert_eq!(
            apply_compare(
                CompareOp::Eq,
                &Value::string("a".to_string()),
                &Value::string("a".to_string())
            )
            .unwrap(),
            Value::bool(true)
        );
        assert!(
            apply_compare(
                CompareOp::Lt,
                &Value::string("a".to_string()),
                &Value::string("b".to_string())
            )
            .is_err(),
            "ordering on strings must bail"
        );
    }

    #[test]
    fn int_float_conversions() {
        assert_eq!(
            int_from_value(Value::string("  123\n".to_string())).unwrap(),
            Value::int(123)
        );
        assert_eq!(int_from_value(Value::float(3.0)).unwrap(), Value::int(3));
        assert!(int_from_value(Value::float(3.5)).is_err());
        assert!(int_from_value(Value::string("abc".to_string())).is_err());
        assert_eq!(int_from_value(Value::bool(true)).unwrap(), Value::int(1));
        assert_eq!(int_from_value(Value::bool(false)).unwrap(), Value::int(0));
        assert_eq!(
            float_from_value(Value::string("2.5".to_string())).unwrap(),
            Value::float(2.5)
        );
        assert_eq!(float_from_value(Value::int(3)).unwrap(), Value::float(3.0));
        for bad in ["nan", "inf", "-inf", "abc"] {
            assert!(
                float_from_value(Value::string(bad.to_string())).is_err(),
                "{bad:?} must fail"
            );
        }
    }

    #[test]
    fn coerce_value_coerces_union_members_in_order() {
        use oxdock_parser::union_tag;
        // Built by macro: no hand-written spelling to drift.
        let union = union_tag!(Int, Float);
        assert_eq!(union.name(), "INT|FLOAT");
        // Exact members pass through untouched.
        assert_eq!(
            coerce_value(Value::int(7), &union)
                .expect("int passes")
                .as_i64(),
            Some(7)
        );
        // Strict boundary: strings never parse into numeric slots.
        // The explicit `INT()` converter owns that parsing; coercion
        // names the set instead of silently re-parsing.
        let err = coerce_value(Value::string("123".to_string()), &union).expect_err("string fails");
        assert!(
            format!("{err:#}").contains("expected INT|FLOAT"),
            "names the set: {err:#}"
        );
        let mixed = union_tag!(Float, String);
        assert_eq!(
            coerce_value(Value::int(10), &mixed)
                .expect("int coerces")
                .as_f64(),
            Some(10.0)
        );
        // Total failure names the set, never a single member.
        let err = coerce_value(Value::bool(true), &union).expect_err("bool fails");
        assert!(
            format!("{err:#}").contains("expected INT|FLOAT"),
            "names the set: {err:#}"
        );
    }

    #[test]
    fn text_helpers_cover_table_ops() {
        assert_eq!(text_trim_str("  hello  "), "hello");
        assert_eq!(text_trim_prefix_str("v1.2.3", "v"), "1.2.3");
        assert_eq!(text_trim_prefix_str("1.2.3", "v"), "1.2.3");
        assert_eq!(text_trim_suffix_str("archive.tar.gz", ".gz"), "archive.tar");
        assert_eq!(text_trim_suffix_str("archive.tar", ".gz"), "archive.tar");
        assert_eq!(text_split_str("a,b,c", ","), vec!["a", "b", "c"]);
        assert_eq!(text_split_str("ab", ""), vec!["a", "b"]);
        assert_eq!(text_fields_str("  abc  def "), vec!["abc", "def"]);
        assert_eq!(
            text_lines_str("one\ntwo\nthree"),
            vec!["one", "two", "three"]
        );
        assert_eq!(
            text_lines_str("one\r\ntwo\r\nthree"),
            vec!["one", "two", "three"]
        );
        assert_eq!(
            text_lines_str("one\rtwo\rthree"),
            vec!["one", "two", "three"]
        );
        assert_eq!(text_lines_str("a\r\nb\nc\rd"), vec!["a", "b", "c", "d"]);
        assert_eq!(
            text_replace_literal_str("hello world", "world", "there", "TEXT_REPLACE")
                .expect("replace"),
            "hello there"
        );
        assert!(
            text_replace_literal_str("hello", "", "x", "TEXT_REPLACE").is_err(),
            "empty search strings must fail closed"
        );
        assert_eq!(
            text_replace_regex_str(
                "2026-10-13",
                "(\\d+)-(\\d+)-(\\d+)",
                "$3/$2/$1",
                "TEXT_REPLACE_REGEX"
            )
            .expect("regex replace"),
            "13/10/2026"
        );
        assert_eq!(trailing_incomplete_len("abc".as_bytes()), 0);
        assert_eq!(trailing_incomplete_len("é".as_bytes()), 0);
        assert_eq!(trailing_incomplete_len(&[0xC3]), 1);
        assert_eq!("héllo".chars().count(), 5);
        assert_eq!(
            text_count_str("hello world", "o", "TEXT_COUNT").expect("count"),
            2
        );
        assert_eq!(text_count_str("aaa", "aa", "TEXT_COUNT").expect("once"), 1);
        assert!(text_count_str("aaa", "", "TEXT_COUNT").is_err());
        assert_eq!(
            text_count_matches_str("test a: test\ntest b: nope", ": test", "TEXT_COUNT_MATCHES")
                .expect("count matches"),
            1
        );
        assert_eq!(
            text_count_matches_str("a\r\nb\nc", "^[ab]$", "TEXT_COUNT_MATCHES")
                .expect("universal lines"),
            2
        );
        assert_eq!(
            text_grep_str("one\ntwo\none more", "^one", false, "TEXT_GREP").expect("grep"),
            vec!["one", "one more"]
        );
        assert!(
            text_grep_str("one\ntwo", "^z", false, "TEXT_GREP")
                .expect("miss")
                .is_empty()
        );
        assert_eq!(
            text_grep_str("one\ntwo\none more", "^one", true, "TEXT_GREP").expect("invert"),
            vec!["two"]
        );
        assert!(
            text_grep_str("one\ntwo", "^", true, "TEXT_GREP")
                .expect("invert match-all")
                .is_empty()
        );
        // Compiled patterns cache by text: same pattern, same automaton.
        let first = text_compile_pattern("TEXT_MATCH", "\\d+").expect("compile");
        let second = text_compile_pattern("TEXT_MATCH", "\\d+").expect("cached");
        assert_eq!(first.as_str(), second.as_str());
        assert_eq!(
            text_lines_range_str("one\ntwo\nthree\nfour", 2, 3, "TEXT_LINES_RANGE")
                .expect("window"),
            vec!["two", "three"]
        );
        assert_eq!(
            text_lines_range_str("one\ntwo", 2, 9, "TEXT_LINES_RANGE").expect("clamp"),
            vec!["two"]
        );
        assert!(
            text_lines_range_str("one\ntwo", 9, 12, "TEXT_LINES_RANGE")
                .expect("past end")
                .is_empty()
        );
        assert!(text_lines_range_str("one", 0, 2, "TEXT_LINES_RANGE").is_err());
        assert!(text_lines_range_str("one", 3, 2, "TEXT_LINES_RANGE").is_err());
        assert_eq!(
            text_extract_str("abc123", "([a-z]+)(\\d+)", "TEXT_EXTRACT").expect("extract"),
            vec!["abc123", "abc", "123"]
        );
        assert!(
            text_extract_str("abc", "^\\d+$", "TEXT_EXTRACT")
                .expect("miss")
                .is_empty()
        );
        assert!(text_compile_pattern("TEXT_MATCH", "([").is_err());
        assert_eq!(
            text_list_value(vec!["a".to_string()])
                .as_list()
                .expect("list")
                .len(),
            1
        );
    }

    /// Drive one pump state through chunked pushes plus flush, collecting
    /// output from a spill-backed writer. Lets pump framing tests run
    /// without threads or script pipes.
    fn pump_to_string(pump: TextPump, chunks: &[&[u8]]) -> String {
        use std::sync::Arc;
        let spill = Arc::new(SpillBuffer::new());
        let writer = spill.writer();
        let mut state = TextPumpState::new(pump);
        for chunk in chunks {
            state.push(chunk, &writer).expect("pump push runs");
        }
        state.flush(&writer).expect("pump flush runs");
        let out = spill.drain_bytes().expect("spill drains");
        String::from_utf8(out).expect("pump output is UTF-8")
    }

    #[test]
    fn text_pump_streams_case_across_char_cuts() {
        // A two-byte char split across pushes still folds as one char.
        let out = pump_to_string(TextPump::ToUpper, &[&[0xC3], &[0xA9]]);
        assert_eq!(out, "É");
        let out = pump_to_string(TextPump::ToLower, &[b"HE", b"LLO"]);
        assert_eq!(out, "hello");
        // Invalid bytes end the stream at the bad chunk.
        use std::sync::Arc;
        let spill = Arc::new(SpillBuffer::new());
        let writer = spill.writer();
        let mut state = TextPumpState::new(TextPump::ToUpper);
        state.push(b"ok", &writer).expect("valid prefix writes");
        assert!(state.push(&[0xFF], &writer).is_err());
    }

    #[test]
    fn text_pump_trims_edges_streaming() {
        // Leading whitespace falls at the head, trailing at EOF, and
        // interior whitespace passes through across chunk cuts.
        let out = pump_to_string(TextPump::Trim, &[b"   hel", b"lo   ", b"   "]);
        assert_eq!(out, "hello");
        let out = pump_to_string(TextPump::Trim, &[b"  a  b  "]);
        assert_eq!(out, "a  b");
        // All-whitespace input strips to empty.
        let out = pump_to_string(TextPump::Trim, &[b"   ", b"\n\t "]);
        assert_eq!(out, "");
    }

    #[test]
    fn text_pump_prefix_decides_once_at_head() {
        // A prefix split across pushes still strips exactly once.
        let out = pump_to_string(TextPump::TrimPrefix("v".to_string()), &[b"v", b"1.2.3"]);
        assert_eq!(out, "1.2.3");
        // Absent prefixes pass through untouched, and short inputs
        // emit whole at EOF.
        let out = pump_to_string(TextPump::TrimPrefix("v".to_string()), &[b"1", b".2"]);
        assert_eq!(out, "1.2");
        // Only the head decides: later occurrences stay.
        let out = pump_to_string(TextPump::TrimPrefix("ab".to_string()), &[b"ababa"]);
        assert_eq!(out, "aba");
    }

    #[test]
    fn text_pump_suffix_holds_trailing_window() {
        // A suffix split across pushes still strips exactly once.
        let out = pump_to_string(
            TextPump::TrimSuffix(".gz".to_string()),
            &[b"archive.tar", b".g", b"z"],
        );
        assert_eq!(out, "archive.tar");
        // Near misses and short inputs pass through untouched.
        let out = pump_to_string(TextPump::TrimSuffix(".gz".to_string()), &[b"archive.tar"]);
        assert_eq!(out, "archive.tar");
        let out = pump_to_string(TextPump::TrimSuffix(".gz".to_string()), &[b"ab"]);
        assert_eq!(out, "ab");
    }

    #[test]
    fn text_pump_replace_spans_chunk_cuts() {
        // A needle split across pushes still rewrites, in order, with
        // no recursive rescan of replacement text.
        let out = pump_to_string(
            TextPump::ReplaceLiteral {
                from: "world".to_string(),
                to: "there".to_string(),
            },
            &[b"hello wo", b"rld and world"],
        );
        assert_eq!(out, "hello there and there");
        // Single-byte needles stream byte by byte.
        let out = pump_to_string(
            TextPump::ReplaceLiteral {
                from: "a".to_string(),
                to: "b".to_string(),
            },
            &[b"aaa", b"aa"],
        );
        assert_eq!(out, "bbbbb");
    }
}