oxdock-core 0.48.0-alpha

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

use oxdock_diagnostics::{Diagnostic, DiagnosticResult};
use oxdock_fs::to_forward_slashes;
use oxdock_fs::{GuardedPath, WorkspaceSelection};
use oxdock_func_macro::oxdock_func;
use oxdock_parser::value::HandleValue;
use oxdock_parser::{
    Field, GuardExpr, KEYWORD_CONST, KEYWORD_EXPORT, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IMPORT,
    KEYWORD_INSPECT, KEYWORD_LET, KEYWORD_TYPE, MODULE_SEPARATOR, SCRIPT_MODULE_NAME,
    STD_MODULE_NAME, SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify,
    render_structural, split_qualified, strip_sigil,
};
use oxdock_pipe::PipeHandle;
use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};

use super::diagnostics as std_diag;
use super::function_names::{
    FUNC_BOOL, FUNC_BOOL_OR, FUNC_PARSE_ARGS, FUNC_PARSE_FLAGS, FUNC_PARSE_POSITIONALS,
    FUNC_TEXT_COUNT, FUNC_TEXT_COUNT_MATCHES, FUNC_TEXT_EXTRACT, FUNC_TEXT_GREP,
    FUNC_TEXT_LINES_RANGE, FUNC_TEXT_MATCH, FUNC_TEXT_REPLACE, FUNC_TEXT_REPLACE_REGEX,
};
use super::io::StreamHandle;
use super::state::{ExecState, TypeSnapshot};
use super::steps::StepCtx;
use super::typing::TypeDescriptor;

/// Origin of a callable in the unified function registry. `Script` is an
/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
/// functions (the `#[oxdock_func]` host export macro). Builtins and
/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
/// shows the label, and both host kinds keep rendering as `host`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FuncKind {
    Script,
    HostCtx,
    HostPure,
}

/// Canonical registry key for a file-imported script function:
/// defining file plus base name, through the shared [`qualify`]
/// owner. Importer aliases never appear here.
pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
    qualify(defining_file, name)
}

/// Loud ambiguity error for one unit importing the same alias from
/// several files. `files` sorts for deterministic rendering.
pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
    let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
    files.sort();
    format!(
        "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
        files.join(", ")
    )
}

/// Single owner for the `function` to `CONST` wording shift.
/// All const-ambiguity sites route here, never restating `replacen`.
pub(super) fn const_ambiguous_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
    ambiguous_alias_message(alias, name, files).replacen("function", KEYWORD_CONST, 1)
}

/// One `ALIAS::FUNC` spelling's fate under a unit's alias targets.
/// Single owner for alias-target matching: every resolution path
/// (static calls, template gates, runtime dispatch, placeholder
/// misses, snapshots, re-exports) classifies here and acts on the
/// result, never restating the singleton/ambiguity branches.
pub(super) enum AliasResolution {
    /// Resolve as spelled (bare, `SCRIPT::`, hosts, unknown-to-unit).
    Global,
    /// Canonical defining-file key.
    Canonical(String),
    /// Known alias with no usable target: the caller reports unknown.
    Unknown,
    /// One alias, several files with the name in overlapping guards:
    /// fail loud, naming the colliding spelling.
    Ambiguous {
        alias: String,
        base: String,
        files: HashSet<String>,
    },
    /// Several files hold the name under disjoint guards: the caller
    /// validates every target instead of failing outright
    /// (platform-conditional imports). `has_host` marks a disjoint
    /// host-harvest branch (a `(None, guard)` target) alongside the
    /// files: that branch holds no file functions, so any file-backed
    /// call misses there.
    Any {
        base: String,
        files: HashSet<String>,
        has_host: bool,
    },
}

/// One unit's alias targets: defining file, host module name for
/// host-only imports, plus the import's guard. Single owner for the
/// target-set shape; static and runtime tables share it. Guards decide
/// ambiguity (overlapping guards importing different files under one
/// alias are ambiguous); unguarded imports overlap everything. Runtime
/// records `None` file with `Some(host)` for host imports (its imports
/// execute once taken).
/// One alias target: defining file, host module, and import guard.
/// Named fields so external callers cannot transpose the two
/// `Option<String>` positions. `file` is `Some` for file imports,
/// `host` is `Some` for host harvests, `guard` carries the import
/// guard when present.
#[derive(Clone, Debug, PartialEq)]
pub struct AliasTarget {
    pub file: Option<String>,
    pub host: Option<String>,
    pub guard: Option<GuardExpr>,
}

pub type AliasTargets = HashMap<String, Vec<AliasTarget>>;

/// Shared frame-walk precedence for script resolution (#322):
/// innermost nested frames, then the owning file top-level, then
/// per-unit harvests. Static checking and runtime dispatch implement
/// this trait over their own stores and share [`FuncFrameView::walk`],
/// so precedence lives once and the twins cannot drift.
pub(super) trait FuncFrameView {
    /// Resolution hit for this layer (entry, info+key, etc.).
    type Hit;
    /// Innermost nested frames outward.
    fn find_nested(&self, base: &str) -> Option<Self::Hit>;
    /// Owning file top-level (entry included via its unit key).
    fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
    /// Per-unit bare harvests.
    fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
    /// Precedence owner: nested, home, harvest.
    fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
        self.find_nested(base)
            .or_else(|| self.find_home(unit, base))
            .or_else(|| self.find_harvest(unit, base))
    }
}

/// Classify one call spelling under a unit's alias targets. Single
/// entry point for alias-target matching: splits the spelling,
/// resolves `SCRIPT::` and bare names globally, and maps file aliases
/// through the unit's recorded targets. `exists` probes the caller's
/// function map for a canonical key.
pub(super) fn classify_alias_call(
    unit_targets: &AliasTargets,
    name: &str,
    exists: &dyn Fn(&str) -> bool,
) -> AliasResolution {
    let Some((alias, base)) = split_qualified(name) else {
        return AliasResolution::Global;
    };
    if alias == SCRIPT_MODULE_NAME {
        return AliasResolution::Global;
    }
    let Some(entries) = unit_targets.get(alias) else {
        return AliasResolution::Global;
    };
    if entries.is_empty() {
        return AliasResolution::Unknown;
    }
    // Distinct defining files in first-seen order; `(None, Some(host),
    // guard)` entries are host-harvest branches holding no file functions.
    let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
    let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
    for target in entries {
        match &target.file {
            Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
                Some((_, guards)) => guards.push(target.guard.as_ref()),
                None => files.push((path, vec![target.guard.as_ref()])),
            },
            None => host_guards.push(target.guard.as_ref()),
        }
    }
    if files.is_empty() {
        return AliasResolution::Unknown;
    }
    let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
        left.iter()
            .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
    };
    if files.len() == 1 {
        // A lone file target stays canonical unless a host-harvest
        // branch is disjoint from it: on that platform the alias
        // holds no file function, so the call misses there.
        let disjoint_host = host_guards
            .iter()
            .any(|host| !overlaps(&files[0].1, &[*host]));
        if !disjoint_host {
            return AliasResolution::Canonical(file_func_key(files[0].0, base));
        }
        let mut all = HashSet::new();
        all.insert(files[0].0.to_string());
        return AliasResolution::Any {
            base: base.to_string(),
            files: all,
            has_host: true,
        };
    }
    let mut ambiguous = HashSet::new();
    for (i, (file, guards)) in files.iter().enumerate() {
        for (other, other_guards) in files.iter().skip(i + 1) {
            if overlaps(guards, other_guards)
                && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
            {
                ambiguous.insert((*file).to_string());
                ambiguous.insert((*other).to_string());
            }
        }
    }
    if !ambiguous.is_empty() {
        return AliasResolution::Ambiguous {
            alias: alias.to_string(),
            base: base.to_string(),
            files: ambiguous,
        };
    }
    let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
    if all.iter().any(|file| exists(&file_func_key(file, base))) {
        return AliasResolution::Any {
            base: base.to_string(),
            files: all,
            has_host: !host_guards.is_empty(),
        };
    }
    AliasResolution::Unknown
}

/// Missing-import hint for an unknown function (#319): when `base`
/// is `EXPORT`ed by already-loaded files, name them so the error
/// directs the author to the fix instead of dead-ending. `files`
/// pairs each loaded file's key with its exported func names (only
/// exported names suggest: privates would fail the `EXPORT` gate);
/// `unit_targets` is the failing unit's alias map for `did you mean
/// ALIAS::BASE` suggestions. Bare and `SCRIPT::` spellings search
/// the same way. Labels sort for determinism. Only unknown-function
/// errors append this; nothing else restates the exporter search.
pub(super) fn missing_import_hint<'a>(
    files: impl IntoIterator<Item = (&'a str, &'a [String])>,
    unit_targets: &AliasTargets,
    name: &str,
) -> Option<String> {
    let base = match split_qualified(name) {
        Some((_, base)) => base,
        None => name,
    };
    if base.is_empty() {
        return None;
    }
    let mut exporters: Vec<&str> = files
        .into_iter()
        .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
        .map(|(file, _)| file)
        .collect();
    exporters.sort();
    exporters.dedup();
    if exporters.is_empty() {
        return None;
    }
    // Aliases the failing unit already imports each exporter under.
    let imported_as = |file: &str| {
        let mut aliases: Vec<&str> = unit_targets
            .iter()
            .filter(|(_, targets)| targets.iter().any(|t| t.file.as_deref() == Some(file)))
            .map(|(alias, _)| alias.as_str())
            .collect();
        aliases.sort();
        aliases
    };
    if exporters.len() == 1 {
        let file = exporters[0];
        let aliases = imported_as(file);
        // Prefer a working spelling: when the file is imported under
        // several aliases, an alias spelling the failed call
        // differently resolves, so suggest it before falling back to
        // the self-view diagnostic.
        let import_alias = aliases
            .iter()
            .find(|alias| qualify(alias, base) != name)
            .or(aliases.first())
            .copied();
        let suggestion = match import_alias {
            Some(import_alias) => {
                let spelling = qualify(import_alias, base);
                if spelling == name {
                    // Disjoint-guard view: the file exports the name
                    // but this alias resolves it elsewhere here.
                    format!(
                        "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
                    )
                } else {
                    format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
                }
            }
            None => {
                // Forward slashes: a raw Windows path would emit
                // invalid escapes inside the quoted suggestion.
                let path = to_forward_slashes(file);
                format!(
                    "file \"{file}\" exports `{base}`: add `[{KEYWORD_FUNC} {base} {KEYWORD_FROM} \"{path}\"]` to an {KEYWORD_IMPORT}"
                )
            }
        };
        return Some(format!("; {suggestion}"));
    }
    let mut files = exporters.join("\", \"");
    files.insert(0, '"');
    files.push('"');
    Some(format!(
        "; files {files} export `{base}`: qualify the call with the importing alias"
    ))
}

/// Whether one `EXPORT CONST` entry serves reads of stored `name`
/// (the sigil-stripped binding key): the entry itself, or a
/// qualified `ALIAS::NAME` forward of the same base. Single owner
/// for the cover rule every qualified-`CONST` path matches on.
pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
    base_name(entry) == name
}

/// How a module holds a top-level binding, for broken-forward
/// diagnostics: a `CONST`, a never-exportable `LET`, or nothing.
pub(super) enum BindingPresence {
    Const,
    Let,
    Absent,
}

/// Missing-`CONST` hint from the queried alias's own files: an
/// unexported `CONST` or a private `LET` with the same base names the
/// real fault instead of a bare unknown-name miss. Single owner for
/// the hint every qualified-`CONST` miss renders, so static and
/// runtime agree word for word. Reads only `view.binding`, never a
/// twin-local store scan.
pub(super) fn missing_const_hint<S: ModuleGraphView>(
    view: &S,
    targets: &AliasTargets,
    alias: &str,
    name: &str,
) -> Option<String> {
    targets
        .get(alias)
        .map(|entries| {
            entries
                .iter()
                .filter_map(|t| t.file.as_ref())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default()
        .iter()
        .find_map(|file| match view.binding(file, name) {
            BindingPresence::Const => Some(format!(
                "module holds `{name}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${name}`"
            )),
            BindingPresence::Let => Some(format!(
                "`{name}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
            )),
            BindingPresence::Absent => None,
        })
}

/// Read-only view of the module graph one qualified-`CONST`
/// resolution needs. Implemented once for live runtime stores and
/// once for static closure tables, so the walk below runs
/// identically on both and the twins cannot drift: static
/// validation, eager closure checks, and serving all chase through
/// this one owner.
pub(super) trait ModuleGraphView {
    /// Raw `EXPORT CONST` entries (stored bare names and qualified forwards).
    fn const_exports(&self, file: &str) -> Option<&[String]>;
    /// Outbound alias targets for `file`'s own unit: the namespace
    /// each forward hop resolves in.
    fn alias_targets(&self, file: &str) -> AliasTargets;
    /// How `file` holds top-level `name`, for broken-link detail.
    fn binding(&self, file: &str, name: &str) -> BindingPresence;
}

/// One `ALIAS::NAME` read's holder files: the unit's alias targets
/// classified through the shared matcher, kept only when the file
/// covers the base. Single owner for the holder half of
/// qualified-`CONST` resolution; the chase half is
/// [`chase_const_forward`].
#[derive(Debug)]
pub(super) enum ConstHolders {
    /// Covering files, sorted, possibly empty (callers run their
    /// own missing-name hints then).
    Found(Vec<String>),
    /// The alias is unknown to this unit.
    NoAlias,
    /// Several overlapping files hold the base: fail loud.
    Ambiguous {
        alias: String,
        base: String,
        files: HashSet<String>,
    },
}

/// Suffix probe for the matcher's canonical keys (`file::base`):
/// the base is ours, so stripping it recovers the file exactly,
/// and only a covering file counts as a holder. Single owner for
/// the suffix shape, so call sites never restate the separator.
fn const_canonical_suffix(name: &str) -> String {
    format!("{MODULE_SEPARATOR}{name}")
}

/// Classify one qualified-`CONST` read to its holder files.
pub(super) fn const_holder_files<S: ModuleGraphView>(
    view: &S,
    unit_targets: &AliasTargets,
    alias: &str,
    name: &str,
) -> ConstHolders {
    let qualified = qualify(alias, name);
    let suffix = const_canonical_suffix(name);
    // Suffix probe for the matcher's canonical keys
    // (`file::base`): the base is ours, so stripping it recovers the
    // file exactly, and only a covering file counts as a holder.
    let exports = |canonical: &str| {
        canonical
            .strip_suffix(suffix.as_str())
            .and_then(|file| view.const_exports(file))
            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
    };
    let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
        AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
        AliasResolution::Ambiguous { alias, base, files } => {
            return ConstHolders::Ambiguous { alias, base, files };
        }
        AliasResolution::Canonical(canonical) => {
            let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
                return ConstHolders::NoAlias;
            };
            vec![file.to_string()]
        }
        AliasResolution::Any { mut files, .. } => {
            let mut files: Vec<String> = files.drain().collect();
            files.sort();
            files
        }
    };
    holders.retain(|file| {
        view.const_exports(file)
            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
    });
    ConstHolders::Found(holders)
}

/// Failure modes of [`chase_const_forward`], rendered by each caller
/// with its own position context (static line/col, runtime none,
/// eager file attribution). Wording lives here once, on [`std::fmt::Display`],
/// so diagnostics cannot drift between the twins. The walk
/// returns the keyed diagnostic directly ([`DiagnosticResult`]);
/// [`forward_failed`] is the single conversion from wording to
/// key, so no `anyhow` carrier sits between the walk and its
/// callers.
#[derive(Debug)]
pub(super) enum ForwardError {
    /// The holder file itself is gone from the view.
    Unknown { original: String },
    /// A forward hop lands where the base is missing.
    Broken {
        original: String,
        hop: String,
        detail: BrokenDetail,
    },
    /// One file forwards the same base from several aliases.
    Split { original: String, hops: Vec<String> },
    /// Hops revisit a spelling. Import cycles are rejected before
    /// resolution, so this is defense in depth.
    Cycle { chain: Vec<String> },
    /// One hop resolves to several overlapping files.
    HopAmbiguous {
        alias: String,
        base: String,
        files: HashSet<String>,
    },
}

/// Why a forward hop lands nowhere.
#[derive(Debug)]
pub(super) enum BrokenDetail {
    /// The terminal file holds the base as an unexported `CONST`.
    UnexportedConst,
    /// The terminal file holds the base as a `LET`.
    Let,
    /// Nothing there answers to the base.
    Absent,
}

impl std::fmt::Display for ForwardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ForwardError::Unknown { original } => write!(f, "unknown {KEYWORD_CONST} `{original}`"),
            ForwardError::Broken {
                original,
                hop,
                detail,
            } => {
                let base = base_name(hop);
                let detail = match detail {
                    BrokenDetail::UnexportedConst => format!(
                        "module holds `{base}` as {KEYWORD_CONST} but does not export it: add `{KEYWORD_EXPORT} {KEYWORD_CONST} ${base}`"
                    ),
                    BrokenDetail::Let => format!(
                        "`{base}` is a {KEYWORD_LET} binding and cannot be exported: only {KEYWORD_CONST} bindings cross the module boundary"
                    ),
                    BrokenDetail::Absent => {
                        let (forward, _) = split_qualified(hop).unwrap_or(("", base));
                        format!("no import alias `{forward}` exports `{base}`")
                    }
                };
                write!(
                    f,
                    "unknown {KEYWORD_CONST} `{original}`: re-export `{hop}` does not resolve: {detail}"
                )
            }
            ForwardError::Split { original, hops } => write!(
                f,
                "ambiguous {KEYWORD_CONST} `{original}`: re-exported from {}; export exactly one source",
                hops.join(" and ")
            ),
            ForwardError::Cycle { chain } => {
                write!(
                    f,
                    "{KEYWORD_CONST} re-export cycle detected: {}",
                    chain.join(" -> ")
                )
            }
            ForwardError::HopAmbiguous { alias, base, files } => {
                write!(f, "{}", const_ambiguous_message(alias, base, files))
            }
        }
    }
}

/// Single conversion from `ForwardError` wording to key: the walk
/// builds the `dsl.import.const_forward_failed` diagnostic at
/// each failure site, so callers receive [`DiagnosticResult`]
/// with no `anyhow` carrier in between.
fn forward_failed(err: ForwardError) -> Diagnostic {
    std_diag::import_const_forward_failed(&err.to_string())
}

/// Follow qualified `EXPORT CONST $ALIAS::NAME` forwards from `file`
/// to the files holding the stored bare binding, resolving each hop
/// in the exporting file's own unit. A local bare definition shadows
/// forwards; disjoint-guard branches each chase to their own
/// terminal, so all terminals return (callers apply their own
/// multi-holder policy). Each hop preserves the base name.
pub(super) fn chase_const_forward<S: ModuleGraphView>(
    view: &S,
    file: &str,
    name: &str,
    original: &str,
) -> DiagnosticResult<Vec<String>> {
    let mut terminals: Vec<String> = Vec::new();
    chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
    terminals.sort();
    terminals.dedup();
    Ok(terminals)
}

/// Neutral failure of the shared qualified-`CONST` walk. Holders stay
/// neutral so each side maps them with its own position context
/// (static line/col, runtime none); chase failures already carry
/// their keyed diagnostic. Single owner for the classify-then-chase
/// flow: static tag reads and runtime value reads both run this one
/// walk instead of restating it.
pub(super) enum ConstWalkError {
    /// The alias is unknown to the resolving unit.
    NoAlias,
    /// Several overlapping files hold the base.
    HolderAmbiguous {
        alias: String,
        base: String,
        files: HashSet<String>,
    },
    /// Forward chasing failed with its keyed diagnostic.
    Forward(Diagnostic),
}

/// Terminal and holder files of one `ALIAS::NAME` read through the
/// shared walk. Terminals are the defining files after forwarding;
/// holders are the alias-target files for ambiguity reports.
pub(super) struct ConstTerminals {
    pub holders: Vec<String>,
    pub terminals: Vec<String>,
}

/// Shared classify-then-chase flow for one qualified-`CONST` read:
/// holder classification through [`const_holder_files`], then
/// [`chase_const_forward`] per holder with terminals sorted and
/// deduped. Both the static tag read and the runtime value read run
/// this instead of restating the branches.
pub(super) fn const_terminal_files<S: ModuleGraphView>(
    view: &S,
    unit_targets: &AliasTargets,
    alias: &str,
    name: &str,
    qualified: &str,
) -> Result<ConstTerminals, ConstWalkError> {
    let holders = match const_holder_files(view, unit_targets, alias, name) {
        ConstHolders::Found(holders) => holders,
        ConstHolders::NoAlias => return Err(ConstWalkError::NoAlias),
        ConstHolders::Ambiguous { alias, base, files } => {
            return Err(ConstWalkError::HolderAmbiguous { alias, base, files });
        }
    };
    let mut terminals: Vec<String> = Vec::new();
    for file in &holders {
        match chase_const_forward(view, file, name, qualified) {
            Ok(mut found) => terminals.append(&mut found),
            Err(diag) => return Err(ConstWalkError::Forward(diag)),
        }
    }
    terminals.sort();
    terminals.dedup();
    Ok(ConstTerminals { holders, terminals })
}

/// Shared tag rule for platform branches: same tags read, differing
/// tags name the holder files for the caller's ambiguity diagnostic.
/// Single owner for the "branches must agree on shape" rule so no
/// reader degrades to `Any`.
pub(super) fn unified_const_tag(
    tags: Vec<TypeTag>,
    holders: Vec<String>,
) -> Result<TypeTag, HashSet<String>> {
    let Some(first) = tags.first().cloned() else {
        return Err(holders.into_iter().collect());
    };
    let first_render = render_structural(&first);
    if tags
        .iter()
        .all(|tag| render_structural(tag) == first_render)
    {
        Ok(first)
    } else {
        Err(holders.into_iter().collect())
    }
}

fn chase_from<S: ModuleGraphView>(
    view: &S,
    current: &str,
    name: &str,
    original: &str,
    chain: &mut Vec<String>,
    terminals: &mut Vec<String>,
) -> DiagnosticResult<()> {
    let suffix = const_canonical_suffix(name);
    let covering = |canonical: &str| {
        canonical
            .strip_suffix(suffix.as_str())
            .and_then(|file| view.const_exports(file))
            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
    };
    let mut current = current.to_string();
    loop {
        let Some(names) = view.const_exports(current.as_str()) else {
            return Err(forward_failed(ForwardError::Unknown {
                original: original.to_string(),
            }));
        };
        if names.iter().any(|entry| entry == name) {
            terminals.push(current);
            return Ok(());
        }
        let mut aliases: Vec<&str> = Vec::new();
        for entry in names {
            if let Some((alias, base)) = split_qualified(entry)
                && base == name
                && !aliases.contains(&alias)
            {
                aliases.push(alias);
            }
        }
        if aliases.is_empty() {
            if chain.is_empty() {
                return Err(forward_failed(ForwardError::Unknown {
                    original: original.to_string(),
                }));
            }
            let hop = chain.last().expect("chain never empty").clone();
            let detail = match view.binding(current.as_str(), name) {
                BindingPresence::Const => BrokenDetail::UnexportedConst,
                BindingPresence::Let => BrokenDetail::Let,
                BindingPresence::Absent => BrokenDetail::Absent,
            };
            return Err(forward_failed(ForwardError::Broken {
                original: original.to_string(),
                hop,
                detail,
            }));
        }
        if aliases.len() > 1 {
            let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
            hops.sort();
            return Err(forward_failed(ForwardError::Split {
                original: original.to_string(),
                hops,
            }));
        }
        let forward = aliases[0];
        let hop = qualify(forward, name);
        if chain.contains(&hop) {
            chain.push(hop);
            return Err(forward_failed(ForwardError::Cycle {
                chain: chain.clone(),
            }));
        }
        chain.push(hop.clone());
        let targets = view.alias_targets(current.as_str());
        match classify_alias_call(&targets, &hop, &covering) {
            AliasResolution::Global | AliasResolution::Unknown => {
                return Err(forward_failed(ForwardError::Broken {
                    original: original.to_string(),
                    hop,
                    detail: BrokenDetail::Absent,
                }));
            }
            AliasResolution::Ambiguous { alias, base, files } => {
                return Err(forward_failed(ForwardError::HopAmbiguous {
                    alias,
                    base,
                    files,
                }));
            }
            AliasResolution::Canonical(canonical) => {
                let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
                    return Err(forward_failed(ForwardError::Unknown {
                        original: original.to_string(),
                    }));
                };
                current = next.to_string();
            }
            AliasResolution::Any { mut files, .. } => {
                let mut covering: Vec<String> = files
                    .drain()
                    .filter(|file| {
                        view.const_exports(file).is_some_and(|names| {
                            names.iter().any(|entry| const_export_covers(entry, name))
                        })
                    })
                    .collect();
                covering.sort();
                match covering.len() {
                    0 => {
                        return Err(forward_failed(ForwardError::Broken {
                            original: original.to_string(),
                            hop,
                            detail: BrokenDetail::Absent,
                        }));
                    }
                    1 => {
                        current = covering.into_iter().next().expect("len checked");
                    }
                    _ => {
                        for branch in covering {
                            let mut branch_chain = chain.clone();
                            chase_from(
                                view,
                                branch.as_str(),
                                name,
                                original,
                                &mut branch_chain,
                                terminals,
                            )?;
                        }
                        return Ok(());
                    }
                }
            }
        }
    }
}
/// Whether a disjoint-alias template call names a script function,
/// owned here so every placeholder path agrees with `resolve_call`:
/// visible only when no host-harvest branch competes (`!has_host`)
/// and **every** candidate file defines `base` (universal, not
/// existential: a missing branch fails the `LET` path, so the
/// template must not suggest it). `exists` probes canonical
/// file-function keys for script definitions.
pub(super) fn disjoint_template_script_visible(
    base: &str,
    files: &HashSet<String>,
    has_host: bool,
    exists: &dyn Fn(&str) -> bool,
) -> bool {
    !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
}

/// Miss wording for a disjoint-alias placeholder call, shared by the
/// static gate, the lazy runtime path, and (via the script set) the
/// EXPAND snapshot. Script-visible branches read as script misses
/// (the `LET` path); otherwise the alias is known but holds no
/// callable function here. Always renders: `Any` only arises for a
/// known alias, so the generic unknown wording never applies.
pub(super) fn disjoint_alias_placeholder_miss(
    module: &str,
    name: &str,
    base: &str,
    files: &HashSet<String>,
    has_host: bool,
    is_script: &dyn Fn(&str) -> bool,
) -> String {
    let script = disjoint_template_script_visible(base, files, has_host, is_script);
    describe_placeholder_miss(module, name, script, false, !script)
        .expect("disjoint miss always renders")
}

/// Every local spelling of one defining file's function in a unit.
/// Inverted direction of [`classify_alias_call`]; shares its matcher.
/// `is_script` probes the caller's registry for script bodies, so
/// disjoint platform aliases covering every branch with a script
/// definition read as direct spellings (matching the static gate and
/// the lazy path through [`disjoint_alias_placeholder_miss`]).
pub(super) fn spellings_for_defining_file(
    unit_targets: &AliasTargets,
    defining: &str,
    base: &str,
    is_script: &dyn Fn(&str) -> bool,
) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
    let mut direct = Vec::new();
    let mut ambiguous = Vec::new();
    for (alias, files) in unit_targets {
        if !files.iter().any(|t| t.file.as_deref() == Some(defining)) {
            continue;
        }
        let spelling = qualify(alias, base);
        match classify_alias_call(unit_targets, &spelling, &|key| {
            key == file_func_key(defining, base)
        }) {
            AliasResolution::Canonical(_) => direct.push(spelling),
            AliasResolution::Ambiguous { files, .. } => {
                ambiguous.push((spelling, files));
            }
            AliasResolution::Any {
                base,
                files,
                has_host,
            } => {
                if disjoint_template_script_visible(&base, &files, has_host, is_script) {
                    direct.push(spelling);
                }
            }
            AliasResolution::Global | AliasResolution::Unknown => {}
        }
    }
    (direct, ambiguous)
}

impl FuncKind {
    pub fn label(&self) -> &'static str {
        match self {
            FuncKind::Script => "script",
            FuncKind::HostCtx | FuncKind::HostPure => "host",
        }
    }
}

/// One declared parameter of a registered function. `param_type` is `None`
/// for unconstrained `Value` parameters (the macro accepts any value).
/// `allowed` names the closed value set for constrained `STRING`
/// parameters, declared once via `#[values(...)]`: the generated
/// extractor enforces membership and the reference renders the set,
/// so the list cannot rot apart from the check. `docs` carries the
/// parameter's description (parsed from the `# Arguments` doc section
/// for macro functions, written inline for hand-built entries) and
/// renders into every reference surface. `options` declares the known
/// keys of a `MAP` options parameter: same single-source rule as
/// `allowed`, with per-key types, required flags, defaults, and docs.
/// `optional` marks a trailing `MAP` parameter callers may omit: the
/// runtime fills an empty MAP, and signatures render `= {}`. Only
/// trailing `MAP` params may be optional (run-start validation
/// rejects anything else), so omission always means "no options".
/// The macro never emits optional params: only hand-built entries
/// use them, and only for options MAPs.
#[derive(Debug, Clone)]
pub struct FuncParam {
    pub name: String,
    pub param_type: Option<TypeTag>,
    pub allowed: Option<&'static [&'static str]>,
    pub docs: &'static str,
    pub options: Option<&'static [ParamOption]>,
    pub optional: bool,
}

/// Required argument count: total params minus trailing optionals.
/// Callers may pass any count in `required..=total`; omitted trailing
/// MAPs fill with an empty MAP. Shared by the static arity gate and
/// the runtime gate so the two can never disagree.
pub fn required_arity(params: &[FuncParam]) -> usize {
    params
        .iter()
        .rev()
        .take_while(|param| param.optional)
        .fold(params.len(), |count, _| count - 1)
}

/// Fill omitted trailing optional MAP params with empty MAPs. The
/// caller guarantees `values.len()` is within
/// `required_arity(params)..=params.len()`; anything else is a bug,
/// not a user error, so over- and under-counts panic loudly.
pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
    assert!(
        values.len() <= params.len(),
        "arity gate must run before fill_optional_args"
    );
    assert!(
        values.len() >= required_arity(params),
        "arity gate must run before fill_optional_args"
    );
    while values.len() < params.len() {
        values.push(Value::map(BTreeMap::new()));
    }
    values
}

/// One known key of a `MAP` options parameter: name, value type,
/// whether callers must pass it, the rendered default for optional
/// keys, and what it controls. Declared once per options parameter
/// (macro `#[options(...)]` plus the `# Options` doc section, or
/// inline for hand-built entries) and rendered into signatures,
/// `DESCRIBE` output, and generated references alike.
#[derive(Debug, Clone)]
pub struct ParamOption {
    pub name: &'static str,
    pub value: TypeTag,
    pub required: bool,
    pub default: Option<&'static str>,
}

/// Introspectable metadata for one function. Single source for
/// `DESCRIBE(name)` output and the static function reference. `rpn` names
/// whether the function also runs on the compiled math path (`true` for
/// pure functions and opted-in stateful ones); everything runs on the AST
/// path.
#[derive(Debug, Clone)]
pub struct FuncMeta {
    pub name: String,
    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
    /// the host module name otherwise). `name` is always the qualified
    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
    pub module: String,
    pub kind: FuncKind,
    pub params: Option<Vec<FuncParam>>,
    pub returns: Option<TypeTag>,
    pub rpn: bool,
    pub summary: &'static str,
    pub docs: &'static str,
    /// Executable examples, rendered as ```oxdock fences into the
    /// generated reference and executed by docs_conformance like
    /// command examples. The single precondition mechanism: the
    /// returns gate executes these blocks to cover functions blind
    /// sampling cannot reach.
    pub examples: &'static [crate::Example],
}

/// Pure scalar function: no filesystem, no scope, no process access.
/// Usable from both AST evaluation and compiled RPN math.
pub type PureFn = Arc<dyn Fn(Vec<Value>) -> DiagnosticResult<Value> + Send + Sync>;

/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
pub type NativeFn<P> =
    Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> DiagnosticResult<Value> + Send + Sync>;

/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
/// registration marker. The engine calls `registration()` and never names
/// a generated symbol.
pub trait OxDockFn<P: ProcessManager> {
    /// The registry entry deriving from the Rust signature plus doc
    /// comments: name, metadata, and entry point, rendered.
    fn registration() -> HostRegistration<P>;
}

/// One host-registered function, grouped into a [`HostModule`] and passed
/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
/// generated registration marker, or by hand. `Pure` entries run
/// on both the AST and the compiled RPN math paths; `Stateful` entries run
/// on the AST path with full step context. `Both` entries carry a stateful
/// body plus a pure string projection: every context with step IO runs
/// the body, while `{{ }}` placeholder expansion (which has no step
/// context) runs the projection.
pub enum HostRegistration<P: ProcessManager> {
    Stateful {
        name: String,
        meta: FuncMeta,
        func: NativeFn<P>,
    },
    Pure {
        name: String,
        meta: FuncMeta,
        func: PureFn,
    },
    Both {
        name: String,
        meta: FuncMeta,
        func: NativeFn<P>,
        template: PureFn,
    },
}

// Manual `Clone` (a derive would demand `P: Clone`): entries share their
// function pointers through the `Arc`s and deep-copy the metadata.
impl<P: ProcessManager> Clone for HostRegistration<P> {
    fn clone(&self) -> Self {
        match self {
            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
            HostRegistration::Both {
                name,
                meta,
                func,
                template,
            } => HostRegistration::Both {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
                template: Arc::clone(template),
            },
        }
    }
}

impl<P: ProcessManager> HostRegistration<P> {
    /// Registry name this entry answers to. The lock test in `tests.rs`
    /// (`function_names_match_registry`) asserts every
    /// `function_names::FUNC_*` constant against this, so a rename of
    /// the Rust function (which moves the macro-derived name) fails
    /// loudly instead of leaving diagnostics text behind.
    pub fn name(&self) -> &str {
        match self {
            HostRegistration::Stateful { name, .. } => name,
            HostRegistration::Pure { name, .. } => name,
            HostRegistration::Both { name, .. } => name,
        }
    }

    /// Introspectable metadata for this entry, for documentation tooling
    /// that reads modules without registering them.
    pub fn meta(&self) -> &FuncMeta {
        match self {
            HostRegistration::Stateful { meta, .. } => meta,
            HostRegistration::Pure { meta, .. } => meta,
            HostRegistration::Both { meta, .. } => meta,
        }
    }
}

/// One user-defined function body (`FUNC NAME($p: TYPE, ...): RET { ... }`).
/// Param and return types resolve to tags at definition time, where the type
/// directory is in scope; the registry never holds raw type strings.
/// The flag marks trailing `?` params the caller may omit (filled with
/// [`optional_zero_value`] at call time).
#[derive(Debug, Clone)]
pub(super) struct FuncDefData {
    pub(super) params: Vec<(String, TypeTag, bool)>,
    pub(super) return_type: TypeTag,
    pub(super) return_spelling: String,
    pub(super) is_async: bool,
    pub(super) body: Vec<Step>,
    /// Owning file module (#115, resolved display path): module-owned
    /// `FUNC`s resolve names against the module's shared store after
    /// lexical frames miss. `None` for entry/REPL definitions, which
    /// stay params-only.
    pub(super) module: Option<String>,
    /// Definition-site jail (#322): the workspace selection and cwd
    /// as they stood when this `FUNC` was defined. `Some` for
    /// definitions executed at file top level (entry or module init);
    /// `None` for call-time materializations and bodies, which must
    /// never capture caller ambient (the file fallback applies).
    pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
}

/// Zero value for an omitted trailing optional script param, by
/// resolved tag. Scalars take falsy empties and collections empty
/// shapes (mirroring the host optional-`MAP` fill); records qualify
/// when every field is optional or defaulted (binding fills the
/// defaults). Handles, pipes, custom types, unions, and the
/// remaining words have no zero: omitting those fails at definition,
/// so the caller passes explicitly.
pub fn optional_zero_value(tag: &TypeTag) -> DiagnosticResult<Value> {
    match tag {
        TypeTag::Bool => Ok(Value::bool(false)),
        TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
        TypeTag::Int => Ok(Value::int(0)),
        TypeTag::Float => Ok(Value::float(0.0)),
        TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
        TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
        TypeTag::Record(fields)
            if fields
                .iter()
                .all(|field| field.optional || field.default.is_some()) =>
        {
            Ok(Value::map(BTreeMap::new()))
        }
        other => Err(std_diag::func_zero_value_missing(
            &oxdock_parser::render_structural(other),
        )),
    }
}

/// Resolve script `FUNC` param spellings to tags in one place: tag
/// resolution, declaration checks, and optional zero-value validation.
/// All definition paths (direct, static check, file import) funnel
/// here, so a required-after-optional or zero-less optional fails
/// identically everywhere instead of drifting by call site.
pub fn resolve_script_params<P: ProcessManager>(
    state: &ExecState<P>,
    func_name: &str,
    params: &[(String, String, bool)],
) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
    resolve_script_params_for_unit(
        state,
        &super::import::active_unit_key(state),
        func_name,
        params,
    )
}

/// Unit-scoped param resolution: `ptype` resolves in `unit`'s tables,
/// so unimported qualified param types fail per defining file.
/// Single owner for param loops: static and runtime funnel here with
/// explicit targets, so arity and zero-value gates cannot drift.
/// LSP calls this directly with effective targets for hover/completion.
/// ProcessManager-free query on a closure snapshot; `ExecState`
/// wrappers delegate here so logic lives once.
impl TypeSnapshot {
    pub fn resolve_script_params(
        &self,
        unit: &str,
        alias_targets: &AliasTargets,
        type_exports: &HashMap<String, Vec<String>>,
        func_name: &str,
        params: &[(String, String, bool)],
    ) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
        let mut resolved = Vec::with_capacity(params.len());
        for (pname, ptype, optional) in params {
            let clean = strip_sigil(pname).to_string();
            let tag = self
                .resolve_tag_with_targets(unit, alias_targets, type_exports, ptype)
                .map_err(|err| std_diag::func_param_type(func_name, err))?;
            self.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
            if *optional {
                optional_zero_value(&tag)
                    .map(|_| ())
                    .map_err(|err| std_diag::func_optional_param(func_name, &clean, err))?;
            }
            resolved.push((clean, tag, *optional));
        }
        Ok(resolved)
    }
}

pub fn resolve_script_params_with_targets<P: ProcessManager>(
    state: &ExecState<P>,
    unit: &str,
    alias_targets: &AliasTargets,
    type_exports: &HashMap<String, Vec<String>>,
    func_name: &str,
    params: &[(String, String, bool)],
) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
    state
        .type_env
        .resolve_script_params(unit, alias_targets, type_exports, func_name, params)
}

/// Unit-scoped param resolution: `ptype` resolves in `unit`'s tables,
/// so unimported qualified param types fail per defining file.
pub fn resolve_script_params_for_unit<P: ProcessManager>(
    state: &ExecState<P>,
    unit: &str,
    func_name: &str,
    params: &[(String, String, bool)],
) -> DiagnosticResult<Vec<(String, TypeTag, bool)>> {
    let alias_targets = super::import::unit_alias_targets(state, unit);
    let type_exports = ExecState::<P>::module_type_exports(state);
    resolve_script_params_with_targets(
        state,
        unit,
        &alias_targets,
        &type_exports,
        func_name,
        params,
    )
}

/// Validate already-resolved script param tags: the zero-value gate
/// for registry insertion paths that never see spellings.
pub fn check_script_param_tags(
    func_name: &str,
    params: &[(String, TypeTag, bool)],
) -> DiagnosticResult<()> {
    for (pname, tag, optional) in params {
        if *optional {
            optional_zero_value(tag)
                .map(|_| ())
                .map_err(|err| std_diag::func_optional_param(func_name, pname, err))?;
        }
    }
    Ok(())
}

/// Executable body behind one registry entry: an interpreted script, a
/// pure scalar function, a stateful function with step context, or a
/// dual entry whose pure arm serves `{{ }}` placeholders while the ctx
/// arm serves every context that carries step IO.
pub(super) enum FuncBody<P: ProcessManager> {
    Script(FuncDefData),
    Pure(PureFn),
    Ctx(NativeFn<P>),
    Both { pure: PureFn, ctx: NativeFn<P> },
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncBody<P> {
    fn clone(&self) -> Self {
        match self {
            FuncBody::Script(def) => FuncBody::Script(def.clone()),
            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
            FuncBody::Both { pure, ctx } => FuncBody::Both {
                pure: Arc::clone(pure),
                ctx: Arc::clone(ctx),
            },
        }
    }
}

/// One entry in the unified function registry: introspectable metadata
/// (mandatory for every entry, backing the pre-evaluation arity gate)
/// plus the executable body.
pub(super) struct FuncEntry<P: ProcessManager> {
    pub(super) meta: FuncMeta,
    pub(super) body: FuncBody<P>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncEntry<P> {
    fn clone(&self) -> Self {
        Self {
            meta: self.meta.clone(),
            body: self.body.clone(),
        }
    }
}

/// Names defined in one lexical scope frame: `defined` rejects duplicates
/// in the same scope, `shadowed` restores outer definitions on exit.
struct ScopeFrame<P: ProcessManager> {
    defined: HashSet<String>,
    shadowed: Vec<(String, FuncEntry<P>)>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for ScopeFrame<P> {
    fn clone(&self) -> Self {
        Self {
            defined: self.defined.clone(),
            shadowed: self.shadowed.clone(),
        }
    }
}

/// The single function registry: DSL `FUNC` definitions, builtins, and
/// host extensions share one lookup table, one metadata path, and one
/// dispatch order. Script entries scope lexically (defined names revert on
/// scope exit, shadowing an outer definition restores it); native entries
/// persist for the run. Shared across `fork()` via clone; the entry maps
/// clone while scope frames stay per state.
/// Module to function-name table of pure entries, shared by reference.
/// Nested so placeholder dispatch looks up `table[module][func]` with
/// zero allocation; rebuilt only when native entries register.
pub type PureTable = HashMap<String, HashMap<String, PureFn>>;

/// Shared `{{ MODULE::FUNC(args) }}` dispatch over a pure-function table.
///
/// Single implementation for every expansion path (script `EXPAND`,
/// string interpolation, host-driven fragment expansion): nested
/// module then function lookup with zero allocation, unknown names
/// failing with the sorted known-functions listing. Callers keep
/// their own arg resolution and output handling; only dispatch and
/// its error shape live here.
pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
    Arc::new(move |module, func, args| {
        let callee = table
            .get(module)
            .and_then(|entries| entries.get(func))
            .ok_or_else(|| {
                let mut known: Vec<String> = table
                    .iter()
                    .flat_map(|(m, entries)| {
                        entries
                            .keys()
                            .map(move |f| format!("{m}{MODULE_SEPARATOR}{f}"))
                    })
                    .collect();
                known.sort();
                std_diag::func_placeholder_unknown(module, func, &known)
            })?;
        callee(args)
    })
}

/// Descriptive `{{ MODULE::FUNC }}` miss wording, shared by the static
/// gate and the runtime fallbacks: known callees are never called
/// "unknown". Returns `None` when the callee is genuinely unknown
/// everywhere (callers keep the unknown-function diagnostic with its
/// known-functions listing). `{{ }}` runs without step context, so
/// the fix always routes through a prior `LET` binding.
pub(super) fn describe_placeholder_miss(
    module: &str,
    name: &str,
    is_script: bool,
    is_stateful: bool,
    alias_known: bool,
) -> Option<String> {
    let qualified = qualify(module, name);
    if is_script {
        let call = if module == SCRIPT_MODULE_NAME {
            format!("{name}(...)")
        } else {
            format!("{qualified}(...)")
        };
        return Some(format!(
            "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with {KEYWORD_LET} $v = {call} then interpolate {{{{ $v }}}}"
        ));
    }
    if is_stateful {
        return Some(format!(
            "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
        ));
    }
    if alias_known {
        return Some(format!(
            "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's {KEYWORD_EXPORT} list and the {KEYWORD_IMPORT} harvest, or bind a known function first with {KEYWORD_LET} then interpolate {{{{ $v }}}}"
        ));
    }
    None
}

/// Owned placeholder classes for `'static` closures (notably
/// `EXPAND` streaming), which cannot borrow the registry.
pub(super) struct PlaceholderClasses {
    pub script: HashSet<String>,
    pub stateful: HashSet<String>,
    pub aliases: HashSet<String>,
    /// Ambiguous spellings: alias resolves to several files.
    pub ambiguous: HashMap<String, HashSet<String>>,
}

impl PlaceholderClasses {
    pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
        let qualified = qualify(module, name);
        if let Some(files) = self.ambiguous.get(&qualified) {
            return Some(ambiguous_alias_message(module, name, files));
        }
        describe_placeholder_miss(
            module,
            name,
            self.script.contains(&qualified),
            self.stateful.contains(&qualified),
            self.aliases.contains(module),
        )
    }
}

pub struct FunctionRegistry<P: ProcessManager> {
    entries: HashMap<String, FuncEntry<P>>,
    scopes: Vec<ScopeFrame<P>>,
    pure_shared: Arc<PureTable>,
    /// Script `#` doc comments keyed by qualified `SCRIPT::NAME`.
    /// Populated by the MCP host after linear execution; the tool
    /// table reads these with fallback to `FuncMeta` summary.
    script_docs: HashMap<String, (String, String)>,
}

impl<P: ProcessManager> FunctionRegistry<P> {
    pub(super) fn with_builtins() -> Self {
        let mut reg = Self {
            entries: HashMap::new(),
            pure_shared: Arc::new(HashMap::new()),
            script_docs: HashMap::new(),
            scopes: vec![ScopeFrame {
                defined: HashSet::new(),
                shadowed: Vec::new(),
            }],
        };
        // Every builtin registers through the same `HostRegistration`
        // entries hosts use: no separate authoring path for engine natives.
        // Builtins land in the `STD` module, exactly like a host module.
        for host in Self::builtin_registrations() {
            match host {
                HostRegistration::Stateful { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
                }
                HostRegistration::Pure { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
                }
                HostRegistration::Both {
                    name,
                    meta,
                    func,
                    template,
                } => {
                    reg.insert_qualified(
                        STD_MODULE_NAME,
                        name,
                        meta,
                        FuncBody::Both {
                            pure: template,
                            ctx: func,
                        },
                    );
                }
            }
        }
        reg
    }

    /// All builtins as host-style registrations, built from the same
    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
    /// consumes this list, so builtins and hosts share one registration
    /// pathway instead of two authoring models.
    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
        vec![
            Int::registration(),
            Float::registration(),
            BoolConvert::registration(),
            BoolOr::registration(),
            FormatByteCount::registration(),
            ParseByteCount::registration(),
            FormatDuration::registration(),
            ParseDuration::registration(),
            Types::registration(),
            TypeDescribe::registration(),
            Glob::registration(),
            LoadToml::registration(),
            LoadJson::registration(),
            HashSha256::registration(),
            Cwd::registration(),
            ParseToml::registration(),
            ParseJson::registration(),
            PathType::registration(),
            PathWritable::registration(),
            IsExec::registration(),
            IsFile::registration(),
            IsDir::registration(),
            Exists::registration(),
            HasKey::registration(),
            Get::registration(),
            MapSet::registration(),
            MergeMaps::registration(),
            Base64Encode::registration(),
            Base64Decode::registration(),
            Rand::registration(),
            ToJson::registration(),
            TypeOf::registration(),
            Functions::registration(),
            Describe::registration(),
            IsMain::registration(),
            IsTerminal::registration(),
            Eof::registration(),
            TaskPoll::registration(),
            Version::registration(),
            Interpreter::registration(),
            Argv::registration(),
            ParseArgs::registration(),
            ParseFlags::registration(),
            ParsePositionals::registration(),
            TextTrim::registration(),
            TextTrimPrefix::registration(),
            TextTrimSuffix::registration(),
            PathJoin::registration(),
            PathBase::registration(),
            PathRel::registration(),
            TextToUpper::registration(),
            TextToLower::registration(),
            TextReplace::registration(),
            TextReplaceRegex::registration(),
            TextSplit::registration(),
            TextJoin::registration(),
            TextLines::registration(),
            TextFields::registration(),
            TextMatch::registration(),
            TextExtract::registration(),
            TextStartsWith::registration(),
            TextEndsWith::registration(),
            Contains::registration(),
            Unique::registration(),
            Len::registration(),
            TextCount::registration(),
            TextCountMatches::registration(),
            TextGrep::registration(),
            TextLinesRange::registration(),
            SemaphoreNew::registration(),
            SemaphoreTryAcquire::registration(),
            SemaphoreAvailable::registration(),
            ShellSplitArgs::registration(),
            ShellJoinArgs::registration(),
        ]
    }

    /// Every name the registry answers to. Backs parse-time shadow
    /// validation through `builtin_function_names`.
    pub(super) fn keys(&self) -> HashSet<String> {
        self.entries.keys().cloned().collect()
    }

    /// Single lookup for every callable: script, pure, or stateful.
    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
        self.entries.get(name).cloned()
    }

    /// Number of live function scope frames. Callers record this as
    /// their frame floor so nested lookup stays within the current
    /// call (or init), never reaching caller frames.
    pub(super) fn scope_depth(&self) -> usize {
        self.scopes.len()
    }

    /// Frame-2..N lookup (#322): innermost scope frame at or above
    /// `floor` defining `SCRIPT::BASE`, innermost first. The live
    /// slot always holds the innermost defining frame's value
    /// (save/restore discipline), so a hit here is definitionally
    /// lexical: nested defs shadow everything below them with no
    /// owner tags consulted. Cross-unit exclusion comes from the
    /// caller choosing `floor` (call/init boundary), never from
    /// inspecting whose definition was found.
    pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
        let qualified = qualify(SCRIPT_MODULE_NAME, base);
        let len = self.scopes.len();
        let start = floor.min(len);
        for frame in self.scopes[start..].iter().rev() {
            if frame.defined.contains(&qualified) {
                return self.entries.get(&qualified).cloned();
            }
        }
        None
    }

    /// Single lazy miss classifier for runtime placeholder paths with
    /// registry access: one borrow, no `FuncEntry` clones, invoked only
    /// on resolver failure. Classification runs first (matching
    /// `exported_metas`); the shared body helper below owns the
    /// `Script`/`Ctx` wording, so the match appears once.
    pub(super) fn describe_unit_placeholder_miss(
        &self,
        unit_targets: &AliasTargets,
        module: &str,
        name: &str,
    ) -> Option<String> {
        let qualified = qualify(module, name);
        // File-aliased spellings classify through the shared matcher.
        // A canonical miss means the alias is known but holds no such
        // function; disjoint aliases share the static owner's verdict
        // (script-visible branches read as script misses).
        match classify_alias_call(unit_targets, &qualified, &|key| {
            self.entries.contains_key(key)
        }) {
            AliasResolution::Canonical(canonical) => {
                if let Some(entry) = self.entries.get(&canonical) {
                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
                        return Some(miss);
                    }
                    None
                } else {
                    describe_placeholder_miss(module, name, false, false, true)
                }
            }
            AliasResolution::Global => {
                if let Some(entry) = self.entries.get(&qualified) {
                    // `SCRIPT` and host spellings resolve globally;
                    // canonical file keys never match a call-site
                    // spelling.
                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
                        return Some(miss);
                    }
                }
                None
            }
            AliasResolution::Ambiguous { files, .. } => {
                Some(ambiguous_alias_message(module, name, &files))
            }
            AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
            // Disjoint aliases share the static owner's verdict through
            // the single miss helper, so lazy inline expansion agrees
            // with the static gate word for word (script-visible
            // branches read as script misses, the rest as known-alias
            // misses, never the generic unknown wording).
            AliasResolution::Any {
                base,
                files,
                has_host,
            } => Some(disjoint_alias_placeholder_miss(
                module,
                name,
                &base,
                &files,
                has_host,
                &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
            )),
        }
    }

    /// Single owner for the `FuncBody` miss wording: script and
    /// stateful bodies report their kind, template-capable bodies
    /// (`Pure`/`Both`) report no miss.
    fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
        match body {
            FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
            FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
            FuncBody::Pure(_) | FuncBody::Both { .. } => None,
        }
    }

    /// Owned snapshot for `'static` placeholder closures (notably
    /// `EXPAND` streaming): the resolver closure cannot borrow the
    /// registry, so these name sets are the minimal owned form.
    pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
        let mut script = HashSet::new();
        let mut stateful = HashSet::new();
        let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
        for (key, entry) in self.entries.iter() {
            let Some((module, base)) = split_qualified(key) else {
                continue;
            };
            match &entry.body {
                FuncBody::Script(def) => {
                    if module == SCRIPT_MODULE_NAME {
                        // `SCRIPT` and bare-harvest spellings stay global.
                        script.insert(key.clone());
                        continue;
                    }
                    // Canonical file key: every local spelling in this
                    // unit, singletons (plus disjoint platform branches
                    // covered everywhere by script definitions) into
                    // the script set and several files into the
                    // ambiguity map, through the shared matcher so
                    // `describe` matches call sites exactly like the
                    // static gate and lazy path.
                    let defining = def.module.as_deref().unwrap_or(module);
                    let (direct, ambiguous_here) = spellings_for_defining_file(
                        unit_targets,
                        defining,
                        base,
                        &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
                    );
                    script.extend(direct);
                    for (spelling, files) in ambiguous_here {
                        ambiguous.entry(spelling).or_default().extend(files);
                    }
                }
                FuncBody::Ctx(_) => {
                    stateful.insert(key.clone());
                }
                FuncBody::Pure(_) | FuncBody::Both { .. } => {}
            }
        }
        let aliases = unit_targets.keys().cloned().collect();
        PlaceholderClasses {
            script,
            stateful,
            aliases,
            ambiguous,
        }
    }

    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
        self.entries.insert(name, FuncEntry { meta, body });
        self.rebuild_pure_shared();
    }

    /// Rebuild the shared pure table. Runs only on native insertion:
    /// script definitions insert `Script` bodies directly and never
    /// affect the pure set, so this stays correct between rebuilds.
    /// Dual entries contribute their template arm, which is what
    /// `{{ }}` placeholder expansion resolves.
    fn rebuild_pure_shared(&mut self) {
        let mut table: PureTable = HashMap::new();
        for (name, entry) in &self.entries {
            let func = match &entry.body {
                FuncBody::Pure(func) => func,
                FuncBody::Both { pure, .. } => pure,
                FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
            };
            if let Some((module, base)) = split_qualified(name) {
                table
                    .entry(module.to_string())
                    .or_default()
                    .insert(base.to_string(), Arc::clone(func));
            }
        }
        self.pure_shared = Arc::new(table);
    }

    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
    /// The single choke point for every registry entry: builtins pass
    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
    fn insert_qualified(
        &mut self,
        module: &str,
        base: String,
        mut meta: FuncMeta,
        body: FuncBody<P>,
    ) {
        meta.name = qualify(module, &base);
        meta.module = module.to_string();
        // Last-write-wins would silently reroute calls, so a repeated
        // qualified name is a programmer error, never a shadow: panic like
        // conflicting type registrations do. `SCRIPT` definitions bypass
        // this path (`define_script` owns their scoped shadowing).
        if self.entries.contains_key(&meta.name) {
            panic!("duplicate function registration `{}`", meta.name);
        }
        self.insert_native(meta.name.clone(), meta, body);
    }

    pub(super) fn register_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: NativeFn<P>,
    ) {
        meta.kind = FuncKind::HostCtx;
        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
    }

    pub(super) fn register_pure_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: PureFn,
    ) {
        meta.kind = FuncKind::HostPure;
        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
    }

    pub(super) fn register_both_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: NativeFn<P>,
        template: PureFn,
    ) {
        meta.kind = FuncKind::HostCtx;
        self.insert_qualified(
            module,
            name,
            meta,
            FuncBody::Both {
                pure: template,
                ctx: func,
            },
        );
    }

    /// Define a DSL `FUNC`: names colliding with any known base name cannot
    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
    /// of an outer script definition restores on scope exit. Stored as
    /// `SCRIPT::NAME`, exactly like every other qualified entry.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn define_script(
        &mut self,
        name: &str,
        params: &[(String, TypeTag, bool)],
        return_type: TypeTag,
        return_spelling: &str,
        is_async: bool,
        body: &[Step],
        module: Option<&str>,
        def_jail: Option<(WorkspaceSelection, GuardedPath)>,
    ) -> DiagnosticResult<()> {
        let qualified = qualify(SCRIPT_MODULE_NAME, name);
        let shadowable = matches!(
            self.entries.get(&qualified).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        );
        // Reserved spans every module: compare base names so the message
        // keeps naming the bare script identifier. Script-defined entries
        // (including `ALIAS::NAME` file imports, #115) never reserve: only
        // native/host bodies are unshadowable.
        let reserved = self.entries.iter().any(|(key, entry)| {
            split_qualified(key).is_some_and(|(_, base)| base == name)
                && !matches!(entry.body, FuncBody::Script(_))
        });
        if reserved && !shadowable {
            return Err(std_diag::func_shadow_reserved(name));
        }
        if self
            .scopes
            .last()
            .is_some_and(|frame| frame.defined.contains(&qualified))
        {
            return Err(std_diag::func_duplicate_in_scope(name));
        }
        check_script_param_tags(name, params)?;
        let old = self.entries.insert(
            qualified.clone(),
            FuncEntry {
                meta: FuncMeta {
                    name: qualified.clone(),
                    module: SCRIPT_MODULE_NAME.to_string(),
                    kind: FuncKind::Script,
                    params: Some(
                        params
                            .iter()
                            .map(|(pname, param_type, optional)| {
                                Ok(FuncParam {
                                    name: pname.clone(),
                                    param_type: Some(param_type.clone()),
                                    allowed: None,
                                    // Script `FUNC` params carry no prose:
                                    // declarations have no doc syntax.
                                    docs: "",
                                    options: None,
                                    optional: *optional,
                                })
                            })
                            .collect::<DiagnosticResult<_>>()?,
                    ),
                    returns: Some(return_type.clone()),
                    rpn: false,
                    summary: "DSL-defined function.",
                    docs: "Defined via FUNC in script.",
                    examples: &[],
                },
                body: FuncBody::Script(FuncDefData {
                    params: params.to_vec(),
                    return_type,
                    return_spelling: return_spelling.to_string(),
                    is_async,
                    body: body.to_vec(),
                    module: module.map(|m| m.to_string()),
                    def_jail,
                }),
            },
        );
        if let Some(frame) = self.scopes.last_mut() {
            frame.defined.insert(qualified.clone());
            if let Some(old) = old {
                frame.shadowed.push((qualified, old));
            }
        }
        Ok(())
    }

    /// Define a file-imported DSL `FUNC` under its canonical key
    /// ([`file_func_key`]: defining file plus base name, never the
    /// importer alias) in the global registry frame (index 0, never
    /// popped): eviction on scope exit would strand the module cache
    /// and alias targets that still reference it.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn define_file_func(
        &mut self,
        name: &str,
        params: &[(String, TypeTag, bool)],
        return_type: TypeTag,
        return_spelling: &str,
        is_async: bool,
        body: &[Step],
        defining: &str,
    ) -> DiagnosticResult<()> {
        // The importer alias selects the defining file at dispatch;
        // the key itself names the defining file so units never share
        // entries.
        let qualified = file_func_key(defining, name);
        let shadowable = matches!(
            self.entries.get(&qualified).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        );
        // Reserved spans every module: compare base names so the message
        // keeps naming the bare script identifier. Script-defined entries
        // never reserve: only native/host bodies are unshadowable.
        let reserved = self.entries.iter().any(|(key, entry)| {
            split_qualified(key).is_some_and(|(_, base)| base == name)
                && !matches!(entry.body, FuncBody::Script(_))
        });
        if reserved && !shadowable {
            return Err(std_diag::func_shadow_reserved(name));
        }
        // File entries live in the global frame (index 0, never
        // popped): eviction on scope exit would strand the module
        // cache and alias targets that still reference them.
        let frame_idx = 0;
        if self
            .scopes
            .get(frame_idx)
            .is_some_and(|frame| frame.defined.contains(&qualified))
        {
            return Err(std_diag::func_duplicate_in_scope(name));
        }
        check_script_param_tags(name, params)?;
        let old = self.entries.insert(
            qualified.clone(),
            FuncEntry {
                meta: FuncMeta {
                    name: qualified.clone(),
                    module: defining.to_string(),
                    kind: FuncKind::Script,
                    params: Some(
                        params
                            .iter()
                            .map(|(pname, param_type, optional)| {
                                Ok(FuncParam {
                                    name: pname.clone(),
                                    param_type: Some(param_type.clone()),
                                    allowed: None,
                                    docs: "",
                                    options: None,
                                    optional: *optional,
                                })
                            })
                            .collect::<DiagnosticResult<_>>()?,
                    ),
                    returns: Some(return_type.clone()),
                    rpn: false,
                    summary: "DSL-defined function.",
                    docs: "Defined via FUNC in an imported script.",
                    examples: &[],
                },
                body: FuncBody::Script(FuncDefData {
                    params: params.to_vec(),
                    return_type,
                    return_spelling: return_spelling.to_string(),
                    is_async,
                    body: body.to_vec(),
                    module: Some(defining.to_string()),
                    // Harvest registration never captures a jail: it
                    // runs in the importer context, so capturing here
                    // would leak caller ambient into the defining
                    // file. The file fallback applies at call time.
                    def_jail: None,
                }),
            },
        );
        if let Some(frame) = self.scopes.get_mut(frame_idx) {
            frame.defined.insert(qualified.clone());
            if let Some(old) = old {
                frame.shadowed.push((qualified, old));
            }
        }
        Ok(())
    }

    /// Backfill a definition-site jail onto an import-registered
    /// canonical entry (#322). Imports register canonical slots
    /// before init runs, so they start jail-less; the first
    /// top-level definition seals them exactly once, mirroring the
    /// file frame. Later definitions never overwrite. Harvest-only
    /// registrations stay `None`: without init there is no
    /// definition site to seal.
    pub(super) fn seal_canonical_jail(
        &mut self,
        canonical: &str,
        jail: (WorkspaceSelection, GuardedPath),
    ) {
        if let Some(entry) = self.entries.get_mut(canonical)
            && let FuncBody::Script(def) = &mut entry.body
            && def.def_jail.is_none()
        {
            def.def_jail = Some(jail);
        }
    }

    /// Open a lexical scope frame for script definitions. Native entries
    /// persist; only script names track here.
    pub(super) fn push_scope(&mut self) {
        self.scopes.push(ScopeFrame {
            defined: HashSet::new(),
            shadowed: Vec::new(),
        });
    }

    /// Close a lexical scope frame: names defined inside revert, and any
    /// outer definition they shadowed is restored.
    pub(super) fn pop_scope(&mut self) {
        let Some(frame) = self.scopes.pop() else {
            return;
        };
        for name in frame.defined {
            self.entries.remove(&name);
        }
        for (name, old) in frame.shadowed {
            self.entries.insert(name, old);
        }
    }

    /// Registry lookup key for a runtime call-site spelling, through
    /// the shared alias-target matcher.
    pub(super) fn resolve_file_call_key(
        &self,
        unit_targets: &AliasTargets,
        name: &str,
    ) -> DiagnosticResult<Option<String>> {
        match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
            AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
                Ok(None)
            }
            AliasResolution::Canonical(key) => Ok(Some(key)),
            AliasResolution::Ambiguous { alias, base, files } => {
                Err(std_diag::func_ambiguous_alias(&alias, &base, &files))
            }
        }
    }

    /// Shared snapshot of every pure entry, nested by module and base
    /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
    /// borrows this per expansion with no map copies.
    pub(super) fn pure_shared(&self) -> Arc<PureTable> {
        Arc::clone(&self.pure_shared)
    }

    /// Every entry's metadata, scripts included, sorted by name. Backs
    /// run-start type tag validation.
    pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
        self.entries_metas()
    }

    fn meta(&self, name: &str) -> Option<FuncMeta> {
        self.entries.get(name).map(|entry| entry.meta.clone())
    }

    fn native_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = Vec::new();
        for entry in self.entries.values() {
            if !matches!(entry.body, FuncBody::Script(_)) {
                out.push(entry.meta.clone());
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Metadata for template-capable entries only: `Pure` plus `Both`
    /// (dual entries contribute their template arm to `{{ }}`).
    /// `Ctx` and `Script` never resolve in placeholder expansion, so
    /// the static template gate reads this instead of `all_metas`.
    pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = Vec::new();
        for entry in self.entries.values() {
            if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
                out.push(entry.meta.clone());
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Every entry's metadata, scripts included, sorted by name. Backs
    /// runtime `FUNCTIONS()` listings.
    fn entries_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self
            .entries
            .values()
            .map(|entry| entry.meta.clone())
            .collect();
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Install script `#` docs keyed by bare base name. Stored under
    /// qualified `SCRIPT::NAME` keys.
    pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
        for (base, pair) in docs {
            self.script_docs
                .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
        }
    }

    /// Script doc pair for a qualified name, if the parser collected one.
    pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
        self.script_docs.get(qualified).cloned()
    }

    /// Metadata for single-file `EXPORT` names in source order. Errors
    /// name the first missing export; callers fail fast before serving.
    /// Qualified names resolve through `resolve_file_call_key`, so
    /// re-exported file functions serve under the export spelling.
    pub fn exported_metas(
        &self,
        func_exports: &[String],
        unit_targets: &AliasTargets,
    ) -> DiagnosticResult<Vec<FuncMeta>> {
        let mut out = Vec::with_capacity(func_exports.len());
        for name in func_exports {
            // Bare names are script FUNCs; qualified names resolve
            // through the unit's alias targets first, falling back to
            // the global spelling for hosts and entry-owned scripts.
            let qualified = match split_qualified(name) {
                None => qualify(SCRIPT_MODULE_NAME, name),
                Some(_) => name.clone(),
            };
            let lookup = self
                .resolve_file_call_key(unit_targets, &qualified)?
                .unwrap_or_else(|| qualified.clone());
            if let Some(entry) = self.entries.get(&lookup) {
                let mut meta = entry.meta.clone();
                if lookup != qualified {
                    meta.name = name.clone();
                }
                out.push(meta);
                continue;
            }
            return Err(std_diag::func_export_unknown(name));
        }
        Ok(out)
    }
}

impl<P: ProcessManager> Clone for FunctionRegistry<P> {
    fn clone(&self) -> Self {
        Self {
            entries: self.entries.clone(),
            scopes: self.scopes.clone(),
            pure_shared: Arc::clone(&self.pure_shared),
            script_docs: self.script_docs.clone(),
        }
    }
}

/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
/// node, not a registry entry). Read straight off a stock registry, so the
/// `#[oxdock_func]` annotations stay the single source of truth: adding a
/// builtin extends this set with no parallel list to update. Seeds
/// parse-time shadow validation, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn builtin_function_names() -> HashSet<String> {
    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
    names.insert(KEYWORD_INSPECT.to_string());
    names
}

/// Metadata of every builtin function, sorted by name, for static
/// rendering (oxdock-render). Same single source as `builtin_function_names`:
/// the `#[oxdock_func]` annotations, never a parallel list.
pub fn builtin_function_metas() -> Vec<FuncMeta> {
    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
}

/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
/// the single source of truth for builtin membership and RPN eligibility.
/// Seeds parse-time module resolution, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn std_module_table() -> oxdock_parser::ModuleTable {
    // Registry names are qualified (`STD::GLOB`); the table holds bases.
    let func_names: HashSet<String> = builtin_function_metas()
        .into_iter()
        .map(|meta| base_name(&meta.name).to_string())
        .collect();
    oxdock_parser::ModuleTable {
        modules: HashMap::from([(
            STD_MODULE_NAME.to_string(),
            Some(oxdock_parser::ModuleFuncs { func_names }),
        )]),
    }
}

// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
// model as host-registered functions: metadata, arity checks, and argument
// unpacking derive from the signature plus doc comments, so adding a native
// means writing one small typed function plus one line each in
// `builtin_registrations` (consumed by `with_builtins`) and the
// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.

/// Convert a value to INT.
///
/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
/// when integral and finite; Bool as 1/0.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "convert",
    code = r###"
    IMPORT [STD]
    LET $n: INT = INT("42")
    ASSERT_EQ $n 42
    LET $flag: INT = INT(true)
    ASSERT_EQ $flag 1
    "###
)]
fn int(
    /// Value to convert to `INT`.
    #[union(Int, Float, String, Bool)]
    val: Value,
) -> DiagnosticResult<Value> {
    super::args::int_from_value(val)
}

/// Convert a value to FLOAT.
///
/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
///
#[oxdock_func(pure, returns = TypeTag::Float)]
#[example(
    name = "convert",
    code = r###"
    IMPORT [STD]
    LET $f: FLOAT = FLOAT("1.5")
    ASSERT_EQ $f 1.5
    LET $whole: FLOAT = FLOAT(2)
    ASSERT_EQ $whole 2.0
    "###
)]
fn float(
    /// Value to convert to `FLOAT`.
    #[union(Float, Int, String)]
    val: Value,
) -> DiagnosticResult<Value> {
    super::args::float_from_value(val)
}

/// Format a byte count canonically (`500B`, `10KB`, `2MB`, `1GB`,
/// binary `10KIB` and friends): the inverse of `PARSE_BYTE_COUNT`, so
/// formatted values reparse exactly. Negative inputs fail.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "format and round-trip",
    code = r###"
    # Byte counts render in the largest exact unit.
    IMPORT [STD]
    LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
    ASSERT_EQ $pretty "1MiB"

    # The pair round-trips through the parser.
    LET $back: INT = PARSE_BYTE_COUNT($pretty)
    ASSERT_EQ $back 1_048_576
    "###
)]
fn format_byte_count(
    /// Byte count to format; negatives fail.
    bytes: i64,
) -> DiagnosticResult<Value> {
    if bytes < 0 {
        return Err(std_diag::std_format_byte_count_negative(bytes));
    }
    Ok(Value::string(oxdock_parser::command::format_byte_count(
        bytes as u64,
    )))
}

/// Parse a byte-count token to `INT` bytes.
///
/// Bare digits are bytes; suffixes `B`/`KB`/`MB`/`GB`/`TB` scale
/// decimal and `KIB`/`MIB`/`GIB`/`TIB` binary, in any case. Plain
/// `INT` values pass through (already bytes); integral finite `FLOAT`
/// values convert. Pairs with `FORMAT_BYTE_COUNT` for the round trip.
///
/// ```oxdock
/// # Units parse case-insensitively; bare digits are bytes.
/// IMPORT [STD]
/// LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
/// ASSERT_EQ $bytes 1_000_000_000
///
/// # Binary suffixes scale by powers of two.
/// LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
/// ASSERT_EQ $mebi 2_097_152
///
/// # Digit runs group Rust-literal style.
/// LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
/// ASSERT_EQ $grouped 1_000_000
///
/// # Plain numbers pass through as bytes already.
/// LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
/// ASSERT_EQ $plain 1_048_576
///
/// # Bare literals group too.
/// LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
/// ASSERT_EQ $bare 1_000_000
///
/// # One optional space separates number from unit.
/// LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
/// ASSERT_EQ $spaced 1_000_000_000
/// ```
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "parse",
    code = r###"
    IMPORT [STD]
    LET $n: INT = PARSE_BYTE_COUNT("10KB")
    ASSERT_EQ $n 10_000
    LET $identity: INT = PARSE_BYTE_COUNT(512)
    ASSERT_EQ $identity 512
    "###
)]
fn parse_byte_count(
    /// Byte-count token to parse, or bytes already.
    #[union(Int, Float, String)]
    text: Value,
) -> DiagnosticResult<Value> {
    if let Some(n) = text.as_i64() {
        if n < 0 {
            return Err(std_diag::std_parse_byte_count_negative(n));
        }
        return Ok(Value::int(n));
    }
    if let Some(f) = text.as_f64() {
        if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
            return Ok(Value::int(f as i64));
        }
        return Err(std_diag::std_parse_byte_count_integral(f));
    }
    let Some(s) = text.as_str() else {
        return Err(std_diag::std_parse_byte_count_shape(&text));
    };
    let n = oxdock_parser::command::parse_byte_count(s)?;
    let n = i64::try_from(n).map_err(|_| std_diag::std_parse_byte_count_range(s))?;
    Ok(Value::int(n))
}

/// Format millisecond durations canonically (`500ms`, `10s`, `2m`,
/// `1h`): the inverse of `PARSE_DURATION`, so formatted values
/// reparse exactly. Negative inputs fail.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "format and round-trip",
    code = r###"
    # Durations render in the largest exact unit.
    IMPORT [STD]
    LET $pretty: STRING = FORMAT_DURATION(90_000)
    ASSERT_EQ $pretty "90s"

    # The pair round-trips through the parser.
    LET $back: INT = PARSE_DURATION($pretty)
    ASSERT_EQ $back 90_000
    "###
)]
fn format_duration(
    /// Milliseconds to format; negatives fail.
    millis: i64,
) -> DiagnosticResult<Value> {
    if millis < 0 {
        return Err(std_diag::std_format_duration_negative(millis));
    }
    Ok(Value::string(oxdock_parser::command::format_duration(
        &std::time::Duration::from_millis(millis as u64),
    )))
}

/// Parse a duration token to `INT` milliseconds.
///
/// Suffixes `ms`/`s`/`m`/`h`; a bare number means seconds. Pairs with
/// `FORMAT_DURATION` for the round trip.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "parse",
    code = r###"
    # A bare number means seconds, like TIMEOUT.
    IMPORT [STD]
    LET $ms: INT = PARSE_DURATION("2m")
    ASSERT_EQ $ms 120_000

    # Milliseconds stay exact.
    LET $exact: INT = PARSE_DURATION("1500ms")
    ASSERT_EQ $exact 1_500

    # One optional space separates number from unit.
    LET $spaced: INT = PARSE_DURATION("1 h")
    ASSERT_EQ $spaced 3_600_000
    "###
)]
fn parse_duration(
    /// Duration token to parse.
    text: String,
) -> DiagnosticResult<Value> {
    let duration = oxdock_parser::command::parse_duration(&text)?;
    let millis = i64::try_from(duration.as_millis())
        .map_err(|_| std_diag::std_parse_duration_range(&text))?;
    Ok(Value::int(millis))
}

/// List workspace paths matching a glob pattern.
///
/// Sorted, root-relative LIST; empty on no match or `..` escape.
///
#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "match",
    code = r###"
    IMPORT [STD]
    WRITE "notes-a.md" "a"
    WRITE "notes-b.md" "b"
    WRITE "other.txt" "c"
    LET $found: LIST<STRING> = GLOB("notes-*.md")
    ASSERT_EQ $found.0 "notes-a.md"
    ASSERT_EQ $found.1 "notes-b.md"
    "###
)]
fn glob<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Glob pattern matched against workspace paths.
    #[union(String, Path)]
    pattern: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&pattern)?;
    super::args::glob_from_value(&[Value::string(text)], cx)
}

/// Load and parse a TOML file.
///
/// Reads a workspace file and parses TOML into a DSL value.
///
#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
#[example(
    name = "load",
    code = r###"
    IMPORT [STD]
    WRITE "cfg.toml" "title = \"demo\""
    LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
    ASSERT_EQ $cfg.title "demo"
    "###
)]
fn load_toml<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace file path to load and parse as TOML.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    super::args::load_toml_from_value(&[Value::string(text)], cx)
}

/// Load and parse a JSON file.
///
/// Reads a workspace file and parses JSON into a DSL value. Returns
/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
/// scalar word. `LET` coercion still checks the actual value at
/// assignment.
///
#[oxdock_func(rpn, returns = TypeTag::Any)]
#[example(
    name = "load",
    code = r###"
    IMPORT [STD]
    WRITE "data.json" "{\"a\": 1}"
    LET $doc: MAP<ANY> = LOAD_JSON("data.json")
    ASSERT_EQ $doc.a 1
    "###
)]
fn load_json<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace file path to load and parse as JSON.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    super::args::load_json_from_value(&[Value::string(text)], cx)
}

/// Hash a workspace file or directory with SHA-256.
///
/// The argument is always a path: reads through the workspace guard
/// like the file-loading builtins, so relative paths resolve against
/// the script cwd. To hash a literal string's bytes instead, use
/// `ASSERT_EQ --hash <digest> <string>`, which hashes the actual
/// directly. Returns the 64 lowercase hex chars with no trailing
/// newline.
///
#[oxdock_func(rpn, returns = TypeTag::String)]
#[example(
    name = "hash",
    code = r###"
    IMPORT [STD]
    WRITE payload.txt hello
    LET $digest: STRING = HASH_SHA256("payload.txt")
    ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
    "###
)]
fn hash_sha256<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace file or directory path to hash.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    use sha2::Digest;

    let text = super::args::string_or_path_text(&path)?;
    let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
    let mut hasher = sha2::Sha256::new();
    super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
    let digest = hasher.finalize();
    let bytes: &[u8] = digest.as_ref();
    Ok(Value::string(oxdock_utils::hex_encode(bytes)))
}

/// Current working directory as a workspace-absolute path.
///
/// Returns `STRING` because the result is already resolved: a `PATH`
/// value is workspace-relative text awaiting guard checks at use time,
/// while this directory is already checked and concrete, or absent
/// entirely under a pending snapshot. Compare or display it as text.
///
/// Reports the snapshot-pending sentinel when no concrete directory
/// exists yet, so snapshot scripts keep working unchanged.
///
#[oxdock_func(rpn, returns = TypeTag::String)]
#[example(
    name = "cwd",
    code = r###"
    IMPORT [STD]
    WORKDIR sub
    LET $c: STRING = CWD()
    ASSERT_CONTAINS $c "sub"
    "###
)]
fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    if cx.state.fs.is_snapshot_pending() {
        return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
    }
    let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
    let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
    Ok(Value::string(real))
}

/// Parse TOML text already held in memory.
///
/// Uses the same conversion as file loading, so fetch bodies, file
/// contents, and captured text share one JSON/TOML shape.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
#[example(
    name = "parse",
    code = r###"
    IMPORT [STD]
    LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
    ASSERT_EQ $doc.title "demo"
    "###
)]
fn parse_toml(
    /// TOML text already held in memory.
    text: String,
) -> DiagnosticResult<Value> {
    super::args::parse_toml_from_value(Value::string(text))
}

/// Parse JSON text already held in memory.
///
/// Uses the same conversion as file loading, so fetch bodies, file
/// contents, and captured text share one JSON value shape. Returns
/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
/// parses to `LIST` or a scalar word. `LET` coercion still checks the
/// actual value at assignment.
///
#[oxdock_func(pure, returns = TypeTag::Any)]
#[example(
    name = "parse",
    code = r###"
    # Parse in-memory JSON text with the same conversion as file loading.
    IMPORT [STD]
    LET $body: STRING = "{\"a\": 1}"
    LET $doc: ANY = PARSE_JSON($body)
    ASSERT_EQ $doc.a 1

    # Top-level arrays parse to LIST, which is why the return is ANY.
    LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
    ASSERT_EQ $items.0 1
    ASSERT_EQ $items.1 2
    "###
)]
fn parse_json(
    /// JSON text already held in memory.
    text: String,
) -> DiagnosticResult<Value> {
    super::args::parse_json_from_value(Value::string(text))
}

/// Describe a filesystem entry.
///
/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
/// there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::String)]
#[example(
    name = "describe",
    code = r###"
    IMPORT [STD]
    WRITE "entry.txt" "words"
    LET $kind: STRING = PATH_TYPE("entry.txt")
    ASSERT_EQ $kind "file"
    LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
    ASSERT_EQ $missing "absent"
    "###
)]
fn path_type<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path of the entry to describe.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    super::args::path_type_from_value(&[Value::string(text)], cx)
}

/// Report whether an ordinary file can be created at a path.
///
/// Walks up to the nearest existing ancestor, requires it be a
/// directory, and probes writability by creating and deleting a probe
/// file, so retry loops never litter. The empty string is false.
/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
/// filesystem IO.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    # An absent nested path is writable when its ancestor is.
    IMPORT [STD]
    LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
    ASSERT_EQ $fresh true

    # The empty string never aliases the working directory.
    LET $empty: BOOL = PATH_WRITABLE("")
    ASSERT_EQ $empty false
    "###
)]
fn path_writable<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path to probe for file creation.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    super::args::path_writable_from_value(&[Value::string(text)], cx)
}

/// Report whether a name resolves to an executable file (#100).
///
/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
/// containing a separator check that file directly. True means a real
/// file with an executable bit on Unix, or a `PATHEXT` extension on
/// Windows: each `env:PATHEXT` entry is probed in order (unset or empty
/// probes nothing). Absolute `PATH` entries resolve through the workspace as
/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
/// `PATH`; anything unresolvable reads false, never errors. AST-only
/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    # Missing tools read false instead of failing the run.
    IMPORT [STD]
    LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
    ASSERT_EQ $missing false

    # Plain files are not executable on any platform.
    WRITE tool.txt payload
    LET $plain: BOOL = IS_EXEC("tool.txt")
    ASSERT_EQ $plain false
    "###
)]
fn is_exec<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Command name or file path to probe.
    #[union(String, Path)]
    name: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&name)?;
    super::args::is_exec_from_value(&[Value::string(text)], cx)
}

/// Report whether a workspace path names an ordinary file.
///
/// No-follow by design like `PATH_TYPE`: a symlink is neither a file
/// nor a directory, so it reads false here. Missing or unresolvable
/// paths read false, never error. AST-only by design, like `PATH_TYPE`:
/// there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    # Ordinary files read true; missing paths read false.
    IMPORT [STD]
    WRITE "entry.txt" "words"
    LET $hit: BOOL = IS_FILE("entry.txt")
    ASSERT_EQ $hit true
    LET $miss: BOOL = IS_FILE("no-such-entry.txt")
    ASSERT_EQ $miss false
    "###
)]
fn is_file<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path to probe.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    Ok(Value::bool(super::args::path_is_file(cx, &text)))
}

/// Report whether a workspace path names a directory.
///
/// No-follow by design like `PATH_TYPE`: a symlink is neither a file
/// nor a directory, so it reads false here. Missing or unresolvable
/// paths read false, never error. AST-only by design, like `PATH_TYPE`:
/// there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    # Directories read true; files read false.
    IMPORT [STD]
    LET $hit: BOOL = IS_DIR(".")
    ASSERT_EQ $hit true
    WRITE "entry.txt" "words"
    LET $miss: BOOL = IS_DIR("entry.txt")
    ASSERT_EQ $miss false
    "###
)]
fn is_dir<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path to probe.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    Ok(Value::bool(super::args::path_is_dir(cx, &text)))
}

/// Report whether a workspace path exists in any form.
///
/// True for files, directories, and symlinks; false for absent or
/// unresolvable paths, never an error. AST-only by design, like
/// `PATH_TYPE`: there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    # Present entries read true; absent paths read false.
    IMPORT [STD]
    WRITE "entry.txt" "words"
    LET $hit: BOOL = EXISTS("entry.txt")
    ASSERT_EQ $hit true
    LET $miss: BOOL = EXISTS("no-such-entry.txt")
    ASSERT_EQ $miss false
    "###
)]
fn exists<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path to probe.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    Ok(Value::bool(super::args::path_exists(cx, &text)))
}

/// Report whether a map holds a key.
///
/// Pure MAP probe so scripts can branch on optional fields without
/// tripping the strict missing-key error.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "probe",
    code = r###"
    IMPORT [STD]
    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
    LET $hit: BOOL = HAS_KEY($m, "a")
    ASSERT_EQ $hit true
    LET $miss: BOOL = HAS_KEY($m, "b")
    ASSERT_EQ $miss false
    "###
)]
fn has_key(
    /// Map to probe.
    map: BTreeMap<String, Value>,
    /// Key to look up.
    key: String,
) -> DiagnosticResult<Value> {
    super::args::has_key_from_value(Value::map(map), &key)
}

/// Read one map entry with a default for missing keys.
///
/// Pure MAP getter so optional flags cost one line instead of a
/// `HAS_KEY` + index + rebind triple: present keys return their value
/// verbatim (no coercion), absent keys return `default`.
#[oxdock_func(pure, returns = TypeTag::Any)]
#[example(
    name = "present and absent",
    code = r###"
    IMPORT [STD]
    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
    LET $hit: INT = GET($m, "a", 0)
    ASSERT_EQ $hit 1
    LET $miss: INT = GET($m, "b", 0)
    ASSERT_EQ $miss 0
    "###
)]
fn get(
    /// Map to read.
    map: BTreeMap<String, Value>,
    /// Key to look up.
    key: String,
    /// Default for absent keys.
    default: Value,
) -> DiagnosticResult<Value> {
    Ok(map.get(&key).cloned().unwrap_or(default))
}

/// Insert one key into a map, returning the extended map.
///
/// Fails on duplicates so two entries sharing a key fail the run
/// instead of silently shadowing each other.
///
/// A frozen (`CONST`-derived) map fails instead of deriving: `CONST`
/// bindings never produce a mutable map, so snapshot explicitly
/// through a `LET` copy of unfrozen data if derivation is intended.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
#[example(
    name = "insert",
    code = r###"
    IMPORT [STD]
    LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
    ASSERT_EQ $m.a 1
    "###
)]
fn map_set(
    /// Map to insert into.
    #[reject_frozen]
    map: BTreeMap<String, Value>,
    /// Key to insert; duplicates fail.
    key: String,
    /// Value to store.
    value: Value,
) -> DiagnosticResult<Value> {
    super::args::map_set_from_value(Value::map(map), key, value)
}

/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
///
/// Impure by design: unseeded calls return different values, so this
/// runs on the AST script path only, never as a `{{ }}` placeholder
/// call. A seed draws the same value on every run, for deterministic
/// fixtures. Scale and shift the draw for wider ranges.
///
#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
#[example(
    name = "seeded draw",
    code = r###"
    # A seed draws the same value on every run.
    IMPORT [STD]
    LET $one: FLOAT = RAND({seed: 7})
    LET $two: FLOAT = RAND({seed: 7})
    ASSERT_EQ $one $two
    "###
)]
#[example(
    name = "unseeded draw",
    code = r###"
    # Scale a unit draw into a backoff delay between 1 and 11 seconds.
    IMPORT [STD]
    LET $draw: FLOAT = RAND()
    LET $delay: FLOAT = 1.0 + $draw * 10.0
    IF $delay < 1.0 {
        FAIL "trap: RAND draw below range"
    }
    IF $delay >= 11.0 {
        FAIL "trap: RAND draw above range"
    }
    ECHO "retrying in {{ $delay }}s"
    "###
)]
fn rand<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.
    #[options("seed?: INT")]
    #[optional]
    options: BTreeMap<String, Value>,
) -> DiagnosticResult<Value> {
    let _ = cx;
    // `check_options` in the wrapper verified the shape above; the
    // read below narrows infallibly after.
    let seed = options
        .get("seed")
        .map(|value| value.as_i64().expect("check_options verified INT"));
    super::args::rand_float_from_value(seed)
}

/// Encode a STRING as standard base64.
///
/// Padded RFC 4648 alphabet, so encoded output pastes into any
/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "encode",
    code = r###"
    # Encode text to standard base64.
    IMPORT [STD]
    LET $encoded: STRING = BASE64_ENCODE("hello")
    ASSERT_EQ $encoded "aGVsbG8="
    "###
)]
fn base64_encode(
    /// Text to encode.
    text: String,
) -> DiagnosticResult<Value> {
    super::args::base64_encode_from_value(Value::string(text))
}

/// Decode standard base64 to a STRING.
///
/// Fails naming the input on invalid alphabet characters or
/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
/// with `BASE64_ENCODE` for the round trip.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "decode",
    code = r###"
    # Decode standard base64 back to text.
    IMPORT [STD]
    LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
    ASSERT_EQ $decoded "hello"
    "###
)]
fn base64_decode(
    /// Base64 text to decode.
    text: String,
) -> DiagnosticResult<Value> {
    super::args::base64_decode_from_value(Value::string(text))
}

/// Encode a script value as JSON with one trailing newline.
///
/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
/// BOOL, LIST, MAP) survive, anything else fails here instead of
/// rendering as a silent empty.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "encode",
    code = r###"
    IMPORT [STD]
    LET $json: STRING = TO_JSON({a: 1})
    ASSERT_EQ $json "{\"a\":1}\n"
    "###
)]
fn to_json(
    /// Value to encode as JSON.
    #[union(String, Int, Float, Bool, List, Map)]
    value: Value,
) -> DiagnosticResult<Value> {
    super::args::to_json_from_value(value)
}

/// Name the word a value holds, for data-driven branching.
///
/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
/// value prints in arity and coercion errors, so scripts can branch
/// on config shapes (a path string or a path list) without failing.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "name the word",
    code = r###"
    IMPORT [STD]
    LET $word: STRING = TYPE_OF(42)
    ASSERT_EQ $word "INT"
    "###
)]
fn type_of(
    /// Value whose word to name.
    value: Value,
) -> DiagnosticResult<Value> {
    super::args::type_of_from_value(value)
}

/// Merge a LIST of MAPs in order under one duplicate policy.
///
/// `fail_on_duplicate` fails naming the repeated key, so two files
/// claiming one placeholder fail the run instead of shadowing each
/// other. `overwrite` lets later files win, for environment overlays.
/// Non MAP elements fail naming their position.
///
/// A frozen (`CONST`-derived) list or element fails instead of
/// deriving, mirroring `MAP_SET`: `CONST` bindings never produce a
/// mutable map.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
#[example(
    name = "merge",
    code = r###"
    IMPORT [STD]
    LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
    ASSERT_EQ $m.a 1
    ASSERT_EQ $m.b 2
    "###
)]
fn merge_maps(
    /// LIST of MAPs to merge in order.
    #[reject_frozen]
    maps: Vec<BTreeMap<String, Value>>,
    /// Duplicate policy.
    #[values("fail_on_duplicate", "overwrite")]
    policy: String,
) -> DiagnosticResult<Value> {
    super::args::merge_maps_from_value(
        Value::list(maps.into_iter().map(Value::map).collect()),
        policy,
    )
}

/// Report the running engine version.
///
/// Returns the workspace version baked in at compile time, so scripts
/// and agents can branch on engine behavior instead of probing it.
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "report",
    code = r###"
    # The engine reports its own build version as a dotted string.
    IMPORT [STD]
    LET $v: STRING = VERSION()
    ASSERT_CONTAINS $v "."
    "###
)]
fn version() -> DiagnosticResult<Value> {
    Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
}

/// List all visible function names.
///
/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
/// plus host-registered names.
#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "list",
    code = r###"
    IMPORT [STD]
    LET $names: LIST<STRING> = FUNCTIONS()
    ASSERT_CONTAINS $names "STD::INT"
    "###
)]
fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    let mut names: Vec<String> = cx
        .state
        .list_functions()
        .into_iter()
        .map(|meta| meta.name)
        .collect();
    names.sort();
    names.dedup();
    Ok(Value::list(names.into_iter().map(Value::string).collect()))
}

/// Report the verbatim CLI tail after the script position.
///
/// Staged per run from `Options.script_args` (#226): everything after
/// the script file (or `--script <file>`), with one leading `--`
/// stripped. Never merged with interpreter flags, so `--dry-run`
/// after the script arrives here instead of enabling dry-run.
#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "empty",
    code = r###"
    # With no staged args the list is empty.
    IMPORT [STD]
    LET $args: LIST<STRING> = ARGV()
    LET $n: INT = LEN($args)
    ASSERT_EQ $n 0
    "###
)]
fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    Ok(Value::list(
        cx.state
            .io
            .script_args()
            .iter()
            .cloned()
            .map(Value::string)
            .collect(),
    ))
}

/// Parse an argv tail against `TYPE FLAGS`, returning flags and positionals.
///
/// Consumes a `LIST<STRING>` (usually `STD::ARGV()`) with the `lexopt`
/// tokenizer. Long `--key=value` binds the string value. Bare long
/// `--key` binds `true`. Short `-a` binds `true`. One `--` entry ends
/// option parsing, so the rest lands in `positionals`. Duplicate keys
/// overwrite in order, so the last occurrence wins.
///
/// The schema is always `TYPE FLAGS`: a `MAP` shape with scalar
/// fields. Present flags coerce to their target (`BOOL` accepts
/// `true`/`false` spellings, `INT`/`FLOAT` parse their strings); bare
/// `--key` for a non-`BOOL` target fails naming the flag. Missing
/// flags fill their `= default`, missing required flags fail, and
/// unknown flags fail. Defaults are literals only: `INT`, `FLOAT`,
/// `BOOL`, and double-quoted `STRING`. A variable or expression in
/// place of a literal fails the `TYPE` statement, so defaults stay
/// plain data in the shape. Absent optional flags without a default stay
/// absent (read them with a typed `GET` default). `positionals` is
/// omitted when empty, so a flags only `MAP<flags: FLAGS>` binds clean.
pub struct ParseArgs;

impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
    fn registration() -> HostRegistration<P> {
        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
            if values.len() != 1 {
                return Err(std_diag::std_parse_args_arity(values.len()));
            }
            let mut iter = values.into_iter();
            let args_val = iter.next().expect("arity checked above");
            let args =
                string_list_arg(&args_val, &format!("{FUNC_PARSE_ARGS}() argument `$args`"))?;
            let specs = resolve_flags_specs(cx)?;
            let (raw, positionals) = tokenize_raw_args(args)?;
            let coerced = coerce_flags(&specs, &raw)?;
            let mut out = BTreeMap::new();
            out.insert("flags".to_string(), Value::map(coerced));
            if !positionals.is_empty() {
                out.insert("positionals".to_string(), Value::list(positionals));
            }
            Ok(Value::map(out))
        });
        HostRegistration::Stateful {
            name: FUNC_PARSE_ARGS.to_string(),
            meta: FuncMeta {
                name: FUNC_PARSE_ARGS.to_string(),
                module: String::new(),
                kind: FuncKind::HostPure,
                params: Some(vec![FuncParam {
                    name: "args".to_string(),
                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
                    allowed: None,
                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
                    options: None,
                    optional: false,
                }]),
                returns: Some(TypeTag::Record(Arc::from([
                    Field {
                        name: "flags".to_string(),
                        ty: TypeTag::Map,
                        docs: "Flags coerced to `TYPE FLAGS`.",
                        optional: false,
                        default: None,

                        alias: None,
                    },
                    Field {
                        name: "positionals".to_string(),
                        ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
                        docs: "Trailing values and entries after the first double dash. Omitted when empty.",
                        optional: true,
                        default: None,

                        alias: None,
                    },
                ]))),
                rpn: true,
                summary: "Parse an argv tail against TYPE FLAGS.",
                docs: "Consumes a `LIST<STRING>` with the `lexopt` tokenizer and coerces flags through `TYPE FLAGS`. See the function reference for the coercion and omission rules.",
                examples: &[
                    crate::Example {
                        name: "flags and positionals",
                        fence_meta: None,
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # One schema TYPE drives coercion; the pair binds both slots.
                            TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
                            LET $flags: FLAGS = $parsed.flags
                            ASSERT_EQ $flags.model "gpt-4"
                            ASSERT_EQ $flags.verbose true
                            ASSERT_EQ $parsed.positionals.0 "serve"
                        "#},
                    },
                    crate::Example {
                        name: "optional stays absent",
                        fence_meta: None,
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Absent optionals stay absent; read them with a typed GET default.
                            TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
                            LET $flags: FLAGS = $parsed.flags
                            LET $propose: BOOL = GET($flags, "propose", false)
                            ASSERT_EQ $propose false
                        "#},
                    },
                    crate::Example {
                        name: "flags only omits positionals",
                        fence_meta: None,
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Empty positionals are omitted, so declare the slot
                            # optional to bind a flags-only run clean.
                            TYPE FLAGS = MAP<model: STRING>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
                            LET $flags: FLAGS = $parsed.flags
                            ASSERT_EQ $flags.model "x"
                        "#},
                    },
                    crate::Example {
                        name: "literal defaults",
                        fence_meta: None,
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Defaults are literals only: INT, FLOAT, BOOL,
                            # and double-quoted STRING fill absent flags.
                            TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS([])
                            LET $flags: FLAGS = $parsed.flags
                            ASSERT_EQ $flags.retries 2
                            ASSERT_EQ $flags.verbose true
                            ASSERT_EQ $flags.model "gpt-4"
                            LET $ratio_ok: BOOL = $flags.ratio == 2.5
                            ASSERT_EQ $ratio_ok true
                        "#},
                    },
                    crate::Example {
                        name: "variable default fails",
                        fence_meta: Some("expect_error:\"expected default literal\""),
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Defaults are literals: a variable in place
                            # of a literal fails instead of evaluating.
                            TYPE FLAGS = MAP<n: INT = $x>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $p: PARSED = PARSE_ARGS([])
                        "#},
                    },
                    crate::Example {
                        name: "missing required",
                        fence_meta: Some("expect_error:\"missing required flag\""),
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Absent required flags fail naming the flag.
                            TYPE FLAGS = MAP<model: STRING>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS([])
                        "#},
                    },
                    crate::Example {
                        name: "unknown flag",
                        fence_meta: Some("expect_error:\"unknown flag\""),
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Undeclared flags fail instead of passing through.
                            TYPE FLAGS = MAP<model: STRING>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
                        "#},
                    },
                    crate::Example {
                        name: "alias accepted",
                        fence_meta: None,
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # One canonical key binds both spellings; the
                            # alias never appears as a separate key.
                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $a: PARSED = PARSE_ARGS(["--help"])
                            ASSERT_EQ $a.flags.h true
                            LET $b: PARSED = PARSE_ARGS(["--h"])
                            ASSERT_EQ $b.flags.h true
                        "#},
                    },
                    crate::Example {
                        name: "alias duplicate fails",
                        fence_meta: Some("expect_error:\"duplicate flag\""),
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Canonical and alias together fail naming both.
                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
                        "#},
                    },
                    crate::Example {
                        name: "alias missing names both",
                        fence_meta: Some("expect_error:\"--h/--help\""),
                        code: indoc::indoc! {r#"
                            IMPORT [STD]
                            # Missing required flags name both spellings.
                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
                            TYPE POSITIONS = LIST<STRING>
                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
                            LET $p: PARSED = PARSE_ARGS([])
                        "#},
                    },
                ],
            },
            func,
        }
    }
}

/// CLI target types for `PARSE_ARGS` schemas: the four scalar words
/// raw flags can coerce into. No new types without extending the
/// coercion below together with the schema resolution below it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CliType {
    String,
    Bool,
    Int,
    Float,
}

/// Coerce one raw flag value to its schema target. Raw values are only
/// ever `BOOL true` (bare) or `STRING` (equals form); anything else is
/// a caller bug. Bare flags for non-`BOOL` targets fail naming the
/// flag instead of smuggling `true` into the slot.
fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> DiagnosticResult<Value> {
    match target {
        CliType::Bool => {
            if let Some(b) = raw.as_bool() {
                return Ok(Value::bool(b));
            }
            if let Some(s) = raw.as_str() {
                match super::args::parse_bool_str(s) {
                    Some(b) => return Ok(Value::bool(b)),
                    None => {
                        return Err(std_diag::std_parse_args_bool_flag(flag, s));
                    }
                }
            }
            Err(std_diag::std_parse_args_bool_type(flag, raw.type_name()))
        }
        CliType::String => {
            if let Some(s) = raw.as_str() {
                return Ok(Value::string(s.to_string()));
            }
            Err(std_diag::std_parse_args_needs_value(flag))
        }
        CliType::Int => {
            if raw.as_bool().is_some() {
                return Err(std_diag::std_parse_args_needs_value(flag));
            }
            super::args::int_from_value(raw).map_err(|_| std_diag::std_parse_args_expects_int(flag))
        }
        CliType::Float => {
            if raw.as_bool().is_some() {
                return Err(std_diag::std_parse_args_needs_value(flag));
            }
            super::args::float_from_value(raw)
                .map_err(|_| std_diag::std_parse_args_expects_float(flag))
        }
    }
}

/// One CLI flag spec: target type, required bit, filled default, and
/// optional alternate spelling. Single owner so the tokenizer,
/// coercion, and both entry points share one signature.
#[derive(Debug, Clone)]
struct CliSpec {
    target: CliType,
    required: bool,
    default: Option<Value>,
    alias: Option<String>,
}

/// Canonical specs keyed by canonical flag name.
type CliSpecs = BTreeMap<String, CliSpec>;

/// Checked `LIST<STRING>` extraction for the CLI trio. Single owner
/// so all three functions admit exactly the same argv shape.
fn string_list_arg(val: &Value, what: &str) -> DiagnosticResult<Vec<String>> {
    crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)
        .map_err(|err| std_diag::std_parse_args_arg_shape(&err))?;
    Ok(val
        .as_list()
        .expect("check_value_at enforces LIST")
        .iter()
        .map(|v| {
            v.as_str()
                .expect("check_value_at enforces STRING")
                .to_string()
        })
        .collect())
}

/// Shared argv tokenizer. Single owner so flags versus positionals
/// split identically for all three entry points. Raw values are only
/// `BOOL true` (bare) or `STRING` (equals form).
fn tokenize_raw_args(args: Vec<String>) -> DiagnosticResult<(BTreeMap<String, Value>, Vec<Value>)> {
    use lexopt::Arg::{Long, Short, Value as ArgValue};
    let mut parser = lexopt::Parser::from_args(args);
    let mut flags: BTreeMap<String, Value> = BTreeMap::new();
    let mut positionals: Vec<Value> = Vec::new();
    let utf8 = |value: std::ffi::OsString| -> DiagnosticResult<String> {
        value
            .into_string()
            .map_err(|_| std_diag::std_parse_args_not_utf8())
    };
    loop {
        match parser.next() {
            Ok(None) => break,
            Ok(Some(Long(name))) => {
                let key = name.to_owned();
                if let Some(raw) = parser.optional_value() {
                    flags.insert(key, Value::string(utf8(raw)?));
                } else {
                    flags.insert(key, Value::bool(true));
                }
            }
            Ok(Some(Short(ch))) => {
                flags.insert(ch.to_string(), Value::bool(true));
            }
            Ok(Some(ArgValue(raw))) => {
                positionals.push(Value::string(utf8(raw)?));
            }
            Err(lexopt::Error::UnexpectedValue { option, value }) => {
                let key = option
                    .strip_prefix("--")
                    .or_else(|| option.strip_prefix('-'))
                    .unwrap_or(option.as_str());
                flags.insert(key.to_string(), Value::string(utf8(value)?));
            }
            Err(err) => return Err(std_diag::std_parse_args_lex_error(&err)),
        }
    }
    Ok((flags, positionals))
}

/// Shared flag coercion. Single owner so `PARSE_ARGS` and
/// `PARSE_FLAGS` fill, require, and reject identically: present flags
/// (canonical or alias) coerce, missing defaulted flags fill, missing
/// required flags fail, missing optionals stay absent, unknown flags
/// fail. One canonical key lands in the parsed map; alias spellings
/// ride the command line only. Missing and duplicate errors name both
/// spellings when an alias exists.
fn coerce_flags(
    specs: &CliSpecs,
    raw: &BTreeMap<String, Value>,
) -> DiagnosticResult<BTreeMap<String, Value>> {
    // Alias reverse map: alias spelling to canonical key. Validated
    // unique at type resolution, so a duplicate insert is unreachable.
    let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
    for (canonical, spec) in specs.iter() {
        if let Some(alias) = spec.alias.as_ref() {
            alias_to_canonical.insert(alias.as_str(), canonical.as_str());
        }
    }
    let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
    for (flag, spec) in specs.iter() {
        if flag.is_empty() {
            return Err(std_diag::std_parse_args_schema_flag_empty());
        }
        let canonical_raw = raw.get(flag);
        let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
        if canonical_raw.is_some() && alias_raw.is_some() {
            return Err(std_diag::std_parse_args_duplicate_flag(
                flag,
                spec.alias.as_deref(),
            ));
        }
        if let Some(raw_val) = canonical_raw.or(alias_raw) {
            coerced.insert(
                flag.clone(),
                coerce_cli_flag(spec.target, flag, raw_val.clone())?,
            );
        } else if let Some(d) = spec.default.as_ref() {
            coerced.insert(flag.clone(), d.clone());
        } else if spec.required {
            return Err(std_diag::std_parse_args_missing_flag(
                flag,
                spec.alias.as_deref(),
            ));
        }
    }
    for flag in raw.keys() {
        if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
            return Err(std_diag::std_parse_args_unknown_flag(flag));
        }
    }
    Ok(coerced)
}

/// Resolve the fixed `TYPE FLAGS` schema into coercion specs: one entry
/// per record field, targets from scalar field types, required unless
/// optional or defaulted, defaults filled from the shape, aliases
/// carried for command-line acceptance. Single owner so both pair and
/// flags only entry points admit exactly the same set. Non-record
/// types and non-scalar fields fail naming the flag.
fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<CliSpecs> {
    let name = "FLAGS";
    let tag = cx
        .state
        .resolve_tag(name)
        .map_err(|err| std_diag::std_parse_args_schema_type(name, &err))?;
    let TypeTag::Record(fields) = tag else {
        return Err(std_diag::std_parse_args_schema_shape(name));
    };
    let mut specs = BTreeMap::new();
    for field in fields.iter() {
        let target = match field.ty {
            TypeTag::String => CliType::String,
            TypeTag::Bool => CliType::Bool,
            TypeTag::Int => CliType::Int,
            TypeTag::Float => CliType::Float,
            _ => {
                return Err(std_diag::std_parse_args_schema_field_type(
                    &field.name,
                    field.ty.name(),
                ));
            }
        };
        specs.insert(
            field.name.clone(),
            CliSpec {
                target,
                required: !field.optional && field.default.is_none(),
                default: field.default.clone(),
                alias: field.alias.clone(),
            },
        );
    }
    Ok(specs)
}

/// Parse flags only against `TYPE FLAGS`.
///
/// Returns the flags `MAP` directly: no pair wrapper. Positional
/// arguments fail instead of dropping silently, so a space-separated
/// value (`--model gpt-4`) names the mistake instead of binding
/// `--model` to `true` and losing `gpt-4`.
/// Same tokenizer, coercion, defaults, and errors as `PARSE_ARGS`.
pub struct ParseFlags;

impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
    fn registration() -> HostRegistration<P> {
        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
            if values.len() != 1 {
                return Err(std_diag::std_parse_flags_arity(values.len()));
            }
            let mut iter = values.into_iter();
            let args_val = iter.next().expect("arity checked above");
            let args = string_list_arg(&args_val, "{FUNC_PARSE_FLAGS}() argument `$args`")?;
            let specs = resolve_flags_specs(cx)?;
            let (raw, positionals) = tokenize_raw_args(args)?;
            if !positionals.is_empty() {
                return Err(std_diag::std_parse_flags_positional(
                    &positionals
                        .iter()
                        .map(|pos| pos.to_string())
                        .collect::<Vec<_>>(),
                ));
            }
            Ok(Value::map(coerce_flags(&specs, &raw)?))
        });
        HostRegistration::Stateful {
            name: FUNC_PARSE_FLAGS.to_string(),
            meta: FuncMeta {
                name: FUNC_PARSE_FLAGS.to_string(),
                module: String::new(),
                kind: FuncKind::HostPure,
                params: Some(vec![FuncParam {
                    name: "args".to_string(),
                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
                    allowed: None,
                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
                    options: None,
                    optional: false,
                }]),
                returns: Some(TypeTag::Map),
                rpn: true,
                summary: "Parse flags against TYPE FLAGS.",
                docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
                examples: &[crate::Example {
                    name: "flags only",
                    fence_meta: None,
                    code: indoc::indoc! {r#"
                        IMPORT [STD]
                        # Flags only returns the flags MAP directly.
                        TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
                        LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
                        ASSERT_EQ $flags.model "x"
                        ASSERT_EQ $flags.retries 2
                    "#},
                }],
            },
            func,
        }
    }
}

/// Parse positionals only: no schema, no `TYPE FLAGS` needed.
///
/// Returns trailing values and entries after the first double dash in
/// argv order. Tokenizer matches `PARSE_ARGS` exactly.
pub struct ParsePositionals;

impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
    fn registration() -> HostRegistration<P> {
        let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
            if values.len() != 1 {
                return Err(std_diag::std_parse_positionals_arity(values.len()));
            }
            let mut iter = values.into_iter();
            let args_val = iter.next().expect("arity checked above");
            let args = string_list_arg(
                &args_val,
                &format!("{FUNC_PARSE_POSITIONALS}() argument `$args`"),
            )?;
            let (_raw, positionals) = tokenize_raw_args(args)?;
            Ok(Value::list(positionals))
        });
        HostRegistration::Stateful {
            name: FUNC_PARSE_POSITIONALS.to_string(),
            meta: FuncMeta {
                name: FUNC_PARSE_POSITIONALS.to_string(),
                module: String::new(),
                kind: FuncKind::HostPure,
                params: Some(vec![FuncParam {
                    name: "args".to_string(),
                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
                    allowed: None,
                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
                    options: None,
                    optional: false,
                }]),
                returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
                rpn: true,
                summary: "Parse positionals in argv order.",
                docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
                examples: &[crate::Example {
                    name: "positionals only",
                    fence_meta: None,
                    code: indoc::indoc! {r#"
                        IMPORT [STD]
                        # No schema needed: positionals are always strings in order.
                        TYPE POSITIONS = LIST<STRING>
                        LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
                        ASSERT_EQ $pos.0 "serve"
                        ASSERT_EQ $pos.1 "--not-a-flag"
                    "#},
                }],
            },
            func,
        }
    }
}

/// Describe one function by qualified name.
///
/// Returns a MAP with name, module, kind, params, returns, rpn, and
/// summary. `params` is always a LIST (empty for parameterless
/// functions) of entries carrying name, param_type, allowed, docs,
/// options, and optional flags, so the shape holds for every entry. Bare names
/// fail closed: `DESCRIBE` requires the qualified form (except
/// `INSPECT`, which is syntax rather than a registry entry). Errors
/// on unknown function.
///
/// Field table for the `DESCRIBE` result bundle: one source for the
/// shape the host mints, so introspection, enforcement, and
/// documentation cannot drift apart.

#[oxdock_func(
    returns = TypeTag::Record(std::sync::Arc::from([Field {
        name: "name".to_string(),
        ty: TypeTag::String,
        docs: "Qualified function name.",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "module".to_string(),
        ty: TypeTag::String,
        docs: "Owning module.",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "kind".to_string(),
        ty: TypeTag::String,
        docs: "Origin label (`host` or `script`).",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "params".to_string(),
        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
            TypeTag::Any,
        )))),
        docs: "Parameter entries (empty for parameterless functions).",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "returns".to_string(),
        ty: TypeTag::String,
        docs: "Structural return shape (empty when untagged).",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "rpn".to_string(),
        ty: TypeTag::Bool,
        docs: "True when callable in RPN position.",
        optional: false,
        default: None,

        alias: None,}, Field {
        name: "summary".to_string(),
        ty: TypeTag::String,
        docs: "One-line description.",
        optional: false,
        default: None,

        alias: None,}]))
    summary = "Describe one function by qualified name."
)]
#[example(
    name = "describe",
    code = r###"
    IMPORT [STD]
    LET $info: MAP<ANY> = DESCRIBE("STD::INT")
    ASSERT_EQ $info.name "STD::INT"
    ASSERT_EQ $info.returns "INT"
    "###
)]
fn describe<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Qualified function name (`MODULE::NAME`).
    name: String,
) -> DiagnosticResult<Value> {
    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
        return Err(std_diag::func_describe_unqualified(&name));
    }
    cx.state
        .describe_function(&name)
        .ok_or_else(|| std_diag::func_unknown(&name))
}

/// List all known type names.
///
/// Sorted LIST of startup plus host-registered type descriptors. Reads the
/// run's name directory, so it runs on the AST path like the other
/// introspection functions.
#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "list",
    code = r###"
    IMPORT [STD]
    LET $names: LIST<STRING> = TYPES()
    ASSERT_CONTAINS $names "STRING"
    "###
)]
fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    Ok(Value::list(
        cx.state
            .type_names()
            .into_iter()
            .map(Value::string)
            .collect(),
    ))
}

/// Describe one type by name.
///
/// Returns a MAP with name, summary, and docs. Errors on unknown type.
/// Reads the run's name directory, so it runs on the AST path.
///
#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
    name: "name".to_string(),
    ty: TypeTag::String,
    docs: "Queried type name.",
    optional: false,
    default: None,

    alias: None,}, Field {
    name: "summary".to_string(),
    ty: TypeTag::String,
    docs: "One-line description.",
    optional: false,
    default: None,

    alias: None,}, Field {
    name: "docs".to_string(),
    ty: TypeTag::String,
    docs: "Full documentation text.",
    optional: false,
    default: None,

    alias: None,}])))]
#[example(
    name = "describe",
    code = r###"
    IMPORT [STD]
    LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
    ASSERT_EQ $info.name "STRING"
    "###
)]
fn type_describe<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Type name to describe.
    name: String,
) -> DiagnosticResult<Value> {
    if let Some(descriptor) = cx.state.describe_type(&name) {
        let mut map = BTreeMap::new();
        map.insert(
            "name".to_string(),
            Value::string(descriptor.name.to_string()),
        );
        map.insert(
            "summary".to_string(),
            Value::string(descriptor.summary.to_string()),
        );
        map.insert(
            "docs".to_string(),
            Value::string(descriptor.docs.to_string()),
        );
        return Ok(Value::map(map));
    }
    // Script aliases have no descriptor but introspect the same way:
    // the entry names the alias and its canonical target spelling.
    if let Some(target) = cx.state.alias_target(&name) {
        let mut map = BTreeMap::new();
        map.insert("name".to_string(), Value::string(name.clone()));
        map.insert(
            "summary".to_string(),
            Value::string(format!("Script type alias for {target}.")),
        );
        map.insert(
            "docs".to_string(),
            Value::string(format!(
                "Declared with {KEYWORD_TYPE} {name} = {target}. The alias expands structurally at every declaration."
            )),
        );
        return Ok(Value::map(map));
    }
    Err(std_diag::std_unknown_type(&name))
}

/// Path of the running interpreter binary.
///
/// Returns the executing binary as a `STRING`, so one script can
/// reinvoke the interpreter on another script without bridging an env
/// var. The child re-parses from bytes in a separate process: no
/// bindings cross back (only stdout and files), and each run pays
/// a spawn. Prefer modules for reuse (statically gated, in-process);
/// reach for reinvocation when the child must run isolated, or under
/// a different binary than the parent.
///
/// Unsupported under Miri isolation: the lookup itself fails there
/// instead of returning a path.
///
#[oxdock_func(returns = TypeTag::String)]
#[example(
    name = "self",
    code = r###"
    # The running interpreter resolves to a non-empty path.
    IMPORT [STD]
    LET $exe: STRING = INTERPRETER()
    LET $nonempty: BOOL = $exe != ""
    ASSERT_EQ $nonempty true
    "###
)]
#[example(
    name = "dynamic assembly",
    code = r###"
    # Assemble the child script dynamically: the parent interpolates
    # its own bindings into the pipe, then runs the interpreter on it.
    # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
    # so the child expands it with its own bindings.
    # The pipe delivers EOF when the producer step ends, so the child
    # reads exactly one script.
    IMPORT [STD]
    LET $exe: STRING = INTERPRETER()
    LET $who: STRING = "Ada"
    LET $child: PIPE
    WITH_IO [stdout=$child] ECHO """
        ECHO "hello {{ $who }}!"
        LET $who: STRING = "Grace"
        ECHO "child sees \{{ $who }}!"
        """
    LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
    ASSERT_CONTAINS $out "hello Ada!"
    ASSERT_CONTAINS $out "child sees Grace!"
    "###
)]
fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    if let Some(staged) = cx.state.io.interpreter_override() {
        return Ok(Value::string(staged));
    }
    Ok(Value::string(oxdock_process::interpreter_exe()?))
}

/// Report whether the current context is the entry script.
///
/// True at entry top level and inside entry-owned functions; false
/// inside module-owned functions and module init bodies. Lets a
/// library file double as a runnable demo: guard the demo with
/// `IF IS_MAIN()` so importing it stays side-effect free.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "main",
    code = r###"
    # Entry top level runs as main.
    IMPORT [STD]
    LET $m: BOOL = IS_MAIN()
    ASSERT_EQ $m true
    "###
)]
#[example(
    name = "library doubles as demo",
    fence_meta = "roots:unified",
    code = r###"
    # A library doubles as a runnable demo: guard the demo with
    # IF IS_MAIN() so importing it stays side effect free. The
    # parent writes both files, then runs each in a fresh
    # interpreter: direct execution prints the demo, importing
    # it does not. Unified roots: the child inherits one
    # workspace, so parent and child see the same files. The
    # exact stdout match proves the demo line stays out of the
    # importing run.
    IMPORT [STD]

    # The library under test: demo guarded by IS_MAIN.
    WRITE lib.oxfile """
        IMPORT [STD]
        FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
        EXPORT GREET
        IF IS_MAIN() {
            ECHO "demo: hi Ada"
        }
        """

    # The importer: calls the library, prints only its own line.
    WRITE main.oxfile """
        IMPORT ["lib.oxfile" AS LIB]
        LET $g: STRING = LIB::GREET("Bo")
        ECHO "imported: \{{ $g }}"
        """

    # Direct run executes the demo.
    LET $exe: STRING = INTERPRETER()
    LET $direct: STRING = RUN [$exe, "lib.oxfile"]
    ASSERT_CONTAINS $direct "demo: hi Ada"

    # Importing run stays silent apart from its own line.
    LET $via: STRING = RUN [$exe, "main.oxfile"]
    ASSERT_EQ $via "imported: hi Bo\n"
    "###
)]
fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> DiagnosticResult<Value> {
    let main = match cx.state.module_stack.last() {
        None | Some(None) => true,
        Some(Some(_)) => false,
    };
    Ok(Value::bool(main))
}

/// Report whether a standard stream is a terminal.
///
/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
/// answers for the step's stream as currently bound, so scripts can adapt
/// prompts, colors, and progress output. Anything diverted from the
/// terminal reports false without touching host handles: `WITH_IO` pipe
/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
/// runner sinks, and any materialized stdin stream (only a directly
/// inherited fd falls back to the process check). A transparent root tee
/// still answers the session question via the process check. The name
/// matches exactly (no case folding): anything else bails. AST-only:
/// reads the step context like the other introspection functions.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "null stdin",
    code = r###"
    # A null stdin is never a terminal, in every harness.
    IMPORT [STD]
    LET $term: BOOL = IS_TERMINAL("stdin")
    ASSERT_EQ $term false
    "###
)]
fn is_terminal<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
    #[values("stdin", "stdout", "stderr")]
    stream_name: String,
) -> DiagnosticResult<Value> {
    use std::io::IsTerminal;
    let terminal = match stream_name.as_str() {
        "stdin" => {
            // A script-pipe backend is definitive; Null is /dev/null.
            // Only a directly inherited fd answers the process check: a
            // materialized Stream is always a binding (staged input,
            // WITH_IO pipe, or OS half), never the raw fd.
            if cx.stdin_pipe.is_some() {
                false
            } else {
                match &cx.stdin {
                    CommandStdin::Null => false,
                    #[cfg(not(miri))]
                    CommandStdin::OsPipe(_) => false,
                    CommandStdin::Stream(_) => false,
                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
                }
            }
        }
        "stdout" => {
            if cx.out_pipe.is_some() {
                // WITH_IO script-pipe binding: never a terminal.
                false
            } else if cx.state.io.stdout().is_some() {
                // Staged runner sink: the root tee diverts bytes to the
                // sink only, never to real stdout.
                false
            } else {
                match &cx.out {
                    // Unbound: inherited straight through.
                    None => std::io::stdout().is_terminal(),
                    // OS kernel pipe: never a terminal.
                    #[cfg(not(miri))]
                    Some(StreamHandle::Os(_)) => false,
                    // Root tee (transparent: forwards to real stdout when
                    // unstaged, so terminal-ness survives) versus a genuine
                    // diversion. WITH_IO bindings never reach here (script
                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
                    // trip above). LET-capture cannot reach here either:
                    // assign_capture installs no sink for a bare NAME(...)
                    // call, so a direct query always observes the ambient
                    // routing. The process check answers the session
                    // question.
                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
                }
            }
        }
        "stderr" => {
            if cx.state.io.stderr().is_some() {
                // Staged runner sink: diverted, never a terminal.
                false
            } else {
                match &cx.err {
                    // Unbound: inherited straight through.
                    None => std::io::stderr().is_terminal(),
                    // OS kernel pipe: never a terminal.
                    #[cfg(not(miri))]
                    Some(StreamHandle::Os(_)) => false,
                    // Root never tees stderr and LET never captures it,
                    // so a bound handle here is always a WITH_IO binding.
                    Some(StreamHandle::Stream(_)) => false,
                }
            }
        }
        _ => {
            return Err(std_diag::std_is_terminal_expected(&stream_name));
        }
    };
    Ok(Value::bool(terminal))
}

/// Create a counting semaphore admitting at most `max` concurrent holders.
///
/// Non-positive maxima bail. The word names a shared backend: every clone
/// observes the same count, and admission runs through
/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
/// readout.
///
#[oxdock_func(returns = TypeTag::Semaphore)]
#[example(
    name = "mint",
    code = r###"
    # Mint a semaphore admitting at most two holders.
    IMPORT [STD]
    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)

    # A fresh semaphore reports its full cap as available.
    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
    ASSERT_EQ $free 2
    "###
)]
fn semaphore_new<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Maximum concurrent holders; must be positive.
    max: i64,
) -> DiagnosticResult<Value> {
    let _ = cx;
    if max <= 0 {
        return Err(std_diag::std_semaphore_needs_positive(max));
    }
    Ok(Value::semaphore(max as usize))
}

/// Attempt one non-blocking acquire, always answering a MAP.
///
/// `held` is `true` with the permit under the `permit` key, or `false`
/// with no `permit` key: branch on `$m.held` directly. The DSL has no
/// null, so the absent key is the miss shape. Do not read `$m.permit`
/// unless `held`: missing-key access bails strictly.
/// Never waits, so no wait can wedge.
///
#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
    name: "held".to_string(),
    ty: TypeTag::Bool,
    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
    optional: false,
    default: None,

    alias: None,}, Field {
    name: "permit".to_string(),
    ty: TypeTag::Permit,
    docs: "Permit handle; read only when `held`.",
    optional: true,
    default: None,

    alias: None,}])))]
#[example(
    name = "acquire",
    code = r###"
    # First acquire holds with a permit to bind.
    IMPORT [STD]
    LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
    LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
    ASSERT_EQ $first.held true
    LET $permit: PERMIT = $first.permit

    # A capped semaphore answers held false with no permit key.
    LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
    ASSERT_EQ $second.held false
    LET $has_permit: BOOL = HAS_KEY($second, "permit")
    ASSERT_EQ $has_permit false
    "###
)]
fn semaphore_try_acquire<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Semaphore handle from `SEMAPHORE_NEW`.
    sem: Arc<SemaphoreState>,
) -> DiagnosticResult<Value> {
    let _ = cx;
    let mut map = BTreeMap::new();
    if sem.try_acquire() {
        map.insert("held".to_string(), Value::bool(true));
        map.insert("permit".to_string(), Value::permit(&sem));
    } else {
        map.insert("held".to_string(), Value::bool(false));
    }
    Ok(Value::map(map))
}

/// Read free permits under the lock, with no mutation.
///
/// Observability only (audit lines, healthchecks: `active = max - free`).
/// Exact at read time and stale the instant the caller acts on it, so it
/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "readout",
    code = r###"
    # Hold one permit on a cap of two.
    IMPORT [STD]
    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
    LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
    ASSERT_EQ $acq.held true

    # One held permit leaves exactly one free.
    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
    ASSERT_EQ $free 1
    "###
)]
fn semaphore_available(
    /// Semaphore handle from `SEMAPHORE_NEW`.
    sem: Arc<SemaphoreState>,
) -> DiagnosticResult<Value> {
    Ok(Value::int(sem.available() as i64))
}

/// Trim Unicode whitespace from both ends of text.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes stream on a pump thread with O(chunk) memory: leading
/// whitespace falls at the stream head while trailing whitespace
/// holds in the spill substrate until the next segment proves it
/// interior, so unbounded streams never buffer unbounded memory.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_trim_string
)]
#[example(
    name = "trim",
    code = r###"
    # Leading and trailing whitespace falls away.
    IMPORT [STD]
    LET $clean: STRING = TEXT_TRIM("  hello  ")
    ASSERT_EQ $clean "hello"
    "###
)]
#[example(
    name = "trim pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same transform.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "  hello  "
    }
    LET $out: PIPE = TEXT_TRIM($cap)
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "hello"
    "###
)]
#[example(
    name = "trim template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM("  hello  ") }}'
    ASSERT_EQ $msg "clean:hello"
    "###
)]
#[example(
    name = "trim file template",
    code = r###"
    # EXPAND templates resolve the same registry.
    IMPORT [STD]
    WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\"  hello  \") }}"
    LET $out: STRING = EXPAND "tpl.txt"
    ASSERT_EQ $out "clean:hello"
    "###
)]
fn text_trim<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to trim.
    #[union(String, Pipe)]
    text: Value,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
}

/// Template projection of `TEXT_TRIM`: the same trim for `{{ }}`
/// placeholders, which carry no step IO for pipes.
fn text_trim_string(text: Value) -> DiagnosticResult<Value> {
    super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
}

/// Strip one leading prefix, returning the input unchanged when absent.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes decide on the first `prefix.len()` bytes and stream the rest
/// untouched. Matching is case-sensitive; there is no
/// case-insensitive mode.
/// Used for tag prefix strips such as `v1.2.3` to `1.2.3`.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_trim_prefix_string
)]
#[example(
    name = "strip prefix",
    code = r###"
    # A present prefix falls away; absence returns the input unchanged.
    IMPORT [STD]
    LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
    ASSERT_EQ $bare "1.2.3"

    # Missing prefixes pass through untouched.
    LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
    ASSERT_EQ $same "1.2.3"
    "###
)]
#[example(
    name = "strip prefix pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same strip.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "v1.2.3"
    }
    LET $trimmed: PIPE = TEXT_TRIM($cap)
    LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "1.2.3"
    "###
)]
#[example(
    name = "strip prefix template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
    ASSERT_EQ $msg "bare:1.2.3"
    "###
)]
fn text_trim_prefix<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to strip.
    #[union(String, Pipe)]
    text: Value,
    /// Leading prefix to remove once.
    prefix: String,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(
        cx,
        "TEXT_TRIM_PREFIX",
        &text,
        super::args::TextPump::TrimPrefix(prefix),
    )
}

/// Template projection of `TEXT_TRIM_PREFIX`: the same strip for
/// `{{ }}` placeholders, which carry no step IO for pipes.
fn text_trim_prefix_string(text: Value, prefix: String) -> DiagnosticResult<Value> {
    super::args::mirror_string(
        "TEXT_TRIM_PREFIX",
        &text,
        super::args::TextPump::TrimPrefix(prefix),
    )
}

/// Strip one trailing suffix, returning the input unchanged when absent.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes hold a `suffix.len()` trailing window and stream the rest.
/// Matching is case-sensitive; there is no case-insensitive mode.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_trim_suffix_string
)]
#[example(
    name = "strip suffix",
    code = r###"
    # A present suffix falls away; absence returns the input unchanged.
    IMPORT [STD]
    LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
    ASSERT_EQ $bare "archive.tar"

    # Missing suffixes pass through untouched.
    LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
    ASSERT_EQ $same "archive.tar"
    "###
)]
#[example(
    name = "strip suffix pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same strip.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "archive.tar.gz"
    }
    LET $trimmed: PIPE = TEXT_TRIM($cap)
    LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "archive.tar"
    "###
)]
#[example(
    name = "strip suffix template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
    ASSERT_EQ $msg "bare:archive.tar"
    "###
)]
fn text_trim_suffix<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to strip.
    #[union(String, Pipe)]
    text: Value,
    /// Trailing suffix to remove once.
    suffix: String,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(
        cx,
        "TEXT_TRIM_SUFFIX",
        &text,
        super::args::TextPump::TrimSuffix(suffix),
    )
}

/// Template projection of `TEXT_TRIM_SUFFIX`: the same strip for
/// `{{ }}` placeholders, which carry no step IO for pipes.
fn text_trim_suffix_string(text: Value, suffix: String) -> DiagnosticResult<Value> {
    super::args::mirror_string(
        "TEXT_TRIM_SUFFIX",
        &text,
        super::args::TextPump::TrimSuffix(suffix),
    )
}

/// Join a directory and a file name with the host-native separator.
///
/// Both inputs accept `STRING` or workspace `PATH` words; the result
/// is a `STRING` joined with the platform separator, so installers
/// never hand-roll separators in templates. No filesystem access:
/// missing parents fail later at the consumer. Stays `STRING` (not
/// `PATH`) on purpose: the joined value is a not-yet-validated
/// destination string like `$dir` itself, and `PATH` words
/// re-canonicalize to forward slashes on template expansion, which
/// would undo the native join.
#[oxdock_func(returns = TypeTag::String)]
#[example(
    name = "join path",
    code = r###"
    # Directory and file stem join with the native separator.
    # Source `\\` is one backslash at runtime; `/` works on Windows
    # too, native just reads better there.
    IMPORT [STD]
    LET $p: STRING = PATH_JOIN("some-dir", "some-file")
    [family:unix] ASSERT_EQ $p "some-dir/some-file"
    [family:windows] ASSERT_EQ $p "some-dir\\some-file"
    "###
)]
fn path_join<P: ProcessManager>(
    _cx: &mut StepCtx<P>,
    /// Directory half of the destination.
    #[union(String, Path)]
    dir: Value,
    /// File half of the destination.
    #[union(String, Path)]
    name: Value,
) -> DiagnosticResult<Value> {
    let d = super::args::string_or_path_text(&dir)?;
    let n = super::args::string_or_path_text(&name)?;
    Ok(Value::string(oxdock_fs::join_native(&d, &n)))
}

/// Final segment of a path (`PATH_BASE`).
///
/// Pure lexical surgery with no filesystem access: backslashes normalize
/// to slashes, trailing slashes trim (root stays `/`), then the text
/// after the last slash binds. Empty input fails closed. Runs in
/// templates like every pure builtin.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "base",
    code = r###"
    # Final segments bind without filesystem access.
    IMPORT [STD]
    LET $b: STRING = PATH_BASE("some-dir/some-file")
    ASSERT_EQ $b "some-file"

    # Trailing slashes trim before the split.
    LET $d: STRING = PATH_BASE("some-dir/")
    ASSERT_EQ $d "some-dir"
    "###
)]
fn path_base(
    /// Path whose final segment to bind.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let text = super::args::string_or_path_text(&path)?;
    let base = oxdock_fs::path_base(&text).map_err(|e| std_diag::std_path_base_failed(&e))?;
    Ok(Value::string(base))
}

/// Lexical relativization (`PATH_REL`): remainder of a path below a base.
///
/// Pure string surgery with no filesystem access: both sides normalize
/// backslashes to slashes and trim trailing slashes, then `base`
/// segments must prefix `path` segments on a segment boundary. Equal
/// paths bind `.`; non-prefix inputs fail closed naming both sides.
/// Absolute and relative shapes never mix. Runs in templates like
/// every pure builtin.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "relativize",
    code = r###"
    # Prefix bases strip to their remainder.
    IMPORT [STD]
    LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
    ASSERT_EQ $r "some-file"

    # Equal paths bind dot.
    LET $dot: STRING = PATH_REL("some-dir", "some-dir")
    ASSERT_EQ $dot "."
    "###
)]
fn path_rel(
    /// Base prefix segments must match.
    #[union(String, Path)]
    base: Value,
    /// Path below the base to relativize.
    #[union(String, Path)]
    path: Value,
) -> DiagnosticResult<Value> {
    let b = super::args::string_or_path_text(&base)?;
    let p = super::args::string_or_path_text(&path)?;
    let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| std_diag::std_path_rel_failed(&e))?;
    Ok(Value::string(rel))
}

/// Uppercase text with full Unicode mapping.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes map chunk by chunk across a char-boundary carry, so
/// multibyte characters split across reads still fold correctly.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_to_upper_string
)]
#[example(
    name = "uppercase",
    code = r###"
    # Text folds to uppercase.
    IMPORT [STD]
    LET $loud: STRING = TEXT_TO_UPPER("hello")
    ASSERT_EQ $loud "HELLO"
    "###
)]
#[example(
    name = "uppercase pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same fold.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "hello"
    }
    LET $out: PIPE = TEXT_TO_UPPER($cap)
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "HELLO"
    "###
)]
#[example(
    name = "uppercase template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
    ASSERT_EQ $msg "loud:HELLO"
    "###
)]
fn text_to_upper<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to uppercase.
    #[union(String, Pipe)]
    text: Value,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
}

/// Template projection of `TEXT_TO_UPPER`: the same fold for `{{ }}`
/// placeholders, which carry no step IO for pipes.
fn text_to_upper_string(text: Value) -> DiagnosticResult<Value> {
    super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
}

/// Lowercase text with full Unicode mapping.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes map chunk by chunk across a char-boundary carry, like
/// `TEXT_TO_UPPER`.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_to_lower_string
)]
#[example(
    name = "lowercase",
    code = r###"
    # Text folds to lowercase.
    IMPORT [STD]
    LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
    ASSERT_EQ $quiet "hello"
    "###
)]
#[example(
    name = "lowercase pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same fold.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "HELLO"
    }
    LET $out: PIPE = TEXT_TO_LOWER($cap)
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "hello"
    "###
)]
#[example(
    name = "lowercase template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
    ASSERT_EQ $msg "quiet:hello"
    "###
)]
fn text_to_lower<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to lowercase.
    #[union(String, Pipe)]
    text: Value,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
}

/// Template projection of `TEXT_TO_LOWER`: the same fold for `{{ }}`
/// placeholders, which carry no step IO for pipes.
fn text_to_lower_string(text: Value) -> DiagnosticResult<Value> {
    super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
}

/// Replace every literal occurrence of `from` with `to`.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Pipes scan through a `from.len()` sliding window, so needles split
/// across chunk reads still rewrite.
/// Literal sliding search, not a pattern: an empty `from` fails
/// closed, and regex work with captures belongs to
/// `TEXT_REPLACE_REGEX`. Matching is case-sensitive; there is no
/// case-insensitive mode.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_replace_string
)]
#[example(
    name = "replace",
    code = r###"
    # Every literal occurrence rewrites in place.
    IMPORT [STD]
    LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
    ASSERT_EQ $fixed "hello there"
    "###
)]
#[example(
    name = "replace pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same rewrite.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "hello world"
    }
    LET $trimmed: PIPE = TEXT_TRIM($cap)
    LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "hello there"
    "###
)]
#[example(
    name = "replace template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
    ASSERT_EQ $msg "fixed:hello there"
    "###
)]
fn text_replace<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to rewrite.
    #[union(String, Pipe)]
    text: Value,
    /// Literal text to search for; empty fails closed.
    from: String,
    /// Literal replacement text.
    to: String,
) -> DiagnosticResult<Value> {
    super::args::mirror_stream(
        cx,
        FUNC_TEXT_REPLACE,
        &text,
        super::args::TextPump::ReplaceLiteral { from, to },
    )
}

/// Template projection of `TEXT_REPLACE`: the same rewrite for `{{ }}`
/// placeholders, which carry no step IO for pipes.
fn text_replace_string(text: Value, from: String, to: String) -> DiagnosticResult<Value> {
    super::args::mirror_string(
        FUNC_TEXT_REPLACE,
        &text,
        super::args::TextPump::ReplaceLiteral { from, to },
    )
}

/// Replace every regex match, expanding `$1` and `$name` captures.
///
/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
/// Eager-only framing: matches span chunks, so pipe inputs stage
/// through the spill substrate instead of streaming.
/// Bad patterns fail closed naming the pattern and its position.
/// Matching is case-sensitive unless the pattern carries an inline
/// `(?i)` flag, which makes uppercase and lowercase letters match
/// each other.
/// The literal counterpart is `TEXT_REPLACE`.
///
#[oxdock_func(
    rpn,
    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
    template = text_replace_regex_string
)]
#[example(
    name = "replace with captures",
    code = r###"
    # Capture groups expand in the replacement.
    IMPORT [STD]
    LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
    ASSERT_EQ $swapped "13/10/2026"
    "###
)]
#[example(
    name = "replace regex pipe mirrors",
    code = r###"
    # Pipe input mints pipe output with the same rewrite.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "2026-10-13"
    }
    LET $trimmed: PIPE = TEXT_TRIM($cap)
    LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
    WITH_IO [stdin=$out] READ_LINE $line
    ASSERT_EQ $line "13/10/2026"
    "###
)]
#[example(
    name = "replace regex template",
    code = r###"
    # String inputs run inside placeholders too.
    IMPORT [STD]
    LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
    ASSERT_EQ $msg "swapped:13/10/2026"
    "###
)]
fn text_replace_regex<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Text to rewrite.
    #[union(String, Pipe)]
    text: Value,
    /// Regex pattern to match.
    pattern: String,
    /// Replacement with `$1` and `$name` capture expansion.
    replacement: String,
) -> DiagnosticResult<Value> {
    if let Some(s) = text.as_str() {
        let out = super::args::text_replace_regex_str(
            s,
            &pattern,
            &replacement,
            FUNC_TEXT_REPLACE_REGEX,
        )?;
        return Ok(Value::string(out));
    }
    let content = super::args::read_pipe_eager(cx, FUNC_TEXT_REPLACE_REGEX, &text)?;
    let out = super::args::text_replace_regex_str(
        &content,
        &pattern,
        &replacement,
        FUNC_TEXT_REPLACE_REGEX,
    )?;
    super::args::write_completed_pipe(cx, FUNC_TEXT_REPLACE_REGEX, out)
}

/// Template projection of `TEXT_REPLACE_REGEX`: the same rewrite for
/// `{{ }}` placeholders, which carry no step IO for pipes.
fn text_replace_regex_string(
    text: Value,
    pattern: String,
    replacement: String,
) -> DiagnosticResult<Value> {
    let Some(s) = text.as_str() else {
        return Err(std_diag::std_pipe_needs_step_io(FUNC_TEXT_REPLACE_REGEX));
    };
    let out =
        super::args::text_replace_regex_str(s, &pattern, &replacement, FUNC_TEXT_REPLACE_REGEX)?;
    Ok(Value::string(out))
}

/// Split text on a literal delimiter into a `LIST<STRING>`.
///
/// An empty delimiter splits into single characters. Eager-only by
/// design: splitting into a list has no line framing to stream.
/// Delimiters match case-sensitively; there is no
/// case-insensitive mode.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "split",
    code = r###"
    # Delimiters split into list items.
    IMPORT [STD]
    LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
    ASSERT_EQ $parts.0 "a"
    ASSERT_EQ $parts.1 "b"
    ASSERT_EQ $parts.2 "c"
    "###
)]
fn text_split(
    /// Text to split.
    text: String,
    /// Literal delimiter; empty splits into characters.
    delimiter: String,
) -> DiagnosticResult<Value> {
    Ok(super::args::text_list_value(super::args::text_split_str(
        &text, &delimiter,
    )))
}

/// Join a `LIST<STRING>` with a literal separator into a `STRING`.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "join",
    code = r###"
    # List items join with the separator between them.
    IMPORT [STD]
    LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
    ASSERT_EQ $joined "a,b,c"
    "###
)]
fn text_join(
    /// List elements to join.
    elements: Vec<String>,
    /// Literal delimiter placed between elements.
    delimiter: String,
) -> DiagnosticResult<Value> {
    Ok(Value::string(elements.join(delimiter.as_str())))
}

/// Split a shell command string into argv words.
///
/// Parses POSIX shell word syntax (single and double quotes, backslash
/// escapes) with the `shell-words` crate, the same splitter the remote
/// plugins use. Returns a `LIST<STRING>`. Unbalanced quotes fail.
/// Inverse of `SHELL_JOIN_ARGS`: joining the result re-splits
/// to the same words.
///
/// Shell syntax only: plain prose with no quoting splits on
/// whitespace like any shell would, which is rarely what prose wants.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "split args",
    code = r###"
    # Quoted segments stay one word.
    IMPORT [STD]
    LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
    ASSERT_EQ $argv.0 "gh"
    ASSERT_EQ $argv.3 "153"
    ASSERT_EQ $argv.5 "notes.md"

    # Quotes and escapes parse the shell way.
    LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
    ASSERT_EQ $quoted.0 "say"
    ASSERT_EQ $quoted.1 "hi there"
    ASSERT_EQ $quoted.2 "a b"
    "###
)]
fn shell_split_args(
    /// Shell command string to split into words.
    command: String,
) -> DiagnosticResult<Value> {
    match shell_words::split(&command) {
        Ok(words) => Ok(super::args::text_list_value(words)),
        Err(err) => Err(std_diag::std_shell_split_failed(&err)),
    }
}

/// Join argv words into one shell-parseable string.
///
/// Quotes each word with POSIX single-quote escaping through the
/// `shell-words` crate, so the result re-splits to the same words.
/// Inverse of `SHELL_SPLIT_ARGS` on the word side: splitting the
/// result returns the input list unchanged.
///
#[oxdock_func(pure, returns = TypeTag::String)]
#[example(
    name = "join args",
    code = r###"
    # Plain words join with spaces and no quoting.
    IMPORT [STD]
    LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
    ASSERT_EQ $plain "gh issue list"

    # Words with spaces quote, and the round trip is exact.
    LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
    LET $joined: STRING = SHELL_JOIN_ARGS($words)
    LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
    ASSERT_EQ $back.0 "say"
    ASSERT_EQ $back.1 "hi there"
    ASSERT_EQ $back.2 "a'b"
    "###
)]
fn shell_join_args(
    /// Words to join into a shell command string.
    words: Vec<String>,
) -> DiagnosticResult<Value> {
    Ok(Value::string(shell_words::join(&words)))
}

/// Split text into lines with universal newline handling.
///
/// Normalizes through the line-ending crate first so LF, CRLF, CR,
/// and mixed endings all split, then delegates the split itself to
/// `LineEnding::split` instead of hand-rolled scanning.
/// Returns a `LIST<STRING>`; eager-only like `TEXT_SPLIT`.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "lines",
    code = r###"
    # Newlines split into line items.
    IMPORT [STD]
    LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
    ASSERT_EQ $lines.0 "one"
    ASSERT_EQ $lines.1 "two"
    ASSERT_EQ $lines.2 "three"

    # Windows endings split the same way after normalization.
    LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
    ASSERT_EQ $crlf.0 "one"
    ASSERT_EQ $crlf.1 "two"
    ASSERT_EQ $crlf.2 "three"

    # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
    LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
    ASSERT_EQ $mixed.0 "a"
    ASSERT_EQ $mixed.1 "b"
    ASSERT_EQ $mixed.2 "c"
    ASSERT_EQ $mixed.3 "d"
    "###
)]
fn text_lines(
    /// Text to split into lines.
    text: String,
) -> DiagnosticResult<Value> {
    Ok(super::args::text_list_value(super::args::text_lines_str(
        &text,
    )))
}

/// Split text into whitespace-separated fields, ignoring empties.
///
/// Returns a `LIST<STRING>`; the checksum-line parser that replaces
/// `cut -d' ' -f1` in CI legs.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "fields",
    code = r###"
    # Runs of whitespace separate fields; empties never appear.
    IMPORT [STD]
    LET $fields: LIST<STRING> = TEXT_FIELDS("  abc  def ")
    ASSERT_EQ $fields.0 "abc"
    ASSERT_EQ $fields.1 "def"
    "###
)]
fn text_fields(
    /// Text to split into fields.
    text: String,
) -> DiagnosticResult<Value> {
    Ok(super::args::text_list_value(super::args::text_fields_str(
        &text,
    )))
}

/// Read lines `from` through `to` as a `LIST<STRING>`: the `sed -n
/// 'A,Bp'` window over universal newlines, for reading one file
/// section without holding the surrounding text.
///
/// Lines are 1-based and inclusive on both ends. Ranges past the end
/// clamp like sed instead of failing; a start before line 1 or past
/// `to` fails closed, since no line reading satisfies it.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "line range",
    code = r###"
    # Lines 2 through 3 come back as a list, 1-based inclusive.
    IMPORT [STD]
    LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
    ASSERT_EQ $window.0 "two"
    ASSERT_EQ $window.1 "three"

    # Ranges past the end clamp instead of failing.
    LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
    ASSERT_EQ $tail.0 "two"
    "###
)]
fn text_lines_range(
    /// Text whose lines to window.
    text: String,
    /// First line, 1-based inclusive.
    from: i64,
    /// Last line, inclusive; past the end clamps.
    to: i64,
) -> DiagnosticResult<Value> {
    Ok(super::args::text_list_value(
        super::args::text_lines_range_str(&text, from, to, FUNC_TEXT_LINES_RANGE)?,
    ))
}

/// Report whether text matches a regex pattern.
///
/// Returns `BOOL`. Bad patterns fail closed naming the pattern and
/// its position. Matching is case-sensitive unless the pattern
/// carries an inline `(?i)` flag, which makes uppercase and lowercase
/// letters match each other.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "match",
    code = r###"
    # Regex matches report true; misses report false.
    IMPORT [STD]
    LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
    ASSERT_EQ $hit true

    # A miss is false, not a failure.
    LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
    ASSERT_EQ $miss false
    "###
)]
fn text_match(
    /// Text to test.
    text: String,
    /// Regex pattern to match.
    pattern: String,
) -> DiagnosticResult<Value> {
    let re = super::args::text_compile_pattern(FUNC_TEXT_MATCH, &pattern)?;
    Ok(Value::bool(re.is_match(&text)))
}

/// Convert a value to BOOL.
///
/// Trims ASCII whitespace; accepts `true`/`false`, `1`/`0`,
/// `yes`/`no`, `on`/`off` in any case. Passes Bool through. Empty
/// and anything else fail: an empty string is not a boolean, so
/// absent env names (which read empty) must go through `BOOL_OR`
/// with a stated default instead of converting here.
///
#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
#[example(
    name = "convert",
    code = r###"
    IMPORT [STD]
    LET $n: BOOL = BOOL("yes")
    ASSERT_EQ $n true
    LET $f: BOOL = BOOL("0")
    ASSERT_EQ $f false
    "###
)]
fn bool_convert(
    /// Value to convert to `BOOL`.
    #[union(Bool, String)]
    val: Value,
) -> DiagnosticResult<Value> {
    if let Some(b) = val.as_bool() {
        return Ok(Value::bool(b));
    }
    let Some(s) = val.as_str() else {
        return Err(std_diag::std_bool_needs_bool_or_string(&val));
    };
    match super::args::parse_bool_str(s) {
        Some(b) => Ok(Value::bool(b)),
        None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL, s)),
    }
}

/// Coerce text to `BOOL`, substituting a default for empty.
///
/// Returns `BOOL`. Blank input (a declared-but-absent env name, which
/// reads empty) resolves to `default` instead of failing, so each flag
/// site states its own absent polarity explicitly: negative-polarity
/// flags (`dry_run`) default true, positive ones default false. No
/// implicit polarity lives in the coercion. Non-blank garbage still
/// fails naming the input, exactly like `LET $x: BOOL` coercion.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "absent-default",
    code = r###"
    # Absent names read empty; the default settles the polarity.
    IMPORT [STD]
    INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
    LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
    ASSERT_EQ $dry true

    # Present values coerce strictly, ignoring the default.
    LET $off: BOOL = BOOL_OR("false", true)
    ASSERT_EQ $off false
    "###
)]
fn bool_or(
    /// Text to coerce (`true`/`false`, `1`/`0`, `yes`/`no`/`on`/`off`, any case).
    text: String,
    /// Absent-value default, used when the text is blank.
    default: bool,
) -> DiagnosticResult<Value> {
    if text.trim().is_empty() {
        return Ok(Value::bool(default));
    }
    match super::args::parse_bool_str(&text) {
        Some(b) => Ok(Value::bool(b)),
        None => Err(std_diag::std_bool_cannot_coerce(FUNC_BOOL_OR, &text)),
    }
}

/// Extract capture groups for the first regex match.
///
/// Returns a `LIST<STRING>` where index 0 is the full match and the
/// rest are groups in order; non-participating groups bind empty so
/// indexes stay stable. No match binds an empty list. Matching is
/// case-sensitive unless the pattern carries an inline `(?i)` flag,
/// which makes uppercase and lowercase letters match each other.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "extract",
    code = r###"
    # Index zero is the full match; groups follow in order.
    IMPORT [STD]
    LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
    ASSERT_EQ $caps.0 "abc123"
    ASSERT_EQ $caps.1 "abc"
    ASSERT_EQ $caps.2 "123"
    "###
)]
fn text_extract(
    /// Text to search.
    text: String,
    /// Regex pattern with capture groups.
    pattern: String,
) -> DiagnosticResult<Value> {
    let groups = super::args::text_extract_str(&text, &pattern, FUNC_TEXT_EXTRACT)?;
    Ok(super::args::text_list_value(groups))
}

/// Report whether text starts with a literal prefix.
///
/// Returns `BOOL`; the literal check behind tag and target branching
/// such as `matrix.target` suffix and prefix tests. Matching is
/// case-sensitive; there is no case-insensitive mode.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "starts with",
    code = r###"
    # Present prefixes report true; misses report false.
    IMPORT [STD]
    LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
    ASSERT_EQ $hit true

    # A miss is false, not a failure.
    LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
    ASSERT_EQ $miss false
    "###
)]
fn text_starts_with(
    /// Text to test.
    text: String,
    /// Literal prefix to look for.
    prefix: String,
) -> DiagnosticResult<Value> {
    Ok(Value::bool(text.starts_with(prefix.as_str())))
}

/// Report whether text ends with a literal suffix.
///
/// Returns `BOOL`; the `endsWith(matrix.target, 'linux-musl')`
/// check in CI legs. Matching is case-sensitive; there is no
/// case-insensitive mode.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "ends with",
    code = r###"
    # Present suffixes report true; misses report false.
    IMPORT [STD]
    LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
    ASSERT_EQ $hit true

    # A miss is false, not a failure.
    LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
    ASSERT_EQ $miss false
    "###
)]
fn text_ends_with(
    /// Text to test.
    text: String,
    /// Literal suffix to look for.
    suffix: String,
) -> DiagnosticResult<Value> {
    Ok(Value::bool(text.ends_with(suffix.as_str())))
}

/// Report whether a `STRING` holds a substring or a `LIST` holds a member.
///
/// Dispatches on the haystack like `LEN`: `STRING` does a literal
/// substring search (case-sensitive, no case-insensitive mode);
/// `LIST<ANY>` compares members with strict `values_equal` (numeric
/// `INT` and `FLOAT` compare across types, every other cross-type pair
/// is unequal, matching `SWITCH`). Returns `BOOL`; misses are false,
/// never failures.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
#[example(
    name = "contains",
    code = r###"
    # Present needles report true; misses report false.
    IMPORT [STD]
    LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
    ASSERT_EQ $hit true

    # A miss is false, not a failure.
    LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
    ASSERT_EQ $miss false
    "###
)]
#[example(
    name = "contains list",
    code = r###"
    # List membership uses strict equality across any element type.
    IMPORT [STD]
    LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
    ASSERT_EQ $hit true
    LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
    ASSERT_EQ $miss false
    LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
    ASSERT_EQ $num true

    # Stringified numbers never coerce to integers.
    LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
    ASSERT_EQ $strnum false

    # Boolean lists match true and miss false with no coercion.
    LET $bools: LIST<BOOL> = [true]
    LET $bhit: BOOL = CONTAINS($bools, true)
    ASSERT_EQ $bhit true
    LET $bmiss: BOOL = CONTAINS($bools, false)
    ASSERT_EQ $bmiss false
    LET $nocoerce: BOOL = CONTAINS($bools, 1)
    ASSERT_EQ $nocoerce false
    "###
)]
fn contains(
    /// Text to search or list to probe.
    #[union(String, List)]
    haystack: Value,
    /// Literal substring or member to look for.
    needle: Value,
) -> DiagnosticResult<Value> {
    if let Some(text) = haystack.as_str() {
        let Some(n) = needle.as_str() else {
            return Err(std_diag::std_contains_needle_type(needle.type_name()));
        };
        return Ok(Value::bool(text.contains(n)));
    }
    if let Some(items) = haystack.as_list() {
        for item in items {
            if super::args::values_equal(item, &needle) {
                return Ok(Value::bool(true));
            }
        }
        return Ok(Value::bool(false));
    }
    Err(std_diag::std_contains_haystack_type(haystack.type_name()))
}

/// Deduplicate a `LIST`, keeping the first occurrence of each member.
///
/// Membership uses strict `values_equal` (numeric `INT` and `FLOAT`
/// compare across types, every other cross-type pair is unequal,
/// matching `CONTAINS` and `==`), so `[1, 1.0]` collapses to one
/// element while `["1", 1]` keeps both. Order is first occurrence;
/// the empty list binds empty, never failing.
#[oxdock_func(pure, returns = TypeTag::List)]
#[example(
    name = "deduplicate",
    code = r###"
    # First occurrences win, later repeats drop.
    IMPORT [STD]
    LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
    ASSERT_EQ $seen.0 "a"
    ASSERT_EQ $seen.1 "b"
    ASSERT_EQ $seen.2 "c"
    ASSERT_EQ LEN($seen) 3

    # The empty list stays empty.
    LET $empty: LIST<STRING> = UNIQUE([])
    ASSERT_EQ LEN($empty) 0
    "###
)]
#[example(
    name = "strict membership",
    code = r###"
    # Numerics collapse across INT and FLOAT like CONTAINS.
    IMPORT [STD]
    LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
    ASSERT_EQ $nums.0 1
    ASSERT_EQ $nums.1 2.0
    ASSERT_EQ $nums.2 3
    ASSERT_EQ LEN($nums) 3

    # Stringified numbers never coerce to integers.
    LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
    ASSERT_EQ $mixed.0 "1"
    ASSERT_EQ $mixed.1 1
    ASSERT_EQ LEN($mixed) 2
    "###
)]
fn unique(
    /// List to deduplicate.
    items: Vec<Value>,
) -> DiagnosticResult<Value> {
    let mut out: Vec<Value> = Vec::with_capacity(items.len());
    for item in items {
        if !out
            .iter()
            .any(|seen| super::args::values_equal(seen, &item))
        {
            out.push(item);
        }
    }
    Ok(Value::list(out))
}

/// Count the elements of a text, list, or map as an `INT`.
///
/// Strings count Unicode scalars: multibyte characters count once
/// each, so this is not the byte length (`"héllo"` binds 5, not 6).
/// Lists count elements, maps count entries; empty values bind 0.
/// The `${#var}` and `wc -m` counterpart for scripts that size tags,
/// digests, and table rows.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "length",
    code = r###"
    # Plain text counts one per character.
    IMPORT [STD]
    LET $n: INT = LEN("hello")
    ASSERT_EQ $n 5

    # Multibyte characters count once each, not per byte.
    LET $wide: INT = LEN("héllo")
    ASSERT_EQ $wide 5

    # Lists count elements, maps count entries.
    LET $items: LIST<STRING> = ["a", "b", "c"]
    LET $nitems: INT = LEN($items)
    ASSERT_EQ $nitems 3
    LET $row: MAP<name: STRING> = {name: "ada"}
    LET $nkeys: INT = LEN($row)
    ASSERT_EQ $nkeys 1
    LET $empty: INT = LEN([])
    ASSERT_EQ $empty 0
    "###
)]
fn len(
    /// Value to measure.
    #[union(String, List, Map)]
    value: Value,
) -> DiagnosticResult<Value> {
    if let Some(text) = value.as_str() {
        return Ok(Value::int(text.chars().count() as i64));
    }
    if let Some(items) = value.as_list() {
        return Ok(Value::int(items.len() as i64));
    }
    if let Some(entries) = value.as_map() {
        return Ok(Value::int(entries.len() as i64));
    }
    Err(std_diag::std_len_unexpected_type(value.type_name()))
}

/// Count non-overlapping literal occurrences of a needle.
///
/// Matches never share bytes, so `"aaa"` holds one `"aa"`, matching
/// `grep -o 'aa' | wc -l`. An empty needle fails closed instead of
/// binding every character boundary. Matching is case-sensitive;
/// there is no case-insensitive mode.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "count",
    code = r###"
    # Every non-overlapping occurrence counts once.
    IMPORT [STD]
    LET $n: INT = TEXT_COUNT("hello world", "o")
    ASSERT_EQ $n 2

    # Overlapping candidates never double count.
    LET $once: INT = TEXT_COUNT("aaa", "aa")
    ASSERT_EQ $once 1
    "###
)]
fn text_count(
    /// Text to search.
    text: String,
    /// Literal needle to count; empty fails closed.
    needle: String,
) -> DiagnosticResult<Value> {
    let n = super::args::text_count_str(&text, &needle, FUNC_TEXT_COUNT)?;
    Ok(Value::int(n))
}

/// Count lines matching a regex pattern.
///
/// Lines split with universal newline handling, like `TEXT_LINES`,
/// and each line reports independently: this is `grep -c`, so a line
/// with two matches still counts once. Bad patterns fail closed
/// naming the pattern and its position. Matching is case-sensitive
/// unless the pattern carries an inline `(?i)` flag, which makes
/// uppercase and lowercase letters match each other.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
#[example(
    name = "count matches",
    code = r###"
    # One line matches once no matter how many times it hits.
    IMPORT [STD]
    LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
    ASSERT_EQ $n 2

    # A miss binds zero, never an error.
    LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
    ASSERT_EQ $none 0
    "###
)]
fn text_count_matches(
    /// Text whose lines to test.
    text: String,
    /// Regex pattern tested per line.
    pattern: String,
) -> DiagnosticResult<Value> {
    let n = super::args::text_count_matches_str(&text, &pattern, FUNC_TEXT_COUNT_MATCHES)?;
    Ok(Value::int(n))
}

/// Keep the lines matching a regex pattern.
///
/// Splits with universal newline handling, like `TEXT_LINES`, and
/// returns every matching line in order: plain `grep`, so a miss
/// binds an empty list instead of failing. A trailing options MAP
/// carries `invert`: `TEXT_GREP($text, $pattern, {invert: true})`
/// keeps every non-matching line instead, the `grep -v` shape. The
/// MAP omits freely; a missing MAP keeps matches. Matching is
/// case-sensitive unless the pattern carries an inline `(?i)` flag,
/// which makes uppercase and lowercase letters match each other. Bad
/// patterns fail closed naming the pattern and its position.
///
#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
#[example(
    name = "grep",
    code = r###"
    # Matching lines come back as a list, in order.
    IMPORT [STD]
    LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
    ASSERT_EQ $hits.0 "one"
    ASSERT_EQ $hits.1 "one more"

    # A miss binds an empty list, never an error.
    LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
    LET $joined: STRING = TEXT_JOIN($miss, ",")
    ASSERT_EQ $joined ""

    # The (?i) flag ignores case, so uppercase lines match too.
    LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
    ASSERT_EQ $folded.0 "One"
    ASSERT_EQ $folded.1 "ONE more"
    "###
)]
#[example(
    name = "grep invert",
    code = r###"
    # The invert option keeps every non-matching line instead.
    IMPORT [STD]
    LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
    ASSERT_EQ $kept.0 "two"

    # A pattern matching every line binds an empty list, never an error.
    LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
    LET $joined: STRING = TEXT_JOIN($none, ",")
    ASSERT_EQ $joined ""

    # Options ride into placeholders as MAP literals. Placeholder
    # strings unescape only backslash and quote, so multiline text
    # arrives through a variable.
    LET $two_lines: STRING = "one\ntwo"
    LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
    ASSERT_EQ $msg "kept:two"
    "###
)]
fn text_grep(
    /// Text whose lines to filter.
    text: String,
    /// Regex pattern keeping a line.
    pattern: String,
    /// Filter settings: `invert`. Omittable: a missing options MAP fills `{}`.
    #[options("invert?: BOOL")]
    #[optional]
    options: BTreeMap<String, Value>,
) -> DiagnosticResult<Value> {
    // `check_options` in the wrapper verified the shape above (keys
    // and value types); the read below narrows infallibly after.
    let invert = super::args::text_invert_flag(&options);
    Ok(super::args::text_list_value(super::args::text_grep_str(
        &text,
        &pattern,
        invert,
        FUNC_TEXT_GREP,
    )?))
}

/// True when a pipe sits at end of stream: closed with nothing buffered,
/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
/// Live writers, pinned keepers, and buffered bytes all answer false.
/// Never blocks: a reader already blocked stays blocked, so branch on
/// `EOF` before reading, not after. OS pairs and unbound handles answer
/// best-effort (kernel bytes are invisible there; see `INSPECT`).
/// Non-pipe arguments bail at the boundary: the parameter declares
/// `PIPE`, so the extractor and the static pass reject them before
/// the body runs.
///
#[oxdock_func(returns = TypeTag::Bool)]
#[example(
    name = "drain to end",
    code = r###"
    # Capture two lines, then drain to end of stream with no sentinel line.
    IMPORT [STD]
    LET $cap: PIPE
    WITH_IO [stdout=$cap] {
        ECHO "one"
        ECHO "two"
    }

    # The loop exits on close, and the count proves both lines drained.
    LET $n: INT = 0
    WHILE !EOF($cap) {
        WITH_IO [stdin=$cap] READ_LINE $line
        $n = $n + 1
    }
    ASSERT_EQ $n 2
    "###
)]
fn eof<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Pipe handle to query for end of stream.
    pipe: PipeHandle,
) -> DiagnosticResult<Value> {
    let info = cx.state.io.inspect_pipe(&pipe);
    Ok(Value::bool(info.closed && info.buffered == 0))
}

/// Field table for the `TASK_POLL` result map. Shared by the declared
/// return tag and the generated schema and reference docs, so the
/// shape agents see is the shape the builtin builds.
fn task_poll_result_fields() -> Arc<[Field]> {
    Arc::from(vec![
        Field {
            name: "state".to_string(),
            ty: TypeTag::String,
            docs: "Task phase: `running` or `finished`.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: "ok".to_string(),
            ty: TypeTag::Bool,
            docs: "True unless the task failed.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: "stdout_tail".to_string(),
            ty: TypeTag::String,
            docs: "Bounded stdout tail, live while running.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: "stderr_tail".to_string(),
            ty: TypeTag::String,
            docs: "Bounded stderr tail, live while running.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: "truncated_bytes".to_string(),
            ty: TypeTag::Int,
            docs: "Dropped head bytes past the per-stream cap.",
            optional: false,
            default: None,

            alias: None,
        },
        Field {
            name: "exit_code".to_string(),
            ty: TypeTag::Int,
            docs: "Process exit code, present once finished.",
            optional: true,
            default: None,

            alias: None,
        },
        Field {
            name: "result".to_string(),
            ty: TypeTag::Any,
            docs: "Task `RETURN` value, present on clean finish.",
            optional: true,
            default: None,

            alias: None,
        },
        Field {
            name: "error".to_string(),
            ty: TypeTag::String,
            docs: "Failure text, present on failed finish.",
            optional: true,
            default: None,

            alias: None,
        },
    ])
}

/// Poll a background task without consuming it.
///
/// Reports the running state, the output tails accumulated so far,
/// and the final outcome once finished. Repeated polls are safe, and
/// a later `AWAIT` still joins normally. Polling after `AWAIT` fails
/// like double-await: the handle is spent.
///
/// Map keys: `state` always names the phase (`"running"` or
/// `"finished"`); `ok` is true unless the task failed; `stdout_tail`
/// and `stderr_tail` carry bounded output with `truncated_bytes`
/// counting dropped head bytes. Finished tasks add `exit_code`;
/// clean finishes add `result`, failed ones add `error` instead.
#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
#[example(
    name = "running poll",
    code = r###"
    # A sleeping task is still running on the first poll.
    IMPORT [STD]
    LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
    LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
    ASSERT_EQ $m.state "running"
    ASSERT_EQ $m.ok true
    # Clean up the sleeper so the run ends promptly.
    CANCEL $t
    "###
)]
#[example(
    name = "finished poll",
    code = r###"
    # A finished task reports its value and final tails, then still awaits.
    IMPORT [STD]
    LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
    # Do other work while the task runs; poll once it should be done.
    SLEEP 2s
    LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
    ASSERT_EQ $m.state "finished"
    ASSERT_EQ $m.result "done"
    LET $o: STRING = AWAIT $t
    ASSERT_EQ $o "done"
    "###
)]
fn task_poll<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Task handle from ASYNC.
    task: HandleValue,
) -> DiagnosticResult<Value> {
    let entry =
        super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
    let obs = entry.observe_completion();
    let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
    let mut out = BTreeMap::new();
    out.insert(
        "state".to_string(),
        Value::string(if obs.running { "running" } else { "finished" }.to_string()),
    );
    out.insert("ok".to_string(), Value::bool(obs.ok));
    if !obs.running {
        out.insert("exit_code".to_string(), Value::int(obs.exit_code));
    }
    if let Some(result) = obs.result {
        out.insert("result".to_string(), result);
    }
    if !obs.error.is_empty() {
        out.insert("error".to_string(), Value::string(obs.error));
    }
    out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
    out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
    out.insert(
        "truncated_bytes".to_string(),
        Value::int(dropped.min(i64::MAX as u64) as i64),
    );
    Ok(Value::map(out))
}

fn meta_to_value(meta: &FuncMeta) -> Value {
    let mut map = BTreeMap::new();
    map.insert("name".to_string(), Value::string(meta.name.clone()));
    map.insert("module".to_string(), Value::string(meta.module.clone()));
    map.insert(
        "kind".to_string(),
        Value::string(meta.kind.label().to_string()),
    );
    let params = match &meta.params {
        Some(params) => Value::list(
            params
                .iter()
                .map(|p| {
                    let mut entry = BTreeMap::new();
                    entry.insert("name".to_string(), Value::string(p.name.clone()));
                    entry.insert(
                        "param_type".to_string(),
                        Value::string(
                            p.param_type
                                .as_ref()
                                .map(render_structural)
                                .unwrap_or_default(),
                        ),
                    );
                    entry.insert(
                        "allowed".to_string(),
                        Value::string(
                            p.allowed
                                .map(|values| values.join(", "))
                                .unwrap_or_default(),
                        ),
                    );
                    entry.insert("docs".to_string(), Value::string(String::new()));
                    entry.insert("optional".to_string(), Value::bool(p.optional));
                    entry.insert(
                        "options".to_string(),
                        match p.options {
                            Some(keys) => Value::list(
                                keys.iter()
                                    .map(|key| {
                                        let mut option = BTreeMap::new();
                                        option.insert(
                                            "name".to_string(),
                                            Value::string(key.name.to_string()),
                                        );
                                        option.insert(
                                            "value_type".to_string(),
                                            Value::string(render_structural(&key.value)),
                                        );
                                        option.insert(
                                            "required".to_string(),
                                            Value::bool(key.required),
                                        );
                                        option.insert(
                                            "default".to_string(),
                                            Value::string(
                                                key.default.unwrap_or_default().to_string(),
                                            ),
                                        );
                                        Value::map(option)
                                    })
                                    .collect(),
                            ),
                            None => Value::string(String::new()),
                        },
                    );
                    Value::map(entry)
                })
                .collect(),
        ),
        // Parameterless functions mint an empty LIST, never an empty
        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
        // for every entry, and the boundary enforces it.
        None => Value::list(Vec::new()),
    };
    map.insert("params".to_string(), params);
    map.insert(
        "returns".to_string(),
        Value::string(
            meta.returns
                .as_ref()
                .map(render_structural)
                .unwrap_or_default(),
        ),
    );
    map.insert("rpn".to_string(), Value::bool(meta.rpn));
    map.insert(
        "summary".to_string(),
        Value::string(meta.summary.to_string()),
    );
    Value::map(map)
}

/// One named record schema: a shape host functions produce and scripts
/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
/// so schemas register exactly when their producer does.
#[derive(Debug, Clone)]
pub struct RecordSchema {
    pub name: &'static str,
    pub fields: std::sync::Arc<[Field]>,
}

/// One host library: functions and types registered under a single module
/// name. `Engine::register_module` stages these; runs expose them as
/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
#[derive(Clone)]
pub struct HostModule<P: ProcessManager> {
    pub name: String,
    pub funcs: Vec<HostRegistration<P>>,
    pub types: Vec<&'static TypeDescriptor>,
    pub record_schemas: Vec<RecordSchema>,
    /// Shared module state (endpoint registries and the like), stashed
    /// at registration and reachable from bodies through
    /// `StepCtx::module_state`. Lets every entry stay `#[oxdock_func]`:
    /// the macro only generates closers-over-nothing, so state that
    /// cannot ride in a value travels here instead of a hand-built
    /// closure. Prefer `.with_state(...)` over spelling this field.
    pub states: Vec<ModuleState>,
}

/// One shared state object traveling with its module. Keyed by the
/// owning module name plus the value type at registration, so two
/// modules sharing one state type never collide.
#[derive(Clone)]
pub struct ModuleState {
    id: std::any::TypeId,
    state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
}

/// A pre-run steps inspection: pure function of the parsed steps,
///
/// shared so the struct field stays under the complexity lint.
pub type PreRunInspector = dyn Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync;

/// A pre-run check riding in a module's `states`: the runner executes
/// every staged check against the parsed steps before the first step
/// runs, so unmapped services fail fast with zero side effects. Modules
/// attach one with `.with_state(Arc::new(check))`; the runner discovers
/// them by type, so no struct field or plugin knowledge is needed here.
#[derive(Clone)]
pub struct PreRunCheck {
    check: Arc<PreRunInspector>,
}

impl PreRunCheck {
    /// Wrap a steps inspector as a pre-run check.
    pub fn new(check: impl Fn(&[Step]) -> DiagnosticResult<()> + Send + Sync + 'static) -> Self {
        Self {
            check: Arc::new(check),
        }
    }

    /// Run the inspection: `Ok` lets execution start.
    pub fn run(&self, steps: &[Step]) -> DiagnosticResult<()> {
        (self.check)(steps)
    }
}

impl<P: ProcessManager> HostModule<P> {
    /// Attach shared state for bodies to fetch with
    /// `cx.module_state::<T>("MODULE")`. Chainable, like registration.
    pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
        self.states.push(ModuleState {
            id: std::any::TypeId::of::<T>(),
            state,
        });
        self
    }

    /// Run every staged [`PreRunCheck`] against already-parsed steps.
    /// The runner calls this before the first step executes; the first
    /// failing check aborts the run with no side effects.
    pub fn check_pre_run(&self, steps: &[Step]) -> DiagnosticResult<()> {
        for state in &self.states {
            if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
                check.run(steps)?;
            }
        }
        Ok(())
    }
}

impl<P: ProcessManager> ExecState<P> {
    /// Register one [`HostModule`]: every function becomes callable as
    /// `MODULE::NAME`, every type joins the run's name directory.
    pub fn register_module(&mut self, module: HostModule<P>) {
        for registration in module.funcs {
            match registration {
                HostRegistration::Stateful { name, meta, func } => {
                    self.functions.register_host(&module.name, name, meta, func);
                }
                HostRegistration::Pure { name, meta, func } => {
                    self.functions
                        .register_pure_host(&module.name, name, meta, func);
                }
                HostRegistration::Both {
                    name,
                    meta,
                    func,
                    template,
                } => {
                    self.functions
                        .register_both_host(&module.name, name, meta, func, template);
                }
            }
        }
        for descriptor in module.types {
            // Ownership lives on the entry, never a side map: `HM::T`
            // filters by `entry.module`.
            if let Some(live) = self.type_env.types.get(descriptor.name) {
                if !std::ptr::eq(live.descriptor, descriptor) {
                    panic!(
                        "type name `{}` already registered for a different descriptor",
                        descriptor.name
                    );
                }
            } else {
                self.type_env.types.insert(
                    descriptor.name.to_string(),
                    super::state::HostTypeEntry {
                        descriptor,
                        module: module.name.clone(),
                    },
                );
                // Digest fold mirrors `register_type` for startup globals.
                self.type_env.type_env_digest ^= {
                    use std::hash::Hasher;
                    let mut h = std::collections::hash_map::DefaultHasher::new();
                    h.write_u8(b't');
                    h.write(descriptor.name.as_bytes());
                    h.write(descriptor.name.as_bytes());
                    h.finish()
                };
            }
        }
        for schema in module.record_schemas {
            if let Some(live) = self.type_env.record_schemas.get(schema.name) {
                if live.fields.len() != schema.fields.len()
                    || live
                        .fields
                        .iter()
                        .zip(schema.fields.iter())
                        .any(|(a, b)| a.name != b.name)
                {
                    panic!(
                        "record schema `{}` already registered with different fields",
                        schema.name
                    );
                }
            } else {
                let rendered = oxdock_parser::render_structural(&oxdock_parser::TypeTag::Record(
                    schema.fields.clone(),
                ));
                self.type_env.record_schemas.insert(
                    schema.name.to_string(),
                    super::state::RecordSchemaEntry {
                        fields: schema.fields,
                        module: module.name.clone(),
                    },
                );
                self.type_env.type_env_digest ^= {
                    use std::hash::Hasher;
                    let mut h = std::collections::hash_map::DefaultHasher::new();
                    h.write_u8(b's');
                    h.write(schema.name.as_bytes());
                    h.write(rendered.as_bytes());
                    h.finish()
                };
            }
        }
        for state in module.states {
            self.module_states
                .insert((module.name.clone(), state.id), state.state);
        }
    }

    /// All visible functions: natives plus hosts plus current DSL definitions.
    pub fn list_functions(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
        // TODO: Make a "virtual function" and don't hardcode
        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
            out.push(FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some(TypeTag::Map),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
                examples: &[],
            });
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Describe one function by name, or `None` when unknown.
    pub fn describe_function(&self, name: &str) -> Option<Value> {
        if let Some(meta) = self.functions.meta(name) {
            return Some(meta_to_value(&meta));
        }
        // TODO: Make a "virtual function" and don't hardcode
        if name == KEYWORD_INSPECT {
            return Some(meta_to_value(&FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some(TypeTag::Map),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
                examples: &[],
            }));
        }
        None
    }

    /// Shared snapshot of every registered pure function for
    /// placeholder and host driven expansion. Public so host crates
    /// resolve calls through the live registry instead of hardcoding
    /// module or function names. Cloning the `Arc` never copies the map.
    pub fn pure_function_table(&self) -> Arc<PureTable> {
        self.functions.pure_shared()
    }
}

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

    #[test]
    fn placeholder_resolver_dispatches_table_entries() {
        // Single dispatch implementation for every expansion path:
        // known names route to the entry, unknown names fail with
        // the sorted known-functions listing.
        let echo: PureFn = Arc::new(|args| {
            args.into_iter().next().ok_or_else(|| {
                Diagnostic::new(
                    "test.echo.arity",
                    "ECHO needs 1 arg".to_string(),
                    Diagnostic::make_fields(&[]),
                )
            })
        });
        let mut entries = HashMap::new();
        entries.insert("ECHO".to_string(), echo);
        let mut table = PureTable::new();
        table.insert("T".to_string(), entries);
        let resolve = placeholder_resolver(Arc::new(table));
        let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
        assert_eq!(out.as_str().expect("string"), "hi");
        let err = format!(
            "{:#}",
            resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
        );
        assert!(
            err.contains("unknown placeholder function `T::NOPE`"),
            "names the call: {err}"
        );
        assert!(
            err.contains("known functions: T::ECHO"),
            "lists known names: {err}"
        );
    }

    #[test]
    fn describe_entry_renders_union_spellings() {
        // Union params and returns render through the same structural
        // renderer every other tag uses: `DESCRIBE` (and the generated
        // reference built on it) names the admission set, never a
        // bare word or an empty string. Built by macro, so the
        // spelling cannot drift from the members.
        let union = oxdock_parser::union_tag!(String, Pipe);
        let meta = FuncMeta {
            name: "T::F".to_string(),
            module: "T".to_string(),
            kind: FuncKind::HostPure,
            params: Some(vec![FuncParam {
                name: "text".to_string(),
                param_type: Some(union.clone()),
                allowed: None,
                docs: "",
                options: None,
                optional: false,
            }]),
            returns: Some(union),
            rpn: false,
            summary: "test-only",
            docs: "test-only",
            examples: &[],
        };
        let value = meta_to_value(&meta);
        let map = value.as_map().expect("describe value is a map");
        let params = map
            .get("params")
            .expect("params key")
            .as_list()
            .expect("params is a list");
        let first = params[0].as_map().expect("entry is a map");
        assert_eq!(
            first.get("param_type").and_then(Value::as_str),
            Some("STRING|PIPE"),
            "param renders the set"
        );
        assert_eq!(
            map.get("returns").and_then(Value::as_str),
            Some("STRING|PIPE"),
            "returns render the set"
        );
    }

    #[test]
    fn describe_entry_renders_handle_payload() {
        // Shaped handles render structurally (HANDLE<STRING>, not
        // bare HANDLE): script ASYNC FUNC declarations surface their
        // payload through DESCRIBE exactly as declared.
        let meta = FuncMeta {
            name: "SCRIPT::FETCH".to_string(),
            module: "SCRIPT".to_string(),
            kind: FuncKind::Script,
            params: Some(vec![]),
            returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
            rpn: false,
            summary: "test-only",
            docs: "test-only",
            examples: &[],
        };
        let value = meta_to_value(&meta);
        let map = value.as_map().expect("describe value is a map");
        assert_eq!(
            map.get("returns").and_then(Value::as_str),
            Some("HANDLE<STRING>"),
            "returns render the payload"
        );
    }

    #[test]
    fn describe_entry_carries_optional_flag() {
        // The `optional` key on params entries is the machine-readable
        // half of the `?` rendering: pin both values through the same
        // builder the runtime serves, not through prose.
        let meta = FuncMeta {
            name: "T::F".to_string(),
            module: "T".to_string(),
            kind: FuncKind::HostPure,
            params: Some(vec![
                FuncParam {
                    name: "url".to_string(),
                    param_type: Some(TypeTag::String),
                    allowed: None,
                    docs: "",
                    options: None,
                    optional: false,
                },
                FuncParam {
                    name: "options".to_string(),
                    param_type: Some(TypeTag::Map),
                    allowed: None,
                    docs: "",
                    options: None,
                    optional: true,
                },
            ]),
            returns: Some(TypeTag::String),
            rpn: false,
            summary: "test-only",
            docs: "test-only",
            examples: &[],
        };
        let value = meta_to_value(&meta);
        let map = value.as_map().expect("describe value is a map");
        let params = map
            .get("params")
            .expect("params key")
            .as_list()
            .expect("params is a list");
        assert_eq!(params.len(), 2);
        let first = params[0].as_map().expect("entry is a map");
        let second = params[1].as_map().expect("entry is a map");
        assert_eq!(
            first.get("optional").and_then(Value::as_bool),
            Some(false),
            "required param must read false"
        );
        assert_eq!(
            second.get("optional").and_then(Value::as_bool),
            Some(true),
            "omittable param must read true"
        );
    }

    #[test]
    fn template_twins_mirror_string_paths_and_refuse_pipes() {
        // Every template twin answers strings through the shared pump
        // semantics and refuses pipes naming the step IO they need:
        // placeholder evaluation carries no step context to pump
        // through. Table-driven so a twinless mirror op fails here
        // naming it.
        let pipe = Value::pipe_fresh();
        type TwinCase = (&'static str, Box<dyn Fn() -> DiagnosticResult<Value>>);
        let cases: Vec<TwinCase> = vec![
            (
                "TEXT_TRIM",
                Box::new(|| text_trim_string(Value::string("  hello  ".to_string()))),
            ),
            (
                "TEXT_TRIM_PREFIX",
                Box::new(|| {
                    text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
                }),
            ),
            (
                "TEXT_TRIM_SUFFIX",
                Box::new(|| {
                    text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
                }),
            ),
            (
                "TEXT_TO_UPPER",
                Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
            ),
            (
                "TEXT_TO_LOWER",
                Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
            ),
            (
                "TEXT_REPLACE",
                Box::new(|| {
                    text_replace_string(
                        Value::string("ab".to_string()),
                        "b".to_string(),
                        "c".to_string(),
                    )
                }),
            ),
            (
                "TEXT_REPLACE_REGEX",
                Box::new(|| {
                    text_replace_regex_string(
                        Value::string("ab".to_string()),
                        "b".to_string(),
                        "c".to_string(),
                    )
                }),
            ),
        ];
        assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
        for (name, run) in &cases {
            let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
            assert!(
                value.as_str().is_some(),
                "{name} twin must answer STRING, got {}",
                value.type_name()
            );
        }
        assert_eq!(
            text_trim_string(Value::string("  hello  ".to_string()))
                .expect("trim twin")
                .as_str(),
            Some("hello")
        );
        // Pipes refuse through the shared message on every twin.
        let pipe_cases: Vec<(&str, DiagnosticResult<Value>)> = vec![
            ("TEXT_TRIM", text_trim_string(pipe.clone())),
            (
                "TEXT_TRIM_PREFIX",
                text_trim_prefix_string(pipe.clone(), "v".to_string()),
            ),
            (
                "TEXT_TRIM_SUFFIX",
                text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
            ),
            ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
            ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
            (
                "TEXT_REPLACE",
                text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
            ),
            (
                "TEXT_REPLACE_REGEX",
                text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
            ),
        ];
        for (name, result) in pipe_cases {
            let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
            assert!(
                format!("{err:#}").contains("step IO"),
                "{name} refusal names the missing context: {err:#}"
            );
        }
    }

    #[test]
    fn shell_words_join_split_round_trip() {
        // Join and split are absolute inverses on the word side: the
        // joiner quotes through `shell-words`, the splitter parses the
        // same syntax, so every adversarial word survives the round trip.
        let words = vec![
            "gh".to_string(),
            "issue".to_string(),
            "comment".to_string(),
            "with spaces".to_string(),
            "it's".to_string(),
            "say \"hi\"".to_string(),
            "$HOME".to_string(),
            "$(whoami)".to_string(),
            "C:\\path\\to".to_string(),
            "naïve café".to_string(),
            "".to_string(),
        ];
        let joined = shell_words::join(&words);
        let back = shell_words::split(&joined).expect("join output must parse");
        assert_eq!(back, words);
        assert!(shell_words::split("unbalanced \"quote").is_err());
    }

    /// Fake module graph for the shared forward walk: export lists,
    /// per-file alias targets, and per-file bindings set directly,
    /// so every chase branch pins without files or execution.
    struct FakeView {
        exports: HashMap<String, Vec<String>>,
        targets: HashMap<String, AliasTargets>,
        bindings: HashMap<String, HashMap<String, bool>>,
    }

    impl ModuleGraphView for FakeView {
        fn const_exports(&self, file: &str) -> Option<&[String]> {
            self.exports.get(file).map(Vec::as_slice)
        }

        fn alias_targets(&self, file: &str) -> AliasTargets {
            self.targets.get(file).cloned().unwrap_or_default()
        }

        fn binding(&self, file: &str, name: &str) -> BindingPresence {
            match self.bindings.get(file).and_then(|names| names.get(name)) {
                Some(true) => BindingPresence::Const,
                Some(false) => BindingPresence::Let,
                None => BindingPresence::Absent,
            }
        }
    }

    fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
        let mut targets = AliasTargets::new();
        for (alias, file) in pairs {
            targets
                .entry((*alias).to_string())
                .or_default()
                .push(AliasTarget {
                    file: Some((*file).to_string()),
                    host: None,
                    guard: None,
                });
        }
        targets
    }

    fn os_guard(os: &str) -> GuardExpr {
        GuardExpr::Predicate(oxdock_parser::Guard::Attr {
            ns: oxdock_parser::Ns::Os,
            key: None,
            val: Some(os.to_string()),
        })
    }

    #[test]
    fn chase_resolves_bare_and_single_forward() {
        // Bare entries terminate in place; one forward hop lands on
        // the defining file; chains compose hop by hop.
        let mut view = FakeView {
            exports: HashMap::from([
                ("a".to_string(), vec!["N".to_string()]),
                ("b".to_string(), vec!["A::N".to_string()]),
                ("c".to_string(), vec!["B::N".to_string()]),
            ]),
            targets: HashMap::from([
                ("u".to_string(), fake_targets(&[("B", "b")])),
                ("b".to_string(), fake_targets(&[("A", "a")])),
                ("c".to_string(), fake_targets(&[("B", "b")])),
            ]),
            bindings: HashMap::new(),
        };
        assert_eq!(
            chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
            vec!["a".to_string()]
        );
        assert_eq!(
            chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
            vec!["a".to_string()]
        );
        view.targets
            .insert("u".to_string(), fake_targets(&[("C", "c")]));
        assert_eq!(
            chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
            vec!["a".to_string()]
        );
    }

    #[test]
    fn chase_prefers_bare_over_forwards() {
        // A local bare definition shadows forwards of the same base:
        // the file answers for its own binding.
        let view = FakeView {
            exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
            targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
            bindings: HashMap::new(),
        };
        assert_eq!(
            chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
            vec!["b".to_string()]
        );
    }

    #[test]
    fn chase_rejects_split_forwards() {
        // Two forwards of one base in one file fail instead of
        // picking one.
        let view = FakeView {
            exports: HashMap::from([(
                "b".to_string(),
                vec!["A::N".to_string(), "C::N".to_string()],
            )]),
            targets: HashMap::new(),
            bindings: HashMap::new(),
        };
        let err = format!(
            "{}",
            chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
        );
        assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
        assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
    }

    #[test]
    fn chase_names_broken_link_detail() {
        // A hop landing nowhere names the break: missing binding,
        // unexported CONST, or LET terminal each render distinctly.
        let view = FakeView {
            exports: HashMap::from([
                ("b".to_string(), vec!["A::M".to_string()]),
                ("c".to_string(), vec!["A::P".to_string()]),
                ("d".to_string(), vec!["A::Q".to_string()]),
                ("a".to_string(), Vec::new()),
            ]),
            targets: HashMap::from([
                ("b".to_string(), fake_targets(&[("A", "a")])),
                ("c".to_string(), fake_targets(&[("A", "a")])),
                ("d".to_string(), fake_targets(&[("A", "a")])),
            ]),
            bindings: HashMap::from([(
                "a".to_string(),
                HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
            )]),
        };
        let err = format!(
            "{}",
            chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
        );
        assert!(err.contains("does not resolve"), "{err}");
        assert!(err.contains("no import alias `A` exports `M`"), "{err}");
        let err = format!(
            "{}",
            chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
        );
        assert!(
            err.contains("holds `P` as CONST but does not export it"),
            "{err}"
        );
        let err = format!(
            "{}",
            chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
        );
        assert!(
            err.contains("is a LET binding and cannot be exported"),
            "{err}"
        );
    }

    #[test]
    fn chase_rejects_cycles() {
        // Mutual forwards never resolve: the walk names the chain
        // instead of recursing forever.
        let view = FakeView {
            exports: HashMap::from([
                ("a".to_string(), vec!["B::N".to_string()]),
                ("b".to_string(), vec!["A::N".to_string()]),
            ]),
            targets: HashMap::from([
                ("a".to_string(), fake_targets(&[("B", "b")])),
                ("b".to_string(), fake_targets(&[("A", "a")])),
            ]),
            bindings: HashMap::new(),
        };
        let err = format!(
            "{}",
            chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
        );
        assert!(err.contains("re-export cycle"), "{err}");
    }

    #[test]
    fn chase_unions_disjoint_guard_branches() {
        // One forward over disjoint platform imports chases each live
        // branch to its own terminal instead of failing ambiguous.
        let mut guarded = AliasTargets::new();
        guarded.insert(
            "A".to_string(),
            vec![
                AliasTarget {
                    file: Some("lin".to_string()),
                    host: None,
                    guard: Some(os_guard("linux")),
                },
                AliasTarget {
                    file: Some("mac".to_string()),
                    host: None,
                    guard: Some(os_guard("macos")),
                },
            ],
        );
        let view = FakeView {
            exports: HashMap::from([
                ("b".to_string(), vec!["A::N".to_string()]),
                ("lin".to_string(), vec!["N".to_string()]),
                ("mac".to_string(), vec!["N".to_string()]),
            ]),
            targets: HashMap::from([("b".to_string(), guarded)]),
            bindings: HashMap::new(),
        };
        assert_eq!(
            chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
            vec!["lin".to_string(), "mac".to_string()]
        );
    }

    #[test]
    fn holder_classification_sorts_and_rejects() {
        // Holders come back sorted; unknown aliases and overlapping
        // files report through their own variants.
        let view = FakeView {
            exports: HashMap::from([
                ("b".to_string(), vec!["N".to_string()]),
                ("c".to_string(), vec!["N".to_string()]),
            ]),
            targets: HashMap::new(),
            bindings: HashMap::new(),
        };
        let unit = fake_targets(&[("B", "b"), ("B", "c")]);
        match const_holder_files(&view, &unit, "B", "N") {
            ConstHolders::Ambiguous { .. } => {}
            other => panic!("overlapping holders must be ambiguous, got {other:?}"),
        }
        match const_holder_files(&view, &unit, "Z", "N") {
            ConstHolders::NoAlias => {}
            other => panic!("unknown alias must report NoAlias, got {other:?}"),
        }
        let unit = fake_targets(&[("B", "b")]);
        match const_holder_files(&view, &unit, "B", "N") {
            ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
            other => panic!("single holder must be found, got {other:?}"),
        }
    }
}