ilo 26.5.0

ilo - the token-minimal programming language AI agents write
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
/// Enum of all builtin functions in ilo.
///
/// Resolving a function name to a `Builtin` variant should happen at
/// compile time (in the bytecode compiler) or once at the start of
/// interpretation, so that hot dispatch paths use integer-discriminant
/// matching rather than string comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Builtin {
    // Conversion
    Str,
    Num,

    // Math
    Abs,
    Flr,
    Cel,
    Rou,
    Min,
    Max,
    Mod,
    Fmod,
    Clamp,
    Pow,
    Sqrt,
    Log,
    Exp,
    Sin,
    Cos,
    Tan,
    Log10,
    Log2,
    Asin,
    Acos,
    Atan,
    Atan2,
    Sum,
    Prod,
    Cumsum,
    Cprod,
    Ewm,
    Avg,
    Median,
    Quantile,
    Stdev,
    Variance,
    Fft,
    Ifft,

    // Linear algebra
    Transpose,
    Matmul,
    Dot,
    // `matvec xm ys > L n` — native matrix-vector multiply. Returns the
    // dot product of each row of `xm` with `ys`. Skips the
    // wrap-as-column-matrix + flatten ceremony required to use `matmul`
    // for this case (`flatten matmul xm (map (y:n>L n;[y]) ys)`).
    // Tree-bridge eligible: composes existing matrix/vector helpers so
    // VM and Cranelift inherit through the bridge without new opcodes.
    // Added in 0.12.1.
    Matvec,

    // Collections
    Len,
    Hd,
    At,
    Tl,
    Rev,
    Srt,
    Rsrt,
    Slc,
    Lst,
    Take,
    Drop,
    Unq,
    Flat,
    Has,
    Spl,
    Cat,
    Zip,
    Enumerate,
    Range,
    Linspace,
    Ones,
    Rep,
    Window,
    Chunks,
    Setunion,
    Setinter,
    Setdiff,

    // Higher-order
    Map,
    Flt,
    Fld,
    Ct,
    Grp,
    Uniqby,
    Partition,
    Frq,
    Flatmap,
    Mapr,

    // Random / time
    Rnd,
    Rndn,
    RandBytes,
    Seed,
    Now,
    NowMs,
    Dtfmt,
    Dtparse,
    DtparseRel,
    Sleep,
    // `tz-offset tz:t epoch:n > R n t` — UTC offset in seconds for the given
    // IANA timezone at the given Unix epoch. Handles DST transitions correctly
    // via chrono-tz. Returns Err on unknown timezone name.
    TzOffset,

    // I/O
    Rd,
    RdJson,
    Rdl,
    Rdb,
    // `rdin > R t t` — read all of stdin to a text string.
    // `rdinl > R (L t) t` — read stdin line by line, returning `R (L t) t`.
    // Both return Err on I/O failure. On WASM targets they always return
    // `Err("rdin: stdin not available on wasm")`.
    Rdin,
    Rdinl,
    // `for-line stdin > LazyStdinLines` — lazy line iterator over stdin.
    // Unlike `rdinl` (which buffers all of stdin before returning), `for-line`
    // produces a lazy handle that the `@binding` foreach consumes one line at
    // a time. This enables processing unbounded streams (e.g. `tail -f` output,
    // streaming log producers) without ever buffering the full input.
    //
    // Canonical usage:
    //   `@line (for-line stdin) { prnt line }`
    //
    // The single argument must be the text "stdin"; other values are a
    // runtime error (ILO-R009). On WASM the builtin returns Err immediately.
    // Partial trailing lines at EOF are emitted unchanged (no newline added).
    // Tree-interpreter only in this release; VM/Cranelift inherit via the
    // tree-bridge (OP_CALL_BUILTIN_TREE) because the return type
    // (`LazyStdinLines`) is opaque to the register-based engines.
    ForLine,
    Wr,
    Wra,
    Wro,
    Wrl,
    Prnt,
    Env,
    /// `world > World` — return the current capability World value.
    /// Zero args; reads from the runtime's active `Caps`.
    WorldCap,
    /// `world-no-net > World` — construct a World with net=false.
    /// All other caps (read, write, run) are inherited from the runtime `Caps`.
    /// Used to pass a restricted capability token to a sub-function that should
    /// not perform network I/O; the verifier enforces this statically (ILO-T044).
    WorldNoNet,
    Ls,
    Walk,
    Glob,
    Fsize,
    Mtime,
    Isfile,
    Isdir,
    EnvAll,

    // String
    Trm,
    Upr,
    Lwr,
    Cap,
    Padl,
    Padr,
    Ord,
    Chr,
    Chars,
    Fmt,
    Fmt2,
    Rgx,
    Rgxall,
    Rgxall1,
    Rgxsub,
    RgxallMulti,

    // JSON
    Jpth,
    Jkeys,
    Jdmp,
    Jpar,
    JparList,
    Rdjl,

    // HTTP
    Get,
    Post,
    GetMany,
    // `get-to url timeout-ms > R t t` — like `get` but with an explicit
    // per-request timeout (milliseconds). Rounds up to nearest whole second
    // for minreq (which takes u64 seconds). Returns Err when the deadline
    // is exceeded, identical to a connection error from the caller's view.
    // Tree-bridge eligible; no new native opcode needed.
    GetTo,
    // `pst-to url body timeout-ms > R t t` — like `pst` but with an explicit
    // per-request timeout. Same millisecond-to-second rounding as `get-to`.
    PstTo,
    // `getx url > R (M t _) t` — like `get` but returns a rich Ok-map with
    // keys `status` (n), `headers` (M t t), `body` (t). Optional 2nd arg is a
    // request-headers map (M t t), same as `get`. Additive — does not change
    // `get`'s shape. Unblocks conditional-request / cache-aware / cookie-
    // following / redirect / pagination-Link workflows that need response
    // metadata. Tree-bridge eligible: no FnRef args, returns Result.
    Getx,
    // `pstx url body > R (M t _) t` — like `pst` but returns the same rich
    // Ok-map shape as `getx`. Optional 3rd arg is a request-headers map.
    // Tree-bridge eligible.
    Pstx,
    // HTTP verb cluster (#5z). Same shape as `pst`/`get`: optional 3rd-arg
    // `M t t` headers map; returns `R t t`. Tree-bridge eligible — no
    // dedicated VM opcodes, the tree interpreter performs the actual minreq
    // call. Verb cluster intentionally limited to the seven safe methods
    // (GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS); TRACE/CONNECT are excluded
    // (CONNECT is for tunnelling, TRACE is footgun-grade — both unsafe to
    // expose without proxy framing). `del` takes only the URL — DELETE bodies
    // exist in the RFC but no major API honours them, so we keep the surface
    // tight and add the headers variant only.
    Put,
    Pat,
    Del,
    Hed,
    Opt,
    // HTTP streaming (ILO-46 client side). Each returns a lazy line iterator
    // (`LazyHttpLines`) drained one chunk-line at a time by `@line stream {...}`
    // foreach. Bytes flow through a `BufReader::lines()` adapter over the
    // underlying chunked/SSE response — the body is never fully buffered.
    // Tree-walker only at runtime; VM/Cranelift inherit via the tree bridge
    // because the return type is opaque to the register engines (same shape
    // as `for-line stdin`). All four perform a capability check via
    // `Caps::check_net` before opening the connection. On WASM the streaming
    // backends are not wired up and the builtins return Err.
    GetStream,
    GetStreamH,
    PostStream,
    PostStreamH,

    // Process spawn (argv-list only — no shell, no interpolation, no glob).
    // See SPEC.md "Process spawn" section for the security framing.
    Run,
    // `run2 cmd:t args:L t > R RunResult t` — structured process spawn.
    // Like `run` but returns a typed Record instead of a loose Map, giving
    // clean dot-access: r.stdout, r.stderr, r.exit (n, not t). Non-zero
    // exit is NOT an error; Err only on spawn failure. Tree-bridge eligible.
    Run2,
    // `run-bg cmd:t args:L t > R n t` — fire-and-forget background spawn.
    // Launches the child process and immediately returns `Ok(pid:n)` without
    // waiting for it to finish. stdout/stderr are inherited from the parent
    // (agents usually redirect via shell or the child itself). Err only on
    // spawn failure. The returned pid is a positive integer; callers that
    // need to reap the child can pass it to a platform wait(2) equivalent.
    // Tree-bridge eligible.
    RunBg,

    // Map (associative array)
    Mmap,
    Mget,
    Mset,
    Mhas,
    Mkeys,
    Mvals,
    Mdel,
    // `mget-or m k default > v` — value at key, or default if missing.
    // Same shape as `mget m k > O v` but unwraps with a caller-supplied
    // fallback. Lowered through the tree-bridge so VM and Cranelift inherit
    // semantics without new opcodes.
    MgetOr,
    // `lget-or xs i default > a` — element at index, or default if OOB.
    // Same negative-index semantics as `at xs i`; OOB returns default
    // rather than erroring.
    LgetOr,
    Mpairs,

    // Linear algebra
    Solve,
    Inv,
    Det,
    // `lstsq xm ys > L n` — ordinary least squares via the normal equations:
    // `b = solve (matmul (transpose xm) xm) (matmul (transpose xm) ys)`.
    // Collapses the 5-line OLS recipe into a single call. Same precision
    // tier as `solve`/`inv`/`det` (LU with partial pivoting); ill-conditioned
    // designs surface as `ILO-R009` from the inner `solve`. Tree-bridge
    // eligible — no new opcodes, VM and Cranelift inherit semantics through
    // the bridge. Added in 0.12.1.
    Lstsq,
    // Index-returning aggregates (numpy convention).
    // argmax xs:L n > n — index of max element.
    // argmin xs:L n > n — index of min element.
    // argsort xs:L n > L n — sorted index permutation (ascending).
    Argmax,
    Argmin,
    Argsort,
    // `bisect xs:L n target:n > n` — insertion point in a sorted list.
    // Python `bisect.bisect_left` semantics: returns the leftmost index `i`
    // such that `xs[0..i] < target <= xs[i..]`. Returns `0` for empty list,
    // `len(xs)` when target is greater than every element, and the index of
    // the first equal element when duplicates are present (leftmost wins on
    // ties). Caller is responsible for the sortedness precondition - we do
    // NOT validate it. O(log N) binary search; closes the verbose
    // `flt fn xs` + len pattern that three sorted-array personas reached for
    // (k-sorted-search, schedule-merge, range-bucket). Tree-bridge eligible:
    // pure 2-arg, no FnRef, no Result wrapper. NaN target propagates as NaN.
    Bisect,
    // `par-map fn xs n > L (R b t)` — general parallel fan-out. Applies `fn`
    // to each element of `xs` with up to `n` concurrent threads. Results are
    // returned in input order. Per-item errors are surfaced as `Err(msg)` in
    // the list so a single failure does not abort the whole operation. When `n`
    // is 0 (or the 2-arg form is used), concurrency defaults to the number of
    // logical CPUs. VM/Cranelift bail to tree (tree-bridge eligible).
    // The inner function may use any builtin (including I/O builtins that check
    // caps); capability checks run inside the worker threads as usual.
    ParMap,

    // Path manipulation (pure text ops, Unix forward-slash only).
    // POSIX dirname/basename semantics; pathjoin takes a list to avoid
    // the variadic-arity ILO-P101 trap that `fmt` lives with.
    Dirname,
    Basename,
    Pathjoin,

    // Math constants (zero-arg). Added 0.12.1 so agents stop hardcoding
    // `3.14159...` or reconstructing pi via `* 2 (atan2 0 -1)` — fft-peak
    // rerun12 surfaced both shapes. Tree-bridge-eligible so VM / Cranelift
    // inherit for free; Python codegen emits `math.pi` / `math.tau` / `math.e`.
    Pi,
    Tau,
    Eu,

    // Duration parse / format.
    // `dur-parse s > R n t` — parse a human-readable duration string ("3 weeks
    // 2 days 5 hours", "4h 32m", "1d", "1.5 hours") into seconds (f64). Lenient:
    // accepts unit abbreviations s/m/h/d/w and full names (singular + plural).
    // `dur-fmt n > t` — format seconds as human-readable "4h 32m", "2 days 1
    // hour", "30s". Drops zero parts; always uses the largest applicable unit.
    // Both are tree-bridge eligible — pure text ↔ number ops, no I/O.
    DurParse,
    DurFmt,

    // `default-on-err r d > T` — unwrap `R T E` to `T`, using `d:T` if `Err`.
    // Mirror of `??` for Result: `?? v d` is nil-coalesce for `O T`; this is
    // the Result equivalent. Tree-bridge eligible (2-arg, pure, no FnRef).
    DefaultOnErr,

    // URL + base64url encoding cluster (0.12.1). Both are token-cheap
    // primitives for the OAuth / JWT / webhook-signature workflows that
    // dominated the bearer-token, jwt-signer and webhook-receiver personas.
    // All four are tree-bridge eligible — pure text-in / text-out with no
    // I/O and no FnRef args.
    // `urlenc s > t` — RFC 3986 percent-encode. Unreserved chars (`-._~` and
    //   ALPHA/DIGIT) stay literal; everything else is `%HH`.
    // `urldec s > R t t` — inverse. Err on invalid percent escapes or
    //   non-UTF-8 decoded bytes.
    // `b64u s > t` — base64url-encode the UTF-8 bytes of `s`, no padding
    //   (RFC 4648 §5: `-`/`_` substituted for `+`/`/`).
    // `b64u-dec s > R t t` — inverse. Err on invalid base64 or non-UTF-8
    //   decoded bytes.
    Urlenc,
    Urldec,
    B64u,
    B64uDec,

    // Crypto primitives cluster (0.12.x). All tree-bridge eligible: pure
    // text-in / text-or-bool-out, no FnRef args, no I/O wrap. VM and Cranelift
    // inherit cross-engine parity without new opcodes.
    // `sha256 s > t` — SHA-256 of the UTF-8 bytes of `s`, lowercase hex.
    // `hmac-sha256 key:t msg:t > t` — HMAC-SHA256, lowercase hex.
    // `b64 s > t` — standard base64 encode (RFC 4648 §4, `=` padding).
    // `b64-dec s > R t t` — standard base64 decode; Err on invalid input
    //   or non-UTF-8 decoded bytes.
    // `hex s > t` — lowercase hex encode of UTF-8 bytes of `s`.
    // `ct-eq a:t b:t > b` — constant-time text equality. Use when comparing
    //   secrets (HMAC digests, tokens) to avoid timing leaks.
    // `sha256-hex hex:t > t` — SHA-256 of hex-decoded bytes, returns lowercase
    //   hex digest. Errors (ILO-R009) on odd-length or non-hex input.
    // `sha256d hex:t > t` — double-SHA256 (Bitcoin protocol: sha256(sha256(x)))
    //   of hex-decoded bytes, returns lowercase hex digest. Errors (ILO-R009) on
    //   odd-length or non-hex input. Equivalent to `sha256-hex (sha256-hex h)`
    //   but named for the Bitcoin Merkle tree use-case.
    Sha256,
    HmacSha256,
    B64,
    B64Dec,
    HexEnc,
    CtEq,
    Sha256Hex,
    Sha256d,

    // `tokcount s > n` — approximate cl100k_base token count of string `s`.
    // Uses a bytes/3.4 approximation (mean bytes-per-token for English prose
    // under cl100k_base). Fast, allocation-minimal, and correct within ~5%
    // for natural-language skill files. A follow-up (ILO-47) will replace
    // this with the full tiktoken-rs BPE tokeniser once the crate's WASM
    // and licence story is confirmed. Pure text-in / number-out; tree-bridge
    // eligible. Added in 0.12.2 (experimental).
    Tokcount,

    // `where cond xs ys > L a` — parallel-list conditional select.
    // NumPy `np.where` equivalent: for each i, output[i] = xs[i] if cond[i] else ys[i].
    // All three lists must have the same length; mismatch raises ILO-R009.
    // The element type of `xs` and `ys` is preserved in the output. Tree-bridge
    // eligible (no FnRef args, no I/O, no Result wrapper). Saves ~50 tokens
    // over the `map (i:n>_;?h (at cond i) (at xs i) (at ys i)) (range 0 (len xs))`
    // recipe; the manifesto framing for NumPy-familiar agents.
    Where,
    // Calendar arithmetic (0.12.2). All four are tree-bridge eligible: pure
    // epoch ↔ epoch / epoch ↔ number, no FnRef args, no I/O.
    //
    // `add-mo dt:n n:n > n` — add N calendar months to an epoch, snapping
    // end-of-month (Jan 31 + 1 = Feb 28/29). N may be negative.
    // `last-dom dt:n > n`  — epoch of the last day of the month containing dt,
    // at 00:00 UTC.
    // `next-business-day dt:n > n` — next weekday after dt (skip Sat/Sun).
    // `day-of-week dt:n > n` — day of week: 0=Sun, 1=Mon … 6=Sat.
    AddMo,
    LastDom,
    NextBusinessDay,
    DayOfWeek,
    // Rolling-window reducers (0.12.x). Numeric-list inputs, fixed window
    // size `n`. Output length = `len xs - n + 1` (empty when `n > len`).
    //
    // `rsum n:n xs:L n > L n` — rolling sum via running-window: O(n) total,
    // not O(n*w) like the naive `map (i:n>n;sum (slc xs i (+ i n))) ...`
    // recipe.
    // `ravg n:n xs:L n > L n` — rolling mean, same running-window strategy.
    // `rmin n:n xs:L n > L n` — rolling minimum, O(n) amortised via a
    // monotonic-deque idiom.
    //
    // `n=0` errors `ILO-R009`; `n > len xs` returns `[]` (Python/numpy
    // convention). Tree-bridge eligible — pure number-list reducers, no
    // FnRef args, no Result wrapper. Appended last to preserve every
    // existing on-wire tag.
    Rsum,
    Ravg,
    Rmin,

    // Text search (0.13.0). Tree-bridge eligible: pure text-in / Option-out,
    // no FnRef args, no I/O, no Result wrapper.
    // `idxof s sub > O n` — byte index of the first occurrence of `sub` in
    // `s`. Returns nil when `sub` is not found. Index is in Unicode code-point
    // units (same as `at`), not raw bytes, so multi-byte characters count as 1.
    Idxof,

    // `hex-rev s > t` — reverse the byte order of a hex-encoded string.
    // Input must be a hex string of even length (2 chars per byte); odd
    // length errors ILO-T013 with a padding hint. Case is preserved:
    // `abCD` reversed is `CDab`. Useful for little-endian ↔ big-endian
    // conversions (e.g. Bitcoin txid display vs wire encoding). Total
    // for even-length hex; errors for odd-length input. Tree-bridge
    // eligible: pure t → t, no FnRef args, no I/O. Appended last to
    // preserve every existing on-wire tag.
    HexRev,

    // Bitwise ops (f64-only, mod 2^32 semantics). All tree-bridge eligible:
    // pure numeric-in / numeric-out, no FnRef args, no I/O, no Result wrapper.
    // Inputs are truncated to u32 via `as u64 & 0xFFFF_FFFF`; output is
    // returned as f64. Closes the crypto-track gap without a new integer type.
    // Added in 0.12.x (ILO-58 MVP).
    //
    // band x y  — bitwise AND  (x & y)
    // bor  x y  — bitwise OR   (x | y)
    // bxor x y  — bitwise XOR  (x ^ y)
    // bnot x    — bitwise NOT  (^x, 32-bit)
    // bshl x n  — logical shift left  (x << n, mod 32)
    // bshr x n  — logical shift right (x >> n, mod 32)
    // brot x n  — rotate left 32-bit  (x.rotate_left(n))
    Band,
    Bor,
    Bxor,
    Bnot,
    Bshl,
    Bshr,
    Brot,
    // 64-bit bitwise variants (ILO-395). Same shape as 32-bit but mask to u64.
    // f64 can exactly represent integers up to 2^53; values >= 2^53 may lose
    // precision on the f64↔u64 round-trip. Keep inputs within safe range.
    //
    // band64 x y  — bitwise AND  (x & y, u64)
    // bor64  x y  — bitwise OR   (x | y, u64)
    // bxor64 x y  — bitwise XOR  (x ^ y, u64)
    // bnot64 x    — bitwise NOT  (^x, 64-bit)
    // bshl64 x n  — logical shift left  (x << n, mod 64)
    // bshr64 x n  — logical shift right (x >> n, mod 64)
    // brot64 x n  — rotate left 64-bit  (x.rotate_left(n))
    Band64,
    Bor64,
    Bxor64,
    Bnot64,
    Bshl64,
    Bshr64,
    Brot64,

    // Numeric-pipeline constructors and stack combinators (0.13.0).
    // All are tree-bridge eligible: pure numeric/list ops, no FnRef args,
    // no I/O. Appended last to preserve every existing on-wire tag.
    //
    // `arange start:n stop:n step:n > L n` — evenly-spaced values in
    //   [start, stop) with the given step (numpy `arange` semantics).
    //   step > 0 required; empty list when start >= stop.
    //
    // `zeros n:n > L n` — list of n 0.0 values. Mirror of `ones`.
    //
    // `vstack matrices:L > L` — vertical stack: concatenate a list of
    //   row-lists, i.e., `flat` on a list of matrices. Each inner list
    //   must be a list of rows (lists). Equivalent to numpy `vstack` for
    //   2-d inputs. Returns a flat list of rows.
    //
    // `hstack matrices:L > L` — horizontal stack: concatenate the rows of
    //   corresponding row-lists column-wise. All inner matrices must have
    //   the same number of rows; output rows are the pairwise `cat` of
    //   corresponding rows. Equivalent to numpy `hstack` for 2-d inputs.
    //
    // `column-stack vecs:L > L` — treat each element (a 1-d vector or
    //   single-column matrix) as a column and return a 2-d matrix (list of
    //   rows). Equivalent to numpy `column_stack`. All vectors must have
    //   the same length.
    //
    // `hist xs:L n_bins:n > L n` — fixed-width histogram over the numeric
    //   list `xs` into `n_bins` equal-width bins spanning [min, max].
    //   Returns a list of n_bins integer counts. Empty xs → all-zero bins.
    //   n_bins must be a positive integer (≤ 1_000_000).
    Arange,
    Zeros,
    Vstack,
    Hstack,
    ColumnStack,
    Hist,

    // Signal/math cluster (0.13.0). All tree-bridge eligible: pure numeric
    // list / complex-pair ops, no FnRef args, no I/O, no Result wrapper.
    // Appended last to preserve every existing on-wire tag.
    //
    // `convolve xs:L n ys:L n > L n` — discrete linear convolution of two
    // real-valued sequences. Output length = `len xs + len ys - 1`. O(n*m)
    // direct sum; suitable for short kernels. Mirrors NumPy `np.convolve`.
    // Both empty → error ILO-R009.
    Convolve,
    // `searchsorted xs:L n targets:L n > L n` — batch sorted-list insertion
    // points. Equivalent to `map (t:n>n; bisect xs t) targets` but more
    // efficient (avoids lambda overhead per target). Numpy
    // `np.searchsorted(a, v)` equivalent with `bisect_left` semantics.
    Searchsorted,
    // `cabs pair:L n > n` — complex magnitude sqrt(re² + im²).
    // Accepts a 2-element [re, im] list. Closes the
    // `sqrt (+ (* re re) (* im im))` recipe that fft-peak personas reach for.
    Cabs,
    // `cmul a:L n b:L n > L n` — complex multiply of two [re, im] pairs.
    // Returns a new 2-element [re, im] list. Closes the 4-multiply
    // complex product expansion in signal processing and FFT convolution.
    Cmul,
    // `pairwise f:F xs:L a > L b` — apply binary function f to each
    // adjacent pair (xs[i], xs[i+1]). Output length = `len xs - 1`. Returns
    // `[]` on empty or singleton list. Collapses the
    // `map (i:n>_;f (at xs i) (at xs (+ i 1))) (range 0 (- (len xs) 1))`
    // recipe. Useful for finite differences, running deltas, and
    // neighbour comparisons.
    Pairwise,
    // `pdist2 xs:L n ys:L n > L n` — squared Euclidean distance between
    // paired points, element-wise. Equivalent to
    // `map (i:n>n; pow (- (at xs i) (at ys i)) 2) (range 0 (len xs))`.
    // Lists must have the same length; mismatch raises ILO-R009. Closes the
    // distance-matrix loop that pairwise-distance personas write.
    Pdist2,

    // `run-full-env cmd:t args:L t > R (M t t) t` — like `run` but inherits
    // the full parent environment (including sensitive vars like ANTHROPIC_API_KEY,
    // GITHUB_TOKEN, etc.). Opt-in; prefer `run` which scrubs secrets by default.
    // Tree-bridge eligible alongside `run`.
    RunFullEnv,
    // `run2-full-env cmd:t args:L t > R RunResult t` — like `run2` but inherits
    // the full parent environment. Opt-in; prefer `run2` which scrubs secrets by default.
    // Tree-bridge eligible alongside `run2`.
    Run2FullEnv,
    // `spawn fn args... > _` (ILO-477) — fire-and-forget background OS thread.
    // First arg is the callable (FnRef / Text / Closure); remaining args are
    // forwarded to it. Returns Nil immediately; the thread runs to completion
    // independently. Runtime errors and panics inside the thread are logged to
    // stderr and the thread dies; the parent is unaffected.
    //
    // Caps are inherited from the parent via `Arc::clone(&env.caps)` — no new
    // cap flag. Tree-walker only at runtime; VM/Cranelift inherit via the
    // tree-bridge (same shape as `par-map` / `for-line`).
    //
    // Out of scope for v1 (separate tickets): join handles, channels,
    // supervision, cancellation, async runtime.
    Spawn,
}

impl Builtin {
    /// Resolve a canonical builtin name to its enum variant.
    /// Returns `None` for user-defined functions.
    pub fn from_name(s: &str) -> Option<Builtin> {
        match s {
            "str" => Some(Builtin::Str),
            "num" => Some(Builtin::Num),
            "abs" => Some(Builtin::Abs),
            "flr" => Some(Builtin::Flr),
            "cel" => Some(Builtin::Cel),
            "rou" => Some(Builtin::Rou),
            "min" => Some(Builtin::Min),
            "max" => Some(Builtin::Max),
            "mod" => Some(Builtin::Mod),
            "fmod" => Some(Builtin::Fmod),
            "clamp" => Some(Builtin::Clamp),
            "pow" => Some(Builtin::Pow),
            "sqrt" => Some(Builtin::Sqrt),
            "log" => Some(Builtin::Log),
            "exp" => Some(Builtin::Exp),
            "sin" => Some(Builtin::Sin),
            "cos" => Some(Builtin::Cos),
            "tan" => Some(Builtin::Tan),
            "log10" => Some(Builtin::Log10),
            "log2" => Some(Builtin::Log2),
            "asin" => Some(Builtin::Asin),
            "acos" => Some(Builtin::Acos),
            "atan" => Some(Builtin::Atan),
            "atan2" => Some(Builtin::Atan2),
            "sum" => Some(Builtin::Sum),
            "prod" => Some(Builtin::Prod),
            "cumsum" => Some(Builtin::Cumsum),
            "cprod" => Some(Builtin::Cprod),
            "ewm" => Some(Builtin::Ewm),
            "avg" => Some(Builtin::Avg),
            "median" => Some(Builtin::Median),
            "quantile" => Some(Builtin::Quantile),
            "stdev" => Some(Builtin::Stdev),
            "variance" => Some(Builtin::Variance),
            "fft" => Some(Builtin::Fft),
            "ifft" => Some(Builtin::Ifft),
            "transpose" => Some(Builtin::Transpose),
            "matmul" => Some(Builtin::Matmul),
            "matvec" => Some(Builtin::Matvec),
            "dot" => Some(Builtin::Dot),
            "len" => Some(Builtin::Len),
            "hd" => Some(Builtin::Hd),
            "at" => Some(Builtin::At),
            "tl" => Some(Builtin::Tl),
            "rev" => Some(Builtin::Rev),
            "srt" => Some(Builtin::Srt),
            "rsrt" => Some(Builtin::Rsrt),
            "slc" => Some(Builtin::Slc),
            "lst" => Some(Builtin::Lst),
            "take" => Some(Builtin::Take),
            "drop" => Some(Builtin::Drop),
            "unq" => Some(Builtin::Unq),
            "flat" => Some(Builtin::Flat),
            "has" => Some(Builtin::Has),
            "spl" => Some(Builtin::Spl),
            "cat" => Some(Builtin::Cat),
            "zip" => Some(Builtin::Zip),
            "enumerate" => Some(Builtin::Enumerate),
            "range" => Some(Builtin::Range),
            "linspace" => Some(Builtin::Linspace),
            "ones" => Some(Builtin::Ones),
            "rep" => Some(Builtin::Rep),
            "window" => Some(Builtin::Window),
            "chunks" => Some(Builtin::Chunks),
            "setunion" => Some(Builtin::Setunion),
            "setinter" => Some(Builtin::Setinter),
            "setdiff" => Some(Builtin::Setdiff),
            "map" => Some(Builtin::Map),
            "flt" => Some(Builtin::Flt),
            "fld" => Some(Builtin::Fld),
            "ct" => Some(Builtin::Ct),
            "grp" => Some(Builtin::Grp),
            "uniqby" => Some(Builtin::Uniqby),
            "partition" => Some(Builtin::Partition),
            "frq" => Some(Builtin::Frq),
            "flatmap" => Some(Builtin::Flatmap),
            "mapr" => Some(Builtin::Mapr),
            "rnd" => Some(Builtin::Rnd),
            "rndn" => Some(Builtin::Rndn),
            "rand-bytes" => Some(Builtin::RandBytes),
            "seed" => Some(Builtin::Seed),
            "now" => Some(Builtin::Now),
            "now-ms" => Some(Builtin::NowMs),
            "dtfmt" => Some(Builtin::Dtfmt),
            "dtparse" => Some(Builtin::Dtparse),
            "dtparse-rel" => Some(Builtin::DtparseRel),
            "sleep" => Some(Builtin::Sleep),
            "tz-offset" => Some(Builtin::TzOffset),
            "rd" => Some(Builtin::Rd),
            "rd-json" => Some(Builtin::RdJson),
            "rdl" => Some(Builtin::Rdl),
            "rdb" => Some(Builtin::Rdb),
            "rdin" => Some(Builtin::Rdin),
            "rdinl" => Some(Builtin::Rdinl),
            "for-line" => Some(Builtin::ForLine),
            "wr" => Some(Builtin::Wr),
            "wra" => Some(Builtin::Wra),
            "wro" => Some(Builtin::Wro),
            "wrl" => Some(Builtin::Wrl),
            "prnt" => Some(Builtin::Prnt),
            "env" => Some(Builtin::Env),
            "world" => Some(Builtin::WorldCap),
            "world-no-net" => Some(Builtin::WorldNoNet),
            "lsd" => Some(Builtin::Ls),
            "walk" => Some(Builtin::Walk),
            "glob" => Some(Builtin::Glob),
            "fsize" => Some(Builtin::Fsize),
            "mtime" => Some(Builtin::Mtime),
            "isfile" => Some(Builtin::Isfile),
            "isdir" => Some(Builtin::Isdir),
            "env-all" => Some(Builtin::EnvAll),
            "trm" => Some(Builtin::Trm),
            "upr" => Some(Builtin::Upr),
            "lwr" => Some(Builtin::Lwr),
            "cap" => Some(Builtin::Cap),
            "padl" => Some(Builtin::Padl),
            "padr" => Some(Builtin::Padr),
            "ord" => Some(Builtin::Ord),
            "chr" => Some(Builtin::Chr),
            "chars" => Some(Builtin::Chars),
            "fmt" => Some(Builtin::Fmt),
            "fmt2" => Some(Builtin::Fmt2),
            "rgx" => Some(Builtin::Rgx),
            "rgxall" => Some(Builtin::Rgxall),
            "rgxall1" => Some(Builtin::Rgxall1),
            "rgxsub" => Some(Builtin::Rgxsub),
            "rgxall-multi" => Some(Builtin::RgxallMulti),
            "jpth" => Some(Builtin::Jpth),
            "jkeys" => Some(Builtin::Jkeys),
            "jdmp" => Some(Builtin::Jdmp),
            "jpar" => Some(Builtin::Jpar),
            "jpar-list" => Some(Builtin::JparList),
            "rdjl" => Some(Builtin::Rdjl),
            "run" => Some(Builtin::Run),
            "run2" => Some(Builtin::Run2),
            "run-bg" => Some(Builtin::RunBg),
            "run-full-env" => Some(Builtin::RunFullEnv),
            "run2-full-env" => Some(Builtin::Run2FullEnv),
            "get" => Some(Builtin::Get),
            // 0.12.0 rename: `post` → `pst`. Brings post into line with the
            // I/O compression family (rd, wr, srt, flt, fld, fmt). Clean
            // break — `post` no longer resolves; the verifier surfaces a
            // did-you-mean to `pst` via the standard suggestion path.
            "pst" => Some(Builtin::Post),
            "get-many" => Some(Builtin::GetMany),
            "get-to" => Some(Builtin::GetTo),
            "pst-to" => Some(Builtin::PstTo),
            "getx" => Some(Builtin::Getx),
            "pstx" => Some(Builtin::Pstx),
            "put" => Some(Builtin::Put),
            "pat" => Some(Builtin::Pat),
            "del" => Some(Builtin::Del),
            "hed" => Some(Builtin::Hed),
            "opt" => Some(Builtin::Opt),
            "get-stream" => Some(Builtin::GetStream),
            "get-stream-h" => Some(Builtin::GetStreamH),
            "pst-stream" => Some(Builtin::PostStream),
            "pst-stream-h" => Some(Builtin::PostStreamH),
            "spawn" => Some(Builtin::Spawn),
            "mmap" => Some(Builtin::Mmap),
            "mget" => Some(Builtin::Mget),
            "mset" => Some(Builtin::Mset),
            "mhas" => Some(Builtin::Mhas),
            "mkeys" => Some(Builtin::Mkeys),
            "mvals" => Some(Builtin::Mvals),
            "mdel" => Some(Builtin::Mdel),
            "mget-or" => Some(Builtin::MgetOr),
            "lget-or" => Some(Builtin::LgetOr),
            "mpairs" => Some(Builtin::Mpairs),
            "solve" => Some(Builtin::Solve),
            "inv" => Some(Builtin::Inv),
            "det" => Some(Builtin::Det),
            "lstsq" => Some(Builtin::Lstsq),
            "argmax" => Some(Builtin::Argmax),
            "argmin" => Some(Builtin::Argmin),
            "argsort" => Some(Builtin::Argsort),
            "bisect" => Some(Builtin::Bisect),
            "convolve" => Some(Builtin::Convolve),
            "searchsorted" => Some(Builtin::Searchsorted),
            "cabs" => Some(Builtin::Cabs),
            "cmul" => Some(Builtin::Cmul),
            "pairwise" => Some(Builtin::Pairwise),
            "pdist2" => Some(Builtin::Pdist2),
            "par-map" => Some(Builtin::ParMap),
            "dirname" => Some(Builtin::Dirname),
            "basename" => Some(Builtin::Basename),
            "pathjoin" => Some(Builtin::Pathjoin),
            "pi" => Some(Builtin::Pi),
            "tau" => Some(Builtin::Tau),
            "e" => Some(Builtin::Eu),
            "dur-parse" => Some(Builtin::DurParse),
            "dur-fmt" => Some(Builtin::DurFmt),
            "default-on-err" => Some(Builtin::DefaultOnErr),
            "urlenc" => Some(Builtin::Urlenc),
            "urldec" => Some(Builtin::Urldec),
            "b64u" => Some(Builtin::B64u),
            "b64u-dec" => Some(Builtin::B64uDec),
            "sha256" => Some(Builtin::Sha256),
            "hmac-sha256" => Some(Builtin::HmacSha256),
            "b64" => Some(Builtin::B64),
            "b64-dec" => Some(Builtin::B64Dec),
            "hex" => Some(Builtin::HexEnc),
            "ct-eq" => Some(Builtin::CtEq),
            "sha256-hex" => Some(Builtin::Sha256Hex),
            "sha256d" => Some(Builtin::Sha256d),
            "hex-rev" => Some(Builtin::HexRev),
            "tokcount" => Some(Builtin::Tokcount),
            "where" => Some(Builtin::Where),
            "add-mo" => Some(Builtin::AddMo),
            "last-dom" => Some(Builtin::LastDom),
            "next-business-day" => Some(Builtin::NextBusinessDay),
            "day-of-week" => Some(Builtin::DayOfWeek),
            "rsum" => Some(Builtin::Rsum),
            "ravg" => Some(Builtin::Ravg),
            "rmin" => Some(Builtin::Rmin),
            "idxof" => Some(Builtin::Idxof),
            "band" => Some(Builtin::Band),
            "bor" => Some(Builtin::Bor),
            "bxor" => Some(Builtin::Bxor),
            "bnot" => Some(Builtin::Bnot),
            "bshl" => Some(Builtin::Bshl),
            "bshr" => Some(Builtin::Bshr),
            "brot" => Some(Builtin::Brot),
            "band64" => Some(Builtin::Band64),
            "bor64" => Some(Builtin::Bor64),
            "bxor64" => Some(Builtin::Bxor64),
            "bnot64" => Some(Builtin::Bnot64),
            "bshl64" => Some(Builtin::Bshl64),
            "bshr64" => Some(Builtin::Bshr64),
            "brot64" => Some(Builtin::Brot64),
            "arange" => Some(Builtin::Arange),
            "zeros" => Some(Builtin::Zeros),
            "vstack" => Some(Builtin::Vstack),
            "hstack" => Some(Builtin::Hstack),
            "column-stack" => Some(Builtin::ColumnStack),
            "hist" => Some(Builtin::Hist),
            _ => None,
        }
    }

    /// Return the canonical short name for this builtin.
    #[allow(dead_code)]
    pub fn name(self) -> &'static str {
        match self {
            Builtin::Str => "str",
            Builtin::Num => "num",
            Builtin::Abs => "abs",
            Builtin::Flr => "flr",
            Builtin::Cel => "cel",
            Builtin::Rou => "rou",
            Builtin::Min => "min",
            Builtin::Max => "max",
            Builtin::Mod => "mod",
            Builtin::Fmod => "fmod",
            Builtin::Clamp => "clamp",
            Builtin::Pow => "pow",
            Builtin::Sqrt => "sqrt",
            Builtin::Log => "log",
            Builtin::Exp => "exp",
            Builtin::Sin => "sin",
            Builtin::Cos => "cos",
            Builtin::Tan => "tan",
            Builtin::Log10 => "log10",
            Builtin::Log2 => "log2",
            Builtin::Asin => "asin",
            Builtin::Acos => "acos",
            Builtin::Atan => "atan",
            Builtin::Atan2 => "atan2",
            Builtin::Sum => "sum",
            Builtin::Prod => "prod",
            Builtin::Cumsum => "cumsum",
            Builtin::Cprod => "cprod",
            Builtin::Ewm => "ewm",
            Builtin::Avg => "avg",
            Builtin::Median => "median",
            Builtin::Quantile => "quantile",
            Builtin::Stdev => "stdev",
            Builtin::Variance => "variance",
            Builtin::Fft => "fft",
            Builtin::Ifft => "ifft",
            Builtin::Transpose => "transpose",
            Builtin::Matmul => "matmul",
            Builtin::Matvec => "matvec",
            Builtin::Dot => "dot",
            Builtin::Len => "len",
            Builtin::Hd => "hd",
            Builtin::At => "at",
            Builtin::Tl => "tl",
            Builtin::Rev => "rev",
            Builtin::Srt => "srt",
            Builtin::Rsrt => "rsrt",
            Builtin::Slc => "slc",
            Builtin::Lst => "lst",
            Builtin::Take => "take",
            Builtin::Drop => "drop",
            Builtin::Unq => "unq",
            Builtin::Flat => "flat",
            Builtin::Has => "has",
            Builtin::Spl => "spl",
            Builtin::Cat => "cat",
            Builtin::Zip => "zip",
            Builtin::Enumerate => "enumerate",
            Builtin::Range => "range",
            Builtin::Linspace => "linspace",
            Builtin::Ones => "ones",
            Builtin::Rep => "rep",
            Builtin::Window => "window",
            Builtin::Chunks => "chunks",
            Builtin::Setunion => "setunion",
            Builtin::Setinter => "setinter",
            Builtin::Setdiff => "setdiff",
            Builtin::Map => "map",
            Builtin::Flt => "flt",
            Builtin::Fld => "fld",
            Builtin::Ct => "ct",
            Builtin::Grp => "grp",
            Builtin::Uniqby => "uniqby",
            Builtin::Partition => "partition",
            Builtin::Frq => "frq",
            Builtin::Flatmap => "flatmap",
            Builtin::Mapr => "mapr",
            Builtin::Rnd => "rnd",
            Builtin::Rndn => "rndn",
            Builtin::RandBytes => "rand-bytes",
            Builtin::Seed => "seed",
            Builtin::Now => "now",
            Builtin::NowMs => "now-ms",
            Builtin::Dtfmt => "dtfmt",
            Builtin::Dtparse => "dtparse",
            Builtin::DtparseRel => "dtparse-rel",
            Builtin::Sleep => "sleep",
            Builtin::TzOffset => "tz-offset",
            Builtin::Rd => "rd",
            Builtin::RdJson => "rd-json",
            Builtin::Rdl => "rdl",
            Builtin::Rdb => "rdb",
            Builtin::Rdin => "rdin",
            Builtin::Rdinl => "rdinl",
            Builtin::ForLine => "for-line",
            Builtin::Wr => "wr",
            Builtin::Wra => "wra",
            Builtin::Wro => "wro",
            Builtin::Wrl => "wrl",
            Builtin::Prnt => "prnt",
            Builtin::Env => "env",
            Builtin::WorldCap => "world",
            Builtin::WorldNoNet => "world-no-net",
            Builtin::Ls => "lsd",
            Builtin::Walk => "walk",
            Builtin::Glob => "glob",
            Builtin::Fsize => "fsize",
            Builtin::Mtime => "mtime",
            Builtin::Isfile => "isfile",
            Builtin::Isdir => "isdir",
            Builtin::EnvAll => "env-all",
            Builtin::Trm => "trm",
            Builtin::Upr => "upr",
            Builtin::Lwr => "lwr",
            Builtin::Cap => "cap",
            Builtin::Padl => "padl",
            Builtin::Padr => "padr",
            Builtin::Ord => "ord",
            Builtin::Chr => "chr",
            Builtin::Chars => "chars",
            Builtin::Fmt => "fmt",
            Builtin::Fmt2 => "fmt2",
            Builtin::Rgx => "rgx",
            Builtin::Rgxall => "rgxall",
            Builtin::Rgxall1 => "rgxall1",
            Builtin::Rgxsub => "rgxsub",
            Builtin::RgxallMulti => "rgxall-multi",
            Builtin::Jpth => "jpth",
            Builtin::Jkeys => "jkeys",
            Builtin::Jdmp => "jdmp",
            Builtin::Jpar => "jpar",
            Builtin::JparList => "jpar-list",
            Builtin::Rdjl => "rdjl",
            Builtin::Run => "run",
            Builtin::Run2 => "run2",
            Builtin::RunBg => "run-bg",
            Builtin::RunFullEnv => "run-full-env",
            Builtin::Run2FullEnv => "run2-full-env",
            Builtin::Get => "get",
            Builtin::Post => "pst",
            Builtin::GetMany => "get-many",
            Builtin::GetTo => "get-to",
            Builtin::PstTo => "pst-to",
            Builtin::Getx => "getx",
            Builtin::Pstx => "pstx",
            Builtin::Put => "put",
            Builtin::Pat => "pat",
            Builtin::Del => "del",
            Builtin::Hed => "hed",
            Builtin::Opt => "opt",
            Builtin::GetStream => "get-stream",
            Builtin::GetStreamH => "get-stream-h",
            Builtin::PostStream => "pst-stream",
            Builtin::PostStreamH => "pst-stream-h",
            Builtin::Spawn => "spawn",
            Builtin::Mmap => "mmap",
            Builtin::Mget => "mget",
            Builtin::Mset => "mset",
            Builtin::Mhas => "mhas",
            Builtin::Mkeys => "mkeys",
            Builtin::Mvals => "mvals",
            Builtin::Mdel => "mdel",
            Builtin::MgetOr => "mget-or",
            Builtin::LgetOr => "lget-or",
            Builtin::Mpairs => "mpairs",
            Builtin::Solve => "solve",
            Builtin::Inv => "inv",
            Builtin::Det => "det",
            Builtin::Lstsq => "lstsq",
            Builtin::Argmax => "argmax",
            Builtin::Argmin => "argmin",
            Builtin::Argsort => "argsort",
            Builtin::Bisect => "bisect",
            Builtin::Convolve => "convolve",
            Builtin::Searchsorted => "searchsorted",
            Builtin::Cabs => "cabs",
            Builtin::Cmul => "cmul",
            Builtin::Pairwise => "pairwise",
            Builtin::Pdist2 => "pdist2",
            Builtin::ParMap => "par-map",
            Builtin::Dirname => "dirname",
            Builtin::Basename => "basename",
            Builtin::Pathjoin => "pathjoin",
            Builtin::Pi => "pi",
            Builtin::Tau => "tau",
            Builtin::Eu => "e",
            Builtin::DurParse => "dur-parse",
            Builtin::DurFmt => "dur-fmt",
            Builtin::DefaultOnErr => "default-on-err",
            Builtin::Urlenc => "urlenc",
            Builtin::Urldec => "urldec",
            Builtin::B64u => "b64u",
            Builtin::B64uDec => "b64u-dec",
            Builtin::Sha256 => "sha256",
            Builtin::HmacSha256 => "hmac-sha256",
            Builtin::B64 => "b64",
            Builtin::B64Dec => "b64-dec",
            Builtin::HexEnc => "hex",
            Builtin::CtEq => "ct-eq",
            Builtin::Sha256Hex => "sha256-hex",
            Builtin::Sha256d => "sha256d",
            Builtin::HexRev => "hex-rev",
            Builtin::Tokcount => "tokcount",
            Builtin::Where => "where",
            Builtin::AddMo => "add-mo",
            Builtin::LastDom => "last-dom",
            Builtin::NextBusinessDay => "next-business-day",
            Builtin::DayOfWeek => "day-of-week",
            Builtin::Rsum => "rsum",
            Builtin::Ravg => "ravg",
            Builtin::Rmin => "rmin",
            Builtin::Idxof => "idxof",
            Builtin::Band => "band",
            Builtin::Bor => "bor",
            Builtin::Bxor => "bxor",
            Builtin::Bnot => "bnot",
            Builtin::Bshl => "bshl",
            Builtin::Bshr => "bshr",
            Builtin::Brot => "brot",
            Builtin::Band64 => "band64",
            Builtin::Bor64 => "bor64",
            Builtin::Bxor64 => "bxor64",
            Builtin::Bnot64 => "bnot64",
            Builtin::Bshl64 => "bshl64",
            Builtin::Bshr64 => "bshr64",
            Builtin::Brot64 => "brot64",
            Builtin::Arange => "arange",
            Builtin::Zeros => "zeros",
            Builtin::Vstack => "vstack",
            Builtin::Hstack => "hstack",
            Builtin::ColumnStack => "column-stack",
            Builtin::Hist => "hist",
        }
    }

    /// Check if a name refers to a builtin function.
    pub fn is_builtin(name: &str) -> bool {
        Self::from_name(name).is_some()
    }

    /// Stable list of every `Builtin` variant, in canonical order.
    ///
    /// The position of each variant in this slice is its on-wire tag
    /// for `OP_CALL_BUILTIN_TREE`. Stability matters: appending is fine,
    /// reordering or removing entries breaks any persisted bytecode.
    pub const ALL: &'static [Builtin] = &[
        Builtin::Str,
        Builtin::Num,
        Builtin::Abs,
        Builtin::Flr,
        Builtin::Cel,
        Builtin::Rou,
        Builtin::Min,
        Builtin::Max,
        Builtin::Mod,
        Builtin::Fmod,
        Builtin::Clamp,
        Builtin::Pow,
        Builtin::Sqrt,
        Builtin::Log,
        Builtin::Exp,
        Builtin::Sin,
        Builtin::Cos,
        Builtin::Tan,
        Builtin::Log10,
        Builtin::Log2,
        Builtin::Asin,
        Builtin::Acos,
        Builtin::Atan,
        Builtin::Atan2,
        Builtin::Sum,
        Builtin::Prod,
        Builtin::Cumsum,
        Builtin::Cprod,
        Builtin::Avg,
        Builtin::Median,
        Builtin::Quantile,
        Builtin::Stdev,
        Builtin::Variance,
        Builtin::Fft,
        Builtin::Ifft,
        Builtin::Transpose,
        Builtin::Matmul,
        Builtin::Dot,
        Builtin::Len,
        Builtin::Hd,
        Builtin::At,
        Builtin::Tl,
        Builtin::Rev,
        Builtin::Srt,
        Builtin::Rsrt,
        Builtin::Slc,
        Builtin::Lst,
        Builtin::Take,
        Builtin::Drop,
        Builtin::Unq,
        Builtin::Flat,
        Builtin::Has,
        Builtin::Spl,
        Builtin::Cat,
        Builtin::Zip,
        Builtin::Enumerate,
        Builtin::Range,
        Builtin::Window,
        Builtin::Chunks,
        Builtin::Setunion,
        Builtin::Setinter,
        Builtin::Setdiff,
        Builtin::Map,
        Builtin::Flt,
        Builtin::Fld,
        Builtin::Grp,
        Builtin::Uniqby,
        Builtin::Partition,
        Builtin::Frq,
        Builtin::Flatmap,
        Builtin::Mapr,
        Builtin::Rnd,
        Builtin::Rndn,
        Builtin::Seed,
        Builtin::Now,
        Builtin::Dtfmt,
        Builtin::Dtparse,
        Builtin::DtparseRel,
        Builtin::Rd,
        Builtin::RdJson,
        Builtin::Rdl,
        Builtin::Rdb,
        Builtin::Wr,
        Builtin::Wra,
        Builtin::Wro,
        Builtin::Wrl,
        Builtin::Prnt,
        Builtin::Env,
        Builtin::WorldCap,
        Builtin::WorldNoNet,
        Builtin::Trm,
        Builtin::Upr,
        Builtin::Lwr,
        Builtin::Cap,
        Builtin::Padl,
        Builtin::Padr,
        Builtin::Ord,
        Builtin::Chr,
        Builtin::Chars,
        Builtin::Fmt,
        Builtin::Fmt2,
        Builtin::Rgx,
        Builtin::Rgxall,
        Builtin::Rgxsub,
        Builtin::Jpth,
        Builtin::Jkeys,
        Builtin::Jdmp,
        Builtin::Jpar,
        Builtin::JparList,
        Builtin::Rdjl,
        Builtin::Get,
        Builtin::Post,
        Builtin::GetMany,
        Builtin::Mmap,
        Builtin::Mget,
        Builtin::Mset,
        Builtin::Mhas,
        Builtin::Mkeys,
        Builtin::Mvals,
        Builtin::Mdel,
        Builtin::Solve,
        Builtin::Inv,
        Builtin::Det,
        Builtin::Sleep,
        // Appended after Sleep to preserve every existing tag. Rgxall1 is a
        // convenience over Rgxall (flat first-capture-group list); see the
        // tree-bridge entry in src/vm/mod.rs for cross-engine dispatch.
        Builtin::Rgxall1,
        // Ct fn xs -> n: count-by-predicate. Tree-bridge eligible alongside
        // its HOF peers (Flt, Map, Grp); see is_tree_bridge_eligible.
        // Named `ct` (not `cnt`) because `cnt` is reserved as the loop
        // continue keyword — see src/parser/mod.rs:3507.
        Builtin::Ct,
        // Appended last to preserve existing on-wire tags. now-ms returns
        // the current Unix epoch in milliseconds as f64 — paired with `now`
        // (seconds) so per-phase timing has no rounding loss in agent
        // perf-bisection workloads.
        Builtin::NowMs,
        // Filesystem enumeration. Closes the categorical gap vs Python rglob
        // and shell `find`: single-file `rd` exists but no directory listing
        // until now. All three return Result so missing-dir / permission-denied
        // are typed at the boundary. Tree-bridge eligible; no native opcodes.
        Builtin::Ls,
        Builtin::Walk,
        Builtin::Glob,
        // env-all -> R M t t: full process environment as Map[Text, Text]
        // wrapped in Result. Tree-bridge eligible (zero args, no FnRef);
        // see is_tree_bridge_eligible in src/vm/mod.rs.
        Builtin::EnvAll,
        // `run cmd:t args:L t > R (M t) t` — argv-list process spawn.
        // No shell, no interpolation, no glob — the principled defence
        // against shell injection in agent orchestration. See SPEC.md
        // "Process spawn" + the tree-bridge entry in src/vm/mod.rs.
        Builtin::Run,
        // 0.12.1: defaulted lookups for Map and List. Both lower through the
        // tree-bridge (OP_CALL_BUILTIN_TREE), so no new opcodes; appending
        // here keeps every existing on-wire tag stable.
        Builtin::MgetOr,
        Builtin::LgetOr,
        // Index-returning aggregates (numpy convention). Pure list ops:
        // tree-bridge eligible, no FnRef args, no I/O. Closes the
        // `srt fn (enumerate xs)` + extract-first pattern that three
        // rerun12 personas converged on. Appended to preserve tags.
        Builtin::Argmax,
        Builtin::Argmin,
        Builtin::Argsort,
        // Path manipulation builtins. Pure text ops, POSIX semantics,
        // forward-slash only (Windows paths are a 0.13.0 concern).
        // Tree-bridge eligible like the lsd/walk/glob trio, but with no
        // Result wrapper — see is_tree_bridge_eligible in src/vm/mod.rs.
        Builtin::Dirname,
        Builtin::Basename,
        Builtin::Pathjoin,
        // 0.12.1: stdin read primitives. Unblocks the Unix-pipeline persona
        // class — `rd` is file-only; child stdin was Stdio::null() previously.
        // `rdin > R t t` reads all of stdin; `rdinl > R (L t) t` is line-mode.
        // Both are 0-arg and tree-bridge eligible. Appended to preserve tags.
        Builtin::Rdin,
        Builtin::Rdinl,
        // `mpairs m > L (L _)` — sorted-by-key list of [k, v] 2-element lists.
        // Invariant: `mpairs m == zip (mkeys m) (mvals m)`. Kills the common
        // `map (fn k > [k (mget m k)]) (mkeys m)` cascade — one builtin call
        // instead of lambda + mkeys + mget per iteration. Added in 0.12.1.
        Builtin::Mpairs,
        // `rgxall-multi pats:L t line:t > L t` — multi-pattern flat-match.
        // Equivalent to `flat (map (p:t>L t;rgxall1 p line) pats)` but saves
        // ~20 tokens per call site. cron-explainer and historical-archeologist
        // both wanted this: apply several patterns to one line and get a single
        // flat list of all hits in pattern order. Tree-bridge eligible alongside
        // rgxall1 — same dispatch path, no new opcodes.
        Builtin::RgxallMulti,
        // Math constants (0.12.1). Appended last to preserve on-wire tag
        // stability for every prior builtin. Zero-arg, tree-bridge-eligible.
        Builtin::Pi,
        Builtin::Tau,
        Builtin::Eu,
        // Duration parse / format. Tree-bridge eligible: pure text↔number, no
        // I/O, no FnRef args. DurParse returns R n t so that malformed input
        // surfaces as a typed error at the boundary. DurFmt is total (always
        // returns a text string). Appended here to preserve every existing tag.
        Builtin::DurParse,
        Builtin::DurFmt,
        // `default-on-err r d > T` — Result mirror of `??`. Unwraps `R T E`
        // to `T`, returning `d` on `Err`. Kills the common `?r{~v:v ^_:default}`
        // pattern. Tree-bridge eligible (2-arg, pure). Added in 0.12.1.
        Builtin::DefaultOnErr,
        // Calendar arithmetic (0.12.2). Pure epoch↔epoch/n ops, no FnRef, no I/O.
        // Tree-bridge eligible: VM + Cranelift inherit for free without new opcodes.
        // Appended to preserve all existing on-wire tags.
        Builtin::AddMo,
        Builtin::LastDom,
        Builtin::NextBusinessDay,
        Builtin::DayOfWeek,
        // 0.12.1 filesystem metadata primitives. Atomic singletons rather
        // than a fat `stat path > R (M t t) t`: agents that want size pay
        // size cost, agents that want a predicate pay predicate cost. Size
        // / mtime return Result (open-and-stat can fail); predicates return
        // bool (Python convention - `false` collapses missing / perm-denied
        // / wrong-kind into the natural branch). All four are tree-bridge
        // eligible; no native opcodes.
        Builtin::Fsize,
        Builtin::Mtime,
        Builtin::Isfile,
        Builtin::Isdir,
        // 0.12.1: HTTP builtins with explicit per-request timeout. Appended
        // last to preserve every existing on-wire tag. Tree-bridge eligible
        // so VM and Cranelift JIT/AOT inherit them without new opcodes.
        // minreq `with_timeout` takes whole seconds; millisecond values are
        // rounded up (ceil(ms / 1000)) so 1 ms => 1 s, 1001 ms => 2 s.
        Builtin::GetTo,
        Builtin::PstTo,
        // `matvec xm ys > L n` — native matrix-vector multiply. Tree-bridge
        // eligible: composes the same row/vector helpers as `matmul`, so VM
        // and Cranelift inherit through the bridge without new opcodes.
        // Appended to preserve every existing tag.
        Builtin::Matvec,
        // `lstsq xm ys > L n` — ordinary least squares via the normal
        // equations. Tree-bridge eligible: composes existing transpose /
        // matmul / solve so VM and Cranelift inherit through the bridge
        // without new opcodes. Appended to preserve every existing tag.
        Builtin::Lstsq,
        // `rand-bytes n > t` — cryptographically random bytes, base64url-no-pad encoded.
        // Distinct from `rnd` (uniform float) and `rndn` (Normal float): this is the
        // CSPRNG path agents need for jti / CSRF tokens / session IDs / nonces. Output
        // is base64url-no-pad so it drops straight into headers, cookies, query strings
        // without further encoding. Tree-bridge eligible (arity 1, no FnRef, no I/O
        // wrap). Appended last to preserve on-wire tags. Backed by `getrandom`, not
        // `fastrand` — cryptographic randomness must never be seeded.
        Builtin::RandBytes,
        // 0.12.1: URL + base64url encoding cluster. Appended last to preserve
        // every existing on-wire tag. Tree-bridge eligible — pure text-in /
        // text-out, no FnRef args, no I/O. Backed by the `percent-encoding`
        // and `base64` crates. The two decoders return Result so malformed
        // input surfaces as a typed error at the boundary; the two encoders
        // are total (always produce Text).
        Builtin::Urlenc,
        Builtin::Urldec,
        Builtin::B64u,
        Builtin::B64uDec,
        // ewm xs a > L n — exponential moving average with smoothing factor a
        // in [0, 1]. Pure number-list reducer; tree-bridge eligible alongside
        // the cumsum/cprod aggregate family. Appended last to preserve every
        // existing on-wire tag.
        Builtin::Ewm,
        // where cond xs ys > L a — parallel-list conditional select (NumPy
        // np.where equivalent). Tree-bridge eligible (3-arg, no FnRef, no I/O,
        // no Result wrapper). Appended last to preserve every existing on-wire
        // tag.
        Builtin::Where,
        // `tz-offset tz:t epoch:n > R n t` — UTC offset in seconds for the
        // given IANA timezone at the given Unix epoch. DST-aware via chrono-tz.
        // Returns Err on unknown timezone name. Tree-bridge eligible (2-arg,
        // no FnRef). Appended to preserve all prior on-wire tags.
        Builtin::TzOffset,
        // `run2 cmd:t args:L t > R RunResult t` - structured process spawn.
        // Returns a typed Record{stdout:t; stderr:t; exit:n} rather than the
        // loose M t t that `run` returns, giving clean dot-access. Appended
        // last to preserve every existing on-wire tag; tree-bridge eligible.
        Builtin::Run2,
        // `run-bg cmd:t args:L t > R n t` — fire-and-forget background spawn.
        // Returns Ok(pid:n) immediately; child inherits parent stdout/stderr.
        // Err only on spawn failure. Appended last to preserve every existing
        // on-wire tag; tree-bridge eligible.
        Builtin::RunBg,
        // Numeric prelude (0.12.1). Three list constructors hit repeatedly by
        // linear-regression (linspace for evenly-spaced sample points),
        // distance-matrix (ones for a design-matrix column), and monte-carlo
        // (rep for seeding accumulators). Tree-bridge eligible — pure, no
        // FnRef args, no I/O, no Result wrapper. Appended last to preserve
        // every existing on-wire tag.
        Builtin::Linspace,
        Builtin::Ones,
        Builtin::Rep,
        // HTTP verb cluster (#5z). Tree-bridge eligible — same shape as `pst`
        // (optional headers, R t t return). Appended last to preserve every
        // existing on-wire tag.
        Builtin::Put,
        Builtin::Pat,
        Builtin::Del,
        Builtin::Hed,
        Builtin::Opt,
        // Crypto primitives cluster (0.12.x). All tree-bridge eligible — pure
        // text-in / text-or-bool-out, no FnRef args, no I/O. VM and Cranelift
        // JIT inherit through the existing bridge at zero opcode cost. Order
        // here is the on-wire dispatch order; appended last to preserve every
        // existing tag.
        //
        // sha256 / hmac-sha256: lowercase hex digest output. Backed by `sha2`
        // and `hmac` crates from the RustCrypto suite.
        // b64 / b64-dec: standard base64 with `=` padding (RFC 4648 §4),
        // distinct from b64u / b64u-dec which use the URL-safe alphabet.
        // hex: lowercase hex encode of the UTF-8 bytes of the input text.
        // ct-eq: constant-time text equality. Use when comparing secrets
        // (HMAC digests, tokens) so a short-circuit `=` doesn't leak timing.
        Builtin::Sha256,
        Builtin::HmacSha256,
        Builtin::B64,
        Builtin::B64Dec,
        Builtin::HexEnc,
        Builtin::CtEq,
        Builtin::Sha256Hex,
        Builtin::Sha256d,
        // getx / pstx — HTTP variants that surface response status, headers,
        // and body as a Map[Text, _] wrapped in Ok. Additive — the existing
        // `get` / `pst` body-only signatures stay intact for token-cheap GETs
        // that don't care about metadata. Tree-bridge eligible (returns
        // Result, no FnRef args), so VM and Cranelift inherit without new
        // opcodes. Appended last to preserve every prior on-wire tag.
        Builtin::Getx,
        Builtin::Pstx,
        // Rolling-window reducers (#5bq). Pure number-list reducers with a
        // fixed window size; output length = `len xs - n + 1`. O(n)
        // amortised via running-sum (rsum/ravg) and monotonic-deque (rmin),
        // not O(n*w) like the naive `slc + sum` recipe. Tree-bridge eligible:
        // VM and Cranelift inherit through OP_CALL_BUILTIN_TREE at zero
        // opcode cost. Appended last to preserve every existing on-wire tag.
        Builtin::Rsum,
        Builtin::Ravg,
        Builtin::Rmin,
        // `hex-rev s > t` — byte-pair reversal of a hex-encoded string.
        // Even-length hex input only; odd length errors ILO-T013.
        // Tree-bridge eligible: pure t → t, no FnRef, no I/O. Appended
        // last to preserve every existing on-wire tag.
        Builtin::HexRev,
        // `bisect xs target > n` — O(log N) insertion point in a sorted
        // numeric list (Python `bisect_left` semantics). Tree-bridge
        // eligible: pure 2-arg, no FnRef, no Result wrapper. Appended last
        // to preserve every existing on-wire tag.
        Builtin::Bisect,
        // `for-line stdin > LazyStdinLines` — lazy stdin line iterator (ILO-70).
        // Returns a LazyStdinLines handle that ForEach drains one line at a time,
        // enabling processing of unbounded piped input without buffering.
        Builtin::ForLine,
        // `idxof s sub > O n` — text-search builtin (0.13.0).
        Builtin::Idxof,
        // tokcount (ILO-47): approximate cl100k_base token count (bytes/3.4 stub).
        // Follow-up (ILO-413) will replace this stub with the full tiktoken-rs BPE
        // tokeniser once the crate's WASM and licence story is confirmed.
        // Appended last to preserve every existing on-wire tag.
        Builtin::Tokcount,
        // Bitwise ops (ILO-58 MVP). All tree-bridge eligible: pure numeric-in /
        // numeric-out, no FnRef args, no I/O, no Result wrapper. Inputs
        // truncated to u32 mod 2^32; output returned as f64. Appended last
        // to preserve every existing on-wire tag.
        Builtin::Band,
        Builtin::Bor,
        Builtin::Bxor,
        Builtin::Bnot,
        Builtin::Bshl,
        Builtin::Bshr,
        Builtin::Brot,
        // 64-bit bitwise ops (ILO-395). All tree-bridge eligible: pure numeric-in /
        // numeric-out, no FnRef args, no I/O, no Result wrapper. Inputs
        // truncated to u64 mod 2^64; output returned as f64. Appended last
        // to preserve every existing on-wire tag.
        Builtin::Band64,
        Builtin::Bor64,
        Builtin::Bxor64,
        Builtin::Bnot64,
        Builtin::Bshl64,
        Builtin::Bshr64,
        Builtin::Brot64,
        // Numeric-pipeline primitives (0.13.0). Appended last; tree-bridge
        // eligible. Preserves all existing on-wire tags.
        Builtin::Arange,
        Builtin::Zeros,
        Builtin::Vstack,
        Builtin::Hstack,
        Builtin::ColumnStack,
        Builtin::Hist,
        // Signal/math cluster (0.13.0). All tree-bridge eligible: pure numeric
        // list / complex-pair ops, no FnRef args (except pairwise), no I/O.
        // Appended last to preserve every existing on-wire tag.
        Builtin::Convolve,
        Builtin::Searchsorted,
        Builtin::Cabs,
        Builtin::Cmul,
        Builtin::Pairwise,
        Builtin::Pdist2,
        // `par-map fn xs n > L (R b t)` — general parallel fan-out: apply `fn`
        // to each element of `xs`, up to `n` items in parallel, order-preserving.
        // Per-item Ok/Err are surfaced in the result list so a single worker
        // failure does not short-circuit the whole operation. `n` defaults to
        // num_cpus when zero or omitted. VM and Cranelift bail out to the tree
        // interpreter (tree-bridge eligible via is_tree_bridge_eligible). Added
        // in 0.12.2 as the recommended general concurrency primitive.
        Builtin::ParMap,
        // `run-full-env cmd:t args:L t > R (M t t) t` — opt-in full-env
        // variant of `run`. The default `run` scrubs ANTHROPIC_*, CLAUDE_*,
        // GITHUB_TOKEN, *_TOKEN, *_KEY, *_SECRET from the child env; use
        // `run-full-env` when the child legitimately needs those vars.
        // Tree-bridge eligible alongside `run`.
        Builtin::RunFullEnv,
        // `run2-full-env cmd:t args:L t > R RunResult t` — opt-in full-env
        // variant of `run2`. Same policy as `run-full-env`.
        Builtin::Run2FullEnv,
        // HTTP streaming client (ILO-46). Lazy-line iterators consumable via
        // `@line stream {...}` foreach. Appended last to preserve every
        // existing on-wire tag.
        Builtin::GetStream,
        Builtin::GetStreamH,
        Builtin::PostStream,
        Builtin::PostStreamH,
        // `spawn fn args... > _` (ILO-477) — fire-and-forget background thread.
        // Tree-walker only at runtime; VM/Cranelift inherit via the tree
        // bridge. Variadic shape: first arg is the callable, the rest are
        // forwarded to it. Appended last to preserve every existing on-wire tag.
        Builtin::Spawn,
    ];

    /// Stability tier for this builtin, sourced from `STABILITY.md`.
    ///
    /// - `"experimental"` — unreleased (above `0.12.1` in `CHANGELOG.md`).
    ///   May be removed or changed without notice.
    /// - `"provisional"` — shipped in a released version (0.12.1 or earlier).
    ///   Signature may change pre-1.0; canonical short name is stable-ish.
    ///
    /// Used by `ilo spec --json ai` to emit per-item stability annotations.
    pub fn stability(self) -> &'static str {
        match self {
            // Unreleased additions (above 0.12.1 in CHANGELOG.md → experimental).
            Builtin::Matvec
            | Builtin::Lstsq
            | Builtin::JparList
            | Builtin::GetTo
            | Builtin::PstTo
            | Builtin::TzOffset
            | Builtin::Run2
            | Builtin::RunBg
            | Builtin::RgxallMulti
            | Builtin::Fmod
            | Builtin::DtparseRel
            | Builtin::DurParse
            | Builtin::DurFmt
            | Builtin::Idxof
            | Builtin::HexRev
            | Builtin::Tokcount
            // Numeric-pipeline primitives (0.13.0) — experimental.
            | Builtin::Arange
            | Builtin::Zeros
            | Builtin::Vstack
            | Builtin::Hstack
            | Builtin::ColumnStack
            | Builtin::Hist
            // Signal/math cluster (0.13.0) — experimental until released.
            | Builtin::Convolve
            | Builtin::Searchsorted
            | Builtin::Cabs
            | Builtin::Cmul
            | Builtin::Pairwise
            | Builtin::Pdist2
            // HTTP streaming client (ILO-46) — experimental until released.
            | Builtin::GetStream
            | Builtin::GetStreamH
            | Builtin::PostStream
            | Builtin::PostStreamH
            // Spawn (ILO-477) — experimental until released.
            | Builtin::Spawn => "experimental",

            // Everything else shipped in 0.12.1 or earlier → provisional.
            _ => "provisional",
        }
    }

    /// On-wire 8-bit tag for cross-engine builtin dispatch. See `ALL`.
    pub fn tag(self) -> u8 {
        // Linear search over a small dense table; this is only called
        // at compile time by the bytecode emitter, not on the hot path.
        Self::ALL
            .iter()
            .position(|b| *b == self)
            .expect("Builtin::ALL must include every variant") as u8
    }

    /// Inverse of `tag`. Returns `None` for unknown tags so the VM/JIT
    /// can surface a clean runtime error rather than panicking on a
    /// malformed instruction.
    pub fn from_tag(tag: u8) -> Option<Builtin> {
        Self::ALL.get(tag as usize).copied()
    }
}

/// Result of a char-by-signed-index lookup on a `&str`.
pub(crate) enum CharAtResult {
    /// The codepoint at the requested index.
    Found(char),
    /// Index was out of range; carries the total char count for error messages.
    OutOfRange { len: usize },
}

/// Fetch the i-th codepoint of `s`, supporting negative indices (`-1` = last).
///
/// Allocation-free in every path: positive indices walk `s.chars().nth(idx)`
/// (O(idx)); negative indices pay one O(n) `chars().count()` to adjust, then
/// the same `chars().nth`. Prior implementations did
/// `s.chars().collect::<Vec<char>>()` on every call, making per-char loops
/// like `@i 0..len s{c=at s i}` O(n²) AND allocating a fresh Vec per
/// iteration. The Vec allocator pressure was the observable trigger behind
/// the 222k-token "OOM" cluster in NLP workloads.
///
/// We deliberately do not branch on `s.is_ascii()` for a constant-time ASCII
/// path here: `is_ascii` itself walks the full string, so the guard would be
/// O(n) per call, more expensive than the `chars().nth(idx)` it replaces.
/// True O(1) ASCII indexing needs a cached `is_ascii` flag on the string
/// value; that's deferred with the RC-aware accumulator work.
pub(crate) fn char_at_signed(s: &str, raw_idx: i64) -> CharAtResult {
    if raw_idx >= 0 {
        let idx = raw_idx as usize;
        if let Some(c) = s.chars().nth(idx) {
            return CharAtResult::Found(c);
        }
        // Out of range: pay one O(n) pass for the count, only on error.
        return CharAtResult::OutOfRange {
            len: s.chars().count(),
        };
    }
    // Negative index: count chars to adjust, then walk again to the target.
    let len = s.chars().count();
    let adjusted = raw_idx + len as i64;
    if adjusted < 0 {
        return CharAtResult::OutOfRange { len };
    }
    match s.chars().nth(adjusted as usize) {
        Some(c) => CharAtResult::Found(c),
        None => CharAtResult::OutOfRange { len },
    }
}

/// Resolve a Python-style signed slice bound against `len`.
///
/// - `raw >= 0`: clamp to `[0, len]`.
/// - `raw < 0`: treat as `len + raw`, then clamp to `[0, len]`. So `-1` on a
///   length-5 list becomes index `4` (the last element); `-5` becomes `0`;
///   `-99` clamps to `0`.
///
/// Returned index is always in `[0, len]`, so callers can use it directly
/// as a slice bound without further checks. Matches the semantics already
/// applied to `at`'s negative index handling (`adjusted = if i < 0 { i + len }
/// else { i }`) — see `Builtin::At` in the tree-walker and `OP_AT` in the VM.
#[inline]
pub(crate) fn resolve_slice_bound(raw: i64, len: usize) -> usize {
    let len_i = len as i64;
    let adjusted = if raw < 0 { raw + len_i } else { raw };
    adjusted.clamp(0, len_i) as usize
}

/// Resolve `slc`'s `end` bound with the `-1 = to end` sugar.
///
/// `slc` historically treated negative end indices as Python-style relative
/// offsets, so `slc s 0 -1` dropped the last element. Agents trained on
/// Python/JS keep reaching for `-1` to mean "to end of string/list" instead,
/// so we add a narrow ergonomic exception: when `start_raw >= 0` and
/// `end_raw == -1`, treat the end as `len`. All other shapes (negative
/// start, or end < -1) keep the Python-style relative-offset behaviour via
/// [`resolve_slice_bound`].
///
/// This is intentionally `-1` only, not "any negative end". Treating every
/// negative end as "to end" would silently break the existing
/// `slc xs -3 -1` / `slc "hello" -99 -1` shapes that already rely on the
/// Python semantics.
#[inline]
pub(crate) fn resolve_slc_end(start_raw: i64, end_raw: i64, len: usize) -> usize {
    if start_raw >= 0 && end_raw == -1 {
        return len;
    }
    resolve_slice_bound(end_raw, len)
}

/// Resolve `take n xs` against `len`, returning the prefix length to retain.
///
/// - `n >= 0`: take the first `min(n, len)` elements.
/// - `n < 0`: take all but the last `|n|`. Equivalent to Python's `xs[:n]`.
///   `take -1 [1,2,3]` returns `[1,2]`; `take -len xs` returns `[]`; `n` more
///   negative than `-len` clamps to `0` (empty).
#[inline]
pub(crate) fn resolve_take_count(n: i64, len: usize) -> usize {
    if n >= 0 {
        (n as usize).min(len)
    } else {
        let adjusted = (len as i64) + n;
        adjusted.max(0) as usize
    }
}

/// Resolve `drop n xs` against `len`, returning the prefix length to skip.
///
/// - `n >= 0`: skip the first `min(n, len)` elements.
/// - `n < 0`: keep only the last `|n|`, i.e. skip the leading `len - |n|`.
///   Equivalent to Python's `xs[n:]`. `drop -1 [1,2,3]` returns `[3]`;
///   `drop -len xs` returns the full list; `n` more negative than `-len`
///   clamps to `0` (returns the full list).
#[inline]
pub(crate) fn resolve_drop_count(n: i64, len: usize) -> usize {
    if n >= 0 {
        (n as usize).min(len)
    } else {
        let adjusted = (len as i64) + n;
        adjusted.max(0) as usize
    }
}

/// Detects when a `jpth` path argument looks like JSONPath rather than ilo's
/// dot-path. ilo's `jpth` uses `a.b.0.c` style segments — leading `$`, `*`
/// wildcards, and `[...]` bracket selectors all signal that the caller reached
/// for JSONPath syntax. Returns a descriptive error message in that case so the
/// agent doesn't waste retries decoding a generic "key not found" diagnostic.
///
/// The first sentence is kept short so it fits cleanly in JSON error output
/// and matches the diagnostic shape used elsewhere in the runtime.
pub fn jpth_jsonpath_diagnostic(path: &str) -> Option<String> {
    // Leading `$` — classic JSONPath root selector.
    if let Some(rest) = path.strip_prefix('$') {
        // Tolerate a path that happens to be the literal key "$" — `key not found: $`
        // is still the right behaviour for that case. The diagnostic only fires when
        // `$` is followed by `.`, `[`, or `*`, all of which are JSONPath operators.
        if rest.starts_with('.') || rest.starts_with('[') || rest.starts_with('*') {
            return Some(format!(
                "jpth is dot-path only (e.g. \"a.b.0.c\"), not JSONPath. Got: \"{}\". Drop the leading `$` and use dot-separated keys / indices; for wildcards, iterate with `@i` or `map`.",
                path
            ));
        }
    }
    // Wildcard segment — JSONPath `*`, not valid in dot-path.
    if path.contains('*') {
        return Some(format!(
            "jpth is dot-path only (e.g. \"a.b.0.c\"), not JSONPath. Got: \"{}\". `*` wildcards are not supported; iterate the array yourself with `@i` after extracting it, or use `jpar` and walk the parsed value.",
            path
        ));
    }
    // Bracket selector — JSONPath `[0]` / `[*]` / `['key']`, not valid in dot-path.
    if path.contains('[') {
        return Some(format!(
            "jpth is dot-path only (e.g. \"a.b.0.c\"), not JSONPath. Got: \"{}\". Use a dot before array indices (e.g. \"items.0.name\") instead of bracket selectors.",
            path
        ));
    }
    None
}

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

    #[test]
    fn round_trip_all_builtins() {
        let all = [
            "range",
            "str",
            "num",
            "abs",
            "flr",
            "cel",
            "rou",
            "min",
            "max",
            "mod",
            "fmod",
            "clamp",
            "pow",
            "sqrt",
            "log",
            "exp",
            "sin",
            "cos",
            "tan",
            "log10",
            "log2",
            "asin",
            "acos",
            "atan",
            "atan2",
            "sum",
            "prod",
            "cumsum",
            "cprod",
            "ewm",
            "avg",
            "median",
            "quantile",
            "stdev",
            "variance",
            "len",
            "hd",
            "at",
            "tl",
            "rev",
            "srt",
            "rsrt",
            "slc",
            "lst",
            "take",
            "drop",
            "unq",
            "flat",
            "has",
            "spl",
            "cat",
            "zip",
            "enumerate",
            "setunion",
            "setinter",
            "setdiff",
            "map",
            "flt",
            "fld",
            "ct",
            "grp",
            "uniqby",
            "partition",
            "frq",
            "flatmap",
            "mapr",
            "rnd",
            "seed",
            "now",
            "now-ms",
            "rd",
            "rd-json",
            "rdl",
            "rdb",
            "wr",
            "wra",
            "wro",
            "wrl",
            "prnt",
            "env",
            "trm",
            "upr",
            "lwr",
            "cap",
            "padl",
            "padr",
            "ord",
            "chr",
            "chars",
            "fmt",
            "fmt2",
            "rgx",
            "rgxall",
            "rgxall1",
            "rgxsub",
            "rgxall-multi",
            "jpth",
            "jkeys",
            "jdmp",
            "jpar",
            "jpar-list",
            "get",
            "pst",
            "get-to",
            "pst-to",
            "getx",
            "pstx",
            "put",
            "pat",
            "del",
            "hed",
            "opt",
            "mmap",
            "mget",
            "mset",
            "mhas",
            "mkeys",
            "mvals",
            "mdel",
            "mget-or",
            "lget-or",
            "mpairs",
            "fft",
            "ifft",
            "window",
            "chunks",
            "transpose",
            "matmul",
            "matvec",
            "dot",
            "rndn",
            "get-many",
            "solve",
            "inv",
            "det",
            "lstsq",
            "rdjl",
            "dtfmt",
            "dtparse",
            "dtparse-rel",
            "sleep",
            "run",
            "lsd",
            "walk",
            "glob",
            "argmax",
            "argmin",
            "argsort",
            "dirname",
            "basename",
            "pathjoin",
            "rdin",
            "rdinl",
            "pi",
            "tau",
            "e",
            "dur-parse",
            "dur-fmt",
            "rand-bytes",
            "where",
            "add-mo",
            "last-dom",
            "next-business-day",
            "day-of-week",
            "linspace",
            "ones",
            "rep",
            "sha256",
            "hmac-sha256",
            "b64",
            "b64-dec",
            "hex",
            "ct-eq",
            "rsum",
            "ravg",
            "rmin",
            "bisect",
            "tokcount",
            "band",
            "bor",
            "bxor",
            "bnot",
            "bshl",
            "bshr",
            "brot",
            "band64",
            "bor64",
            "bxor64",
            "bnot64",
            "bshl64",
            "bshr64",
            "brot64",
            "arange",
            "zeros",
            "vstack",
            "hstack",
            "column-stack",
            "hist",
            "convolve",
            "searchsorted",
            "cabs",
            "cmul",
            "pairwise",
            "pdist2",
            "par-map",
            "get-stream",
            "get-stream-h",
            "pst-stream",
            "pst-stream-h",
            "spawn",
        ];
        for name in &all {
            let b = Builtin::from_name(name).unwrap_or_else(|| panic!("missing builtin: {name}"));
            assert_eq!(b.name(), *name, "round-trip failed for {name}");
        }
    }

    #[test]
    fn non_builtin_returns_none() {
        assert_eq!(Builtin::from_name("foo"), None);
        assert_eq!(Builtin::from_name(""), None);
    }

    #[test]
    fn resolve_slice_bound_positive_and_clamps() {
        // Within range: returned as-is.
        assert_eq!(resolve_slice_bound(0, 5), 0);
        assert_eq!(resolve_slice_bound(3, 5), 3);
        assert_eq!(resolve_slice_bound(5, 5), 5);
        // Past len: clamps up to len (matches existing slc behaviour).
        assert_eq!(resolve_slice_bound(99, 5), 5);
    }

    #[test]
    fn resolve_slice_bound_negative_python_style() {
        // -1 is the last index; -len is 0; beyond -len clamps to 0.
        assert_eq!(resolve_slice_bound(-1, 5), 4);
        assert_eq!(resolve_slice_bound(-5, 5), 0);
        assert_eq!(resolve_slice_bound(-99, 5), 0);
    }

    #[test]
    fn resolve_slice_bound_empty_list() {
        // len=0 makes every bound clamp to 0 — slc of an empty list always
        // returns empty, never errors. The fencepost-trap case in the
        // quant-trader run.
        assert_eq!(resolve_slice_bound(0, 0), 0);
        assert_eq!(resolve_slice_bound(-1, 0), 0);
        assert_eq!(resolve_slice_bound(99, 0), 0);
    }

    #[test]
    fn resolve_take_count_positive() {
        assert_eq!(resolve_take_count(0, 5), 0);
        assert_eq!(resolve_take_count(3, 5), 3);
        assert_eq!(resolve_take_count(5, 5), 5);
        assert_eq!(resolve_take_count(99, 5), 5);
    }

    #[test]
    fn resolve_take_count_negative_drops_tail() {
        // `take -k xs` == `xs[:-k]` — keep all but the last |k|.
        assert_eq!(resolve_take_count(-1, 5), 4);
        assert_eq!(resolve_take_count(-4, 5), 1);
        assert_eq!(resolve_take_count(-5, 5), 0);
        // Beyond -len clamps to 0 (empty), matching Python's `xs[:-99]`.
        assert_eq!(resolve_take_count(-99, 5), 0);
    }

    #[test]
    fn resolve_drop_count_positive() {
        assert_eq!(resolve_drop_count(0, 5), 0);
        assert_eq!(resolve_drop_count(3, 5), 3);
        assert_eq!(resolve_drop_count(5, 5), 5);
        assert_eq!(resolve_drop_count(99, 5), 5);
    }

    #[test]
    fn resolve_drop_count_negative_keeps_tail() {
        // `drop -k xs` == `xs[-k:]` — discard all but the last |k|.
        // Returned value is the *prefix length to skip*.
        assert_eq!(resolve_drop_count(-1, 5), 4); // skip 4, keep last 1
        assert_eq!(resolve_drop_count(-4, 5), 1); // skip 1, keep last 4
        assert_eq!(resolve_drop_count(-5, 5), 0); // skip 0, keep all
        // Beyond -len clamps to 0 (keep everything), matching Python `xs[-99:]`.
        assert_eq!(resolve_drop_count(-99, 5), 0);
    }

    #[test]
    fn resolve_take_drop_empty_list() {
        // Every count against len=0 must clamp to 0 — take/drop of empty
        // never errors, irrespective of sign.
        assert_eq!(resolve_take_count(0, 0), 0);
        assert_eq!(resolve_take_count(-3, 0), 0);
        assert_eq!(resolve_take_count(3, 0), 0);
        assert_eq!(resolve_drop_count(0, 0), 0);
        assert_eq!(resolve_drop_count(-3, 0), 0);
        assert_eq!(resolve_drop_count(3, 0), 0);
    }

    #[test]
    fn tag_round_trips_for_every_builtin() {
        // Anchor for the OP_CALL_BUILTIN_TREE bridge: every builtin must
        // tag↔from_tag cleanly, and Builtin::ALL must list every variant
        // covered by from_name (no silent drift).
        for name in &[
            "str",
            "num",
            "abs",
            "flr",
            "cel",
            "rou",
            "min",
            "max",
            "mod",
            "fmod",
            "clamp",
            "pow",
            "sqrt",
            "log",
            "exp",
            "sin",
            "cos",
            "tan",
            "log10",
            "log2",
            "asin",
            "acos",
            "atan",
            "atan2",
            "sum",
            "prod",
            "cumsum",
            "cprod",
            "ewm",
            "avg",
            "median",
            "quantile",
            "stdev",
            "variance",
            "fft",
            "ifft",
            "transpose",
            "matmul",
            "matvec",
            "dot",
            "len",
            "hd",
            "at",
            "tl",
            "rev",
            "srt",
            "rsrt",
            "slc",
            "lst",
            "take",
            "drop",
            "unq",
            "flat",
            "has",
            "spl",
            "cat",
            "zip",
            "enumerate",
            "range",
            "window",
            "chunks",
            "setunion",
            "setinter",
            "setdiff",
            "map",
            "flt",
            "fld",
            "ct",
            "grp",
            "uniqby",
            "partition",
            "frq",
            "flatmap",
            "mapr",
            "rnd",
            "rndn",
            "now",
            "now-ms",
            "dtfmt",
            "dtparse",
            "dtparse-rel",
            "rd",
            "rd-json",
            "rdl",
            "rdb",
            "wr",
            "wra",
            "wro",
            "wrl",
            "prnt",
            "env",
            "trm",
            "upr",
            "lwr",
            "cap",
            "padl",
            "padr",
            "ord",
            "chr",
            "chars",
            "fmt",
            "fmt2",
            "rgx",
            "rgxall",
            "rgxall1",
            "rgxsub",
            "rgxall-multi",
            "jpth",
            "jkeys",
            "jdmp",
            "jpar",
            "jpar-list",
            "rdjl",
            "get",
            "pst",
            "get-many",
            "get-to",
            "pst-to",
            "getx",
            "pstx",
            "put",
            "pat",
            "del",
            "hed",
            "opt",
            "mmap",
            "mget",
            "mset",
            "mhas",
            "mkeys",
            "mvals",
            "mdel",
            "mget-or",
            "lget-or",
            "mpairs",
            "solve",
            "inv",
            "det",
            "lstsq",
            "run",
            "lsd",
            "walk",
            "glob",
            "dirname",
            "basename",
            "pathjoin",
            "rdin",
            "rdinl",
            "pi",
            "tau",
            "e",
            "dur-parse",
            "dur-fmt",
            "rand-bytes",
            "where",
            "add-mo",
            "last-dom",
            "next-business-day",
            "day-of-week",
            "linspace",
            "ones",
            "rep",
            "sha256",
            "hmac-sha256",
            "b64",
            "b64-dec",
            "hex",
            "ct-eq",
            "rsum",
            "ravg",
            "rmin",
            "bisect",
            "for-line",
            "idxof",
            "hex-rev",
            "tokcount",
            "arange",
            "zeros",
            "vstack",
            "hstack",
            "column-stack",
            "hist",
            "convolve",
            "searchsorted",
            "cabs",
            "cmul",
            "pairwise",
            "pdist2",
            "par-map",
            "get-stream",
            "get-stream-h",
            "pst-stream",
            "pst-stream-h",
            "spawn",
        ] {
            let b = Builtin::from_name(name).unwrap_or_else(|| panic!("no builtin: {name}"));
            let t = b.tag();
            let round = Builtin::from_tag(t).unwrap_or_else(|| panic!("no from_tag for {name}"));
            assert_eq!(b, round, "tag round-trip failed for {name}");
        }
        // No tag collisions.
        let tags: Vec<u8> = Builtin::ALL.iter().map(|b| b.tag()).collect();
        let mut sorted = tags.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(sorted.len(), tags.len(), "tag collision in Builtin::ALL");
    }

    fn unwrap_found(r: CharAtResult) -> char {
        match r {
            CharAtResult::Found(c) => c,
            CharAtResult::OutOfRange { len } => panic!("expected Found, got OutOfRange len={len}"),
        }
    }

    fn unwrap_oor(r: CharAtResult) -> usize {
        match r {
            CharAtResult::OutOfRange { len } => len,
            CharAtResult::Found(c) => panic!("expected OutOfRange, got Found({c:?})"),
        }
    }

    #[test]
    fn char_at_signed_ascii_positive() {
        assert_eq!(unwrap_found(char_at_signed("hello", 0)), 'h');
        assert_eq!(unwrap_found(char_at_signed("hello", 4)), 'o');
        assert_eq!(unwrap_oor(char_at_signed("hello", 5)), 5);
        assert_eq!(unwrap_oor(char_at_signed("", 0)), 0);
    }

    #[test]
    fn char_at_signed_ascii_negative() {
        assert_eq!(unwrap_found(char_at_signed("hello", -1)), 'o');
        assert_eq!(unwrap_found(char_at_signed("hello", -5)), 'h');
        assert_eq!(unwrap_oor(char_at_signed("hello", -6)), 5);
    }

    #[test]
    fn char_at_signed_unicode_positive() {
        // "naïve" — 5 codepoints, 6 bytes
        assert_eq!(unwrap_found(char_at_signed("naïve", 0)), 'n');
        assert_eq!(unwrap_found(char_at_signed("naïve", 2)), 'ï');
        assert_eq!(unwrap_found(char_at_signed("naïve", 4)), 'e');
        assert_eq!(unwrap_oor(char_at_signed("naïve", 5)), 5);
    }

    #[test]
    fn char_at_signed_unicode_negative() {
        assert_eq!(unwrap_found(char_at_signed("naïve", -1)), 'e');
        assert_eq!(unwrap_found(char_at_signed("naïve", -3)), 'ï');
        assert_eq!(unwrap_oor(char_at_signed("naïve", -6)), 5);
    }
}