ilo 0.8.2

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

pub mod json;

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Number(f64),
    Text(String),
    Bool(bool),
    Nil,
    List(Vec<Value>),
    Map(HashMap<String, Value>),
    Record { type_name: String, fields: HashMap<String, Value> },
    Ok(Box<Value>),
    Err(Box<Value>),
    /// A reference to a named function — produced when a function name is used as a value.
    FnRef(String),
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Number(n) => {
                if *n == (*n as i64) as f64 {
                    write!(f, "{}", *n as i64)
                } else {
                    write!(f, "{}", n)
                }
            }
            Value::Text(s) => write!(f, "{}", s),
            Value::Bool(b) => write!(f, "{}", b),
            Value::Nil => write!(f, "nil"),
            Value::List(items) => {
                write!(f, "[")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", item)?;
                }
                write!(f, "]")
            }
            Value::Record { type_name, fields } => {
                write!(f, "{} {{", type_name)?;
                for (i, (k, v)) in fields.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}: {}", k, v)?;
                }
                write!(f, "}}")
            }
            Value::Map(m) => {
                write!(f, "{{")?;
                let mut keys: Vec<&String> = m.keys().collect();
                keys.sort();
                for (i, k) in keys.iter().enumerate() {
                    if i > 0 { write!(f, "; ")?; }
                    write!(f, "{}: {}", k, m[*k])?;
                }
                write!(f, "}}")
            }
            Value::Ok(v) => write!(f, "~{}", v),
            Value::Err(v) => write!(f, "^{}", v),
            Value::FnRef(name) => write!(f, "<fn:{}>", name),
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[error("Runtime error: {message}")]
pub struct RuntimeError {
    pub code: &'static str,
    pub message: String,
    pub span: Option<crate::ast::Span>,
    pub call_stack: Vec<String>,
    /// When set, the `!` operator is propagating an Err value — not a real error.
    pub propagate_value: Option<Box<Value>>,
}

impl RuntimeError {
    fn new(code: &'static str, msg: impl Into<String>) -> Self {
        RuntimeError { code, message: msg.into(), span: None, call_stack: Vec::new(), propagate_value: None }
    }
}

type Result<T> = std::result::Result<T, RuntimeError>;

struct Env {
    /// Flat variable store — all scopes in one Vec. Each entry is (name, value).
    vars: Vec<(String, Value)>,
    /// Stack of indices into `vars` marking where each scope starts.
    scope_marks: Vec<usize>,
    functions: HashMap<String, Decl>,
    call_stack: Vec<String>,
    tool_provider: Option<std::sync::Arc<dyn crate::tools::ToolProvider>>,
    #[cfg(feature = "tools")]
    tokio_runtime: Option<std::sync::Arc<tokio::runtime::Runtime>>,
}

impl Env {
    fn new() -> Self {
        Env {
            vars: Vec::new(),
            scope_marks: vec![0],
            functions: HashMap::new(),
            call_stack: Vec::new(),
            tool_provider: None,
            #[cfg(feature = "tools")]
            tokio_runtime: None,
        }
    }

    fn with_tools(
        provider: std::sync::Arc<dyn crate::tools::ToolProvider>,
        #[cfg(feature = "tools")] runtime: std::sync::Arc<tokio::runtime::Runtime>,
    ) -> Self {
        Env {
            vars: Vec::new(),
            scope_marks: vec![0],
            functions: HashMap::new(),
            call_stack: Vec::new(),
            tool_provider: Some(provider),
            #[cfg(feature = "tools")]
            tokio_runtime: Some(runtime),
        }
    }

    fn push_scope(&mut self) {
        self.scope_marks.push(self.vars.len());
    }

    fn pop_scope(&mut self) {
        let mark = self.scope_marks.pop().expect("unbalanced push_scope/pop_scope");
        self.vars.truncate(mark);
    }

    fn set(&mut self, name: &str, value: Value) {
        // Update existing binding in any enclosing scope (innermost first)
        for entry in self.vars.iter_mut().rev() {
            if entry.0 == name {
                entry.1 = value;
                return;
            }
        }
        // No existing binding — create in innermost scope
        self.vars.push((name.to_string(), value));
    }

    /// Always create a fresh binding in the innermost scope (used for function parameters).
    fn define(&mut self, name: &str, value: Value) {
        self.vars.push((name.to_string(), value));
    }

    fn get(&self, name: &str) -> Result<Value> {
        for (k, v) in self.vars.iter().rev() {
            if k == name {
                return Ok(v.clone());
            }
        }
        // Function names resolve to FnRef when used as values
        if self.functions.contains_key(name) {
            return Ok(Value::FnRef(name.to_string()));
        }
        Err(RuntimeError::new("ILO-R001", format!("undefined variable: {}", name)))
    }

    fn function(&self, name: &str) -> Result<Decl> {
        self.functions.get(name).cloned().ok_or_else(|| {
            RuntimeError::new("ILO-R002", format!("undefined function: {}", name))
        })
    }
}

/// Signal that a body produced an early return
enum BodyResult {
    /// Normal completion, last value
    Value(Value),
    /// Early return from guard
    Return(Value),
    /// Break from loop, with optional value
    Break(Value),
    /// Continue to next loop iteration
    Continue,
}

pub fn run(program: &Program, func_name: Option<&str>, args: Vec<Value>) -> Result<Value> {
    run_with_env(program, func_name, args, Env::new())
}

pub fn run_with_tools(
    program: &Program,
    func_name: Option<&str>,
    args: Vec<Value>,
    provider: std::sync::Arc<dyn crate::tools::ToolProvider>,
    #[cfg(feature = "tools")] runtime: std::sync::Arc<tokio::runtime::Runtime>,
) -> Result<Value> {
    let env = Env::with_tools(
        provider,
        #[cfg(feature = "tools")]
        runtime,
    );
    run_with_env(program, func_name, args, env)
}

fn run_with_env(program: &Program, func_name: Option<&str>, args: Vec<Value>, mut env: Env) -> Result<Value> {
    // Register all functions and tools
    for decl in &program.declarations {
        match decl {
            Decl::Function { name, .. } | Decl::Tool { name, .. } => {
                env.functions.insert(name.clone(), decl.clone());
            }
            Decl::TypeDef { .. } | Decl::Alias { .. } | Decl::Use { .. } | Decl::Error { .. } => {}
        }
    }

    // Find function to call
    let target = match func_name {
        Some(name) => name.to_string(),
        None => {
            // Find first function
            program.declarations.iter()
                .find_map(|d| match d {
                    Decl::Function { name, .. } => Some(name.clone()),
                    _ => None,
                })
                .ok_or_else(|| RuntimeError::new("ILO-R012", "no functions defined"))?
        }
    };

    call_function(&mut env, &target, args)
}

/// Parse a string into a structured Value given a format name.
/// Grid formats ("csv", "tsv") → Ok(List of rows).
/// Graph formats ("json")      → Ok(parsed JSON) or Err(parse error message).
/// Raw/unknown                 → Ok(plain Text).
fn parse_format(fmt: &str, content: &str) -> std::result::Result<Value, String> {
    match fmt {
        "csv" | "tsv" => {
            let sep = if fmt == "tsv" { '\t' } else { ',' };
            let rows: Vec<Value> = content
                .lines()
                .map(|line| {
                    let fields: Vec<Value> = parse_csv_row(line, sep)
                        .into_iter()
                        .map(Value::Text)
                        .collect();
                    Value::List(fields)
                })
                .collect();
            Ok(Value::List(rows))
        }
        "json" => {
            serde_json::from_str::<serde_json::Value>(content)
                .map(serde_json_to_value)
                .map_err(|e| e.to_string())
        }
        _ => Ok(Value::Text(content.to_string())),
    }
}

/// Parse one CSV/TSV row respecting double-quoted fields.
fn parse_csv_row(line: &str, sep: char) -> Vec<String> {
    let mut fields = Vec::new();
    let mut field = String::new();
    let mut in_quotes = false;
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        if in_quotes {
            if c == '"' {
                if chars.peek() == Some(&'"') {
                    chars.next();
                    field.push('"');
                } else {
                    in_quotes = false;
                }
            } else {
                field.push(c);
            }
        } else if c == '"' {
            in_quotes = true;
        } else if c == sep {
            fields.push(std::mem::take(&mut field));
        } else {
            field.push(c);
        }
    }
    fields.push(field);
    fields
}

fn call_function(env: &mut Env, name: &str, args: Vec<Value>) -> Result<Value> {
    // Builtins
    if name == "len" {
        if args.len() != 1 {
            return Err(RuntimeError::new("ILO-R009", format!("len: expected 1 arg, got {}", args.len())));
        }
        return match &args[0] {
            Value::Text(s) => Ok(Value::Number(s.len() as f64)),
            Value::List(l) => Ok(Value::Number(l.len() as f64)),
            Value::Map(m) => Ok(Value::Number(m.len() as f64)),
            other => Err(RuntimeError::new("ILO-R009", format!("len requires string, list, or map, got {:?}", other))),
        };
    }
    // Map builtins
    if name == "mmap" && args.is_empty() {
        return Ok(Value::Map(HashMap::new()));
    }
    if name == "mget" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Map(m), Value::Text(k)) => Ok(m.get(k).cloned().unwrap_or(Value::Nil)),
            _ => Err(RuntimeError::new("ILO-R009", "mget: expects map and text key".to_string())),
        };
    }
    if name == "mset" && args.len() == 3 {
        return match (&args[0], &args[1]) {
            (Value::Map(m), Value::Text(k)) => {
                let mut new_map = m.clone();
                new_map.insert(k.clone(), args[2].clone());
                Ok(Value::Map(new_map))
            }
            _ => Err(RuntimeError::new("ILO-R009", "mset: expects map, text key, and value".to_string())),
        };
    }
    if name == "mhas" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Map(m), Value::Text(k)) => Ok(Value::Bool(m.contains_key(k.as_str()))),
            _ => Err(RuntimeError::new("ILO-R009", "mhas: expects map and text key".to_string())),
        };
    }
    if name == "mkeys" && args.len() == 1 {
        return match &args[0] {
            Value::Map(m) => {
                let mut keys: Vec<&String> = m.keys().collect();
                keys.sort();
                Ok(Value::List(keys.into_iter().map(|k| Value::Text(k.clone())).collect()))
            }
            _ => Err(RuntimeError::new("ILO-R009", "mkeys: expects a map".to_string())),
        };
    }
    if name == "mvals" && args.len() == 1 {
        return match &args[0] {
            Value::Map(m) => {
                let mut pairs: Vec<(&String, &Value)> = m.iter().collect();
                pairs.sort_by_key(|(k, _)| k.as_str());
                Ok(Value::List(pairs.into_iter().map(|(_, v)| v.clone()).collect()))
            }
            _ => Err(RuntimeError::new("ILO-R009", "mvals: expects a map".to_string())),
        };
    }
    if name == "mdel" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Map(m), Value::Text(k)) => {
                let mut new_map = m.clone();
                new_map.remove(k.as_str());
                Ok(Value::Map(new_map))
            }
            _ => Err(RuntimeError::new("ILO-R009", "mdel: expects map and text key".to_string())),
        };
    }
    if name == "str" {
        if args.len() != 1 {
            return Err(RuntimeError::new("ILO-R009", format!("str: expected 1 arg, got {}", args.len())));
        }
        return match &args[0] {
            Value::Number(n) => {
                let s = if n.fract() == 0.0 && n.abs() < 1e15 {
                    format!("{}", *n as i64)
                } else {
                    format!("{}", n)
                };
                Ok(Value::Text(s))
            }
            other => Err(RuntimeError::new("ILO-R009", format!("str requires a number, got {:?}", other))),
        };
    }
    if name == "num" {
        if args.len() != 1 {
            return Err(RuntimeError::new("ILO-R009", format!("num: expected 1 arg, got {}", args.len())));
        }
        return match &args[0] {
            Value::Text(s) => match s.parse::<f64>() {
                Ok(n) => Ok(Value::Ok(Box::new(Value::Number(n)))),
                Err(_) => Ok(Value::Err(Box::new(Value::Text(s.clone())))),
            },
            other => Err(RuntimeError::new("ILO-R009", format!("num requires text, got {:?}", other))),
        };
    }
    if name == "abs" {
        if args.len() != 1 {
            return Err(RuntimeError::new("ILO-R009", format!("abs: expected 1 arg, got {}", args.len())));
        }
        return match &args[0] {
            Value::Number(n) => Ok(Value::Number(n.abs())),
            other => Err(RuntimeError::new("ILO-R009", format!("abs requires a number, got {:?}", other))),
        };
    }
    if name == "mod" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Number(a), Value::Number(b)) => {
                if *b == 0.0 {
                    Err(RuntimeError::new("ILO-R003", "modulo by zero".to_string()))
                } else {
                    Ok(Value::Number(a % b))
                }
            }
            _ => Err(RuntimeError::new("ILO-R009", "mod requires two numbers".to_string())),
        };
    }
    if (name == "min" || name == "max") && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Number(a), Value::Number(b)) => {
                let result = if name == "min" { a.min(*b) } else { a.max(*b) };
                Ok(Value::Number(result))
            }
            _ => Err(RuntimeError::new("ILO-R009", format!("{} requires two numbers", name))),
        };
    }
    if (name == "flr" || name == "cel") && args.len() == 1 {
        return match &args[0] {
            Value::Number(n) => {
                let result = if name == "flr" { n.floor() } else { n.ceil() };
                Ok(Value::Number(result))
            }
            other => Err(RuntimeError::new("ILO-R009", format!("{} requires a number, got {:?}", name, other))),
        };
    }
    if name == "now" && args.is_empty() {
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();
        return Ok(Value::Number(ts));
    }
    if name == "rnd" {
        if args.is_empty() {
            return Ok(Value::Number(fastrand::f64()));
        }
        if args.len() == 2 {
            return match (&args[0], &args[1]) {
                (Value::Number(a), Value::Number(b)) => {
                    let lo = *a as i64;
                    let hi = *b as i64;
                    if lo > hi {
                        return Err(RuntimeError::new("ILO-R009", format!("rnd: lower bound {} > upper bound {}", lo, hi)));
                    }
                    Ok(Value::Number(fastrand::i64(lo..=hi) as f64))
                }
                _ => Err(RuntimeError::new("ILO-R009", "rnd requires two numbers".to_string())),
            };
        }
    }
    if name == "spl" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Text(s), Value::Text(sep)) => {
                let parts: Vec<Value> = s.split(sep.as_str()).map(|p| Value::Text(p.to_string())).collect();
                Ok(Value::List(parts))
            }
            _ => Err(RuntimeError::new("ILO-R009", "spl requires two text args".to_string())),
        };
    }
    if name == "cat" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::List(items), Value::Text(sep)) => {
                let mut parts = Vec::new();
                for item in items {
                    match item {
                        Value::Text(s) => parts.push(s.clone()),
                        other => return Err(RuntimeError::new("ILO-R009", format!("cat: list items must be text, got {:?}", other))),
                    }
                }
                Ok(Value::Text(parts.join(sep.as_str())))
            }
            _ => Err(RuntimeError::new("ILO-R009", "cat requires a list and text separator".to_string())),
        };
    }
    if name == "has" && args.len() == 2 {
        return match &args[0] {
            Value::List(items) => Ok(Value::Bool(items.contains(&args[1]))),
            Value::Text(s) => match &args[1] {
                Value::Text(needle) => Ok(Value::Bool(s.contains(needle.as_str()))),
                other => Err(RuntimeError::new("ILO-R009", format!("has: text search requires text needle, got {:?}", other))),
            },
            other => Err(RuntimeError::new("ILO-R009", format!("has requires a list or text, got {:?}", other))),
        };
    }
    if name == "hd" && args.len() == 1 {
        return match &args[0] {
            Value::List(items) => {
                if items.is_empty() {
                    Err(RuntimeError::new("ILO-R009", "hd: empty list".to_string()))
                } else {
                    Ok(items[0].clone())
                }
            }
            Value::Text(s) => {
                if s.is_empty() {
                    Err(RuntimeError::new("ILO-R009", "hd: empty text".to_string()))
                } else {
                    Ok(Value::Text(s.chars().next().unwrap().to_string()))
                }
            }
            other => Err(RuntimeError::new("ILO-R009", format!("hd requires a list or text, got {:?}", other))),
        };
    }
    if name == "tl" && args.len() == 1 {
        return match &args[0] {
            Value::List(items) => {
                if items.is_empty() {
                    Err(RuntimeError::new("ILO-R009", "tl: empty list".to_string()))
                } else {
                    Ok(Value::List(items[1..].to_vec()))
                }
            }
            Value::Text(s) => {
                if s.is_empty() {
                    Err(RuntimeError::new("ILO-R009", "tl: empty text".to_string()))
                } else {
                    let mut chars = s.chars();
                    chars.next();
                    Ok(Value::Text(chars.collect()))
                }
            }
            other => Err(RuntimeError::new("ILO-R009", format!("tl requires a list or text, got {:?}", other))),
        };
    }
    if name == "rev" && args.len() == 1 {
        return match &args[0] {
            Value::List(items) => {
                let mut reversed = items.clone();
                reversed.reverse();
                Ok(Value::List(reversed))
            }
            Value::Text(s) => Ok(Value::Text(s.chars().rev().collect())),
            other => Err(RuntimeError::new("ILO-R009", format!("rev requires a list or text, got {:?}", other))),
        };
    }
    if name == "srt" && args.len() == 1 {
        return match &args[0] {
            Value::List(items) => {
                if items.is_empty() {
                    return Ok(Value::List(vec![]));
                }
                let all_numbers = items.iter().all(|v| matches!(v, Value::Number(_)));
                let all_text = items.iter().all(|v| matches!(v, Value::Text(_)));
                if all_numbers {
                    let mut sorted = items.clone();
                    sorted.sort_by(|a, b| {
                        if let (Value::Number(x), Value::Number(y)) = (a, b) {
                            x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
                        } else {
                            unreachable!()
                        }
                    });
                    Ok(Value::List(sorted))
                } else if all_text {
                    let mut sorted = items.clone();
                    sorted.sort_by(|a, b| {
                        if let (Value::Text(x), Value::Text(y)) = (a, b) {
                            x.cmp(y)
                        } else {
                            unreachable!()
                        }
                    });
                    Ok(Value::List(sorted))
                } else {
                    Err(RuntimeError::new("ILO-R009", "srt: list must contain all numbers or all text".to_string()))
                }
            }
            Value::Text(s) => {
                let mut chars: Vec<char> = s.chars().collect();
                chars.sort();
                Ok(Value::Text(chars.into_iter().collect()))
            }
            other => Err(RuntimeError::new("ILO-R009", format!("srt requires a list or text, got {:?}", other))),
        };
    }
    if name == "srt" && args.len() == 2 {
        let fn_name = resolve_fn_ref(&args[0]).ok_or_else(|| {
            RuntimeError::new("ILO-R009", format!("srt: key arg must be a function reference, got {:?}", args[0]))
        })?;
        let items = match &args[1] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("srt: second arg must be a list, got {:?}", other))),
        };
        // Compute keys for each item, then sort by key
        let mut keyed: Vec<(Value, Value)> = items
            .into_iter()
            .map(|item| {
                let key = call_function(env, &fn_name, vec![item.clone()])?;
                Ok((key, item))
            })
            .collect::<Result<_>>()?;
        keyed.sort_by(|(ka, _), (kb, _)| match (ka, kb) {
            (Value::Number(a), Value::Number(b)) => a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal),
            (Value::Text(a), Value::Text(b)) => a.cmp(b),
            _ => std::cmp::Ordering::Equal,
        });
        return Ok(Value::List(keyed.into_iter().map(|(_, v)| v).collect()));
    }
    if name == "slc" && args.len() == 3 {
        let start = match &args[1] {
            Value::Number(n) => *n as usize,
            other => return Err(RuntimeError::new("ILO-R009", format!("slc: start index must be a number, got {:?}", other))),
        };
        let end = match &args[2] {
            Value::Number(n) => *n as usize,
            other => return Err(RuntimeError::new("ILO-R009", format!("slc: end index must be a number, got {:?}", other))),
        };
        return match &args[0] {
            Value::List(items) => {
                let end = end.min(items.len());
                let start = start.min(end);
                Ok(Value::List(items[start..end].to_vec()))
            }
            Value::Text(s) => {
                let chars: Vec<char> = s.chars().collect();
                let end = end.min(chars.len());
                let start = start.min(end);
                Ok(Value::Text(chars[start..end].iter().collect()))
            }
            other => Err(RuntimeError::new("ILO-R009", format!("slc requires a list or text, got {:?}", other))),
        };
    }
    if name == "get" && (args.len() == 1 || args.len() == 2) {
        let url = match &args[0] {
            Value::Text(u) => u.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("get requires text (url), got {:?}", other))),
        };
        let headers = if args.len() == 2 {
            match &args[1] {
                Value::Map(m) => m.iter().map(|(k, v)| {
                    let vs = match v { Value::Text(s) => s.clone(), other => format!("{other:?}") };
                    (k.clone(), vs)
                }).collect::<Vec<_>>(),
                other => return Err(RuntimeError::new("ILO-R009", format!("get headers must be M t t, got {:?}", other))),
            }
        } else { vec![] };
        return {
            #[cfg(feature = "http")]
            {
                let mut req = minreq::get(url.as_str());
                for (k, v) in &headers { req = req.with_header(k.as_str(), v.as_str()); }
                match req.send() {
                    Ok(resp) => match resp.as_str() {
                        Ok(body) => Ok(Value::Ok(Box::new(Value::Text(body.to_string())))),
                        Err(e) => Ok(Value::Err(Box::new(Value::Text(format!("response is not valid UTF-8: {e}"))))),
                    },
                    Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
                }
            }
            #[cfg(not(feature = "http"))]
            {
                let _ = (url, headers);
                Ok(Value::Err(Box::new(Value::Text("http feature not enabled".to_string()))))
            }
        };
    }
    if name == "post" && (args.len() == 2 || args.len() == 3) {
        let (url, body) = match (&args[0], &args[1]) {
            (Value::Text(u), Value::Text(b)) => (u.clone(), b.clone()),
            _ => return Err(RuntimeError::new("ILO-R009", format!("post requires (t, t), got ({:?}, {:?})", args[0], args[1]))),
        };
        let headers = if args.len() == 3 {
            match &args[2] {
                Value::Map(m) => m.iter().map(|(k, v)| {
                    let vs = match v { Value::Text(s) => s.clone(), other => format!("{other:?}") };
                    (k.clone(), vs)
                }).collect::<Vec<_>>(),
                other => return Err(RuntimeError::new("ILO-R009", format!("post headers must be M t t, got {:?}", other))),
            }
        } else { vec![] };
        return {
            #[cfg(feature = "http")]
            {
                let mut req = minreq::post(url.as_str()).with_body(body.as_str());
                for (k, v) in &headers { req = req.with_header(k.as_str(), v.as_str()); }
                match req.send() {
                    Ok(resp) => match resp.as_str() {
                        Ok(b) => Ok(Value::Ok(Box::new(Value::Text(b.to_string())))),
                        Err(e) => Ok(Value::Err(Box::new(Value::Text(format!("response is not valid UTF-8: {e}"))))),
                    },
                    Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
                }
            }
            #[cfg(not(feature = "http"))]
            {
                let _ = (url, body, headers);
                Ok(Value::Err(Box::new(Value::Text("http feature not enabled".to_string()))))
            }
        };
    }
    if name == "trm" && args.len() == 1 {
        return match &args[0] {
            Value::Text(s) => Ok(Value::Text(s.trim().to_string())),
            other => Err(RuntimeError::new("ILO-R009", format!("trm requires text, got {:?}", other))),
        };
    }
    if name == "unq" && args.len() == 1 {
        return match &args[0] {
            Value::List(xs) => {
                let mut seen = std::collections::HashSet::new();
                let mut out = Vec::new();
                for v in xs {
                    let key = format!("{v:?}");
                    if seen.insert(key) {
                        out.push(v.clone());
                    }
                }
                Ok(Value::List(out))
            }
            Value::Text(s) => {
                let mut seen = std::collections::HashSet::new();
                let deduped: String = s.chars().filter(|c| seen.insert(*c)).collect();
                Ok(Value::Text(deduped))
            }
            other => Err(RuntimeError::new("ILO-R009", format!("unq requires a list or text, got {:?}", other))),
        };
    }
    if name == "fmt" && !args.is_empty() {
        let template = match &args[0] {
            Value::Text(s) => s.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("fmt first arg must be text template, got {:?}", other))),
        };
        let mut result = String::new();
        let mut arg_idx = 1;
        let mut chars = template.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '{' && chars.peek() == Some(&'}') {
                chars.next();
                if arg_idx < args.len() {
                    result.push_str(&format!("{}", args[arg_idx]));
                    arg_idx += 1;
                } else {
                    result.push_str("{}");
                }
            } else {
                result.push(c);
            }
        }
        return Ok(Value::Text(result));
    }
    if name == "rd" && (args.len() == 1 || args.len() == 2) {
        let path = match &args[0] {
            Value::Text(s) => s.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("rd requires text path, got {:?}", other))),
        };
        let fmt = if args.len() == 2 {
            match &args[1] {
                Value::Text(s) => s.as_str().to_owned(),
                other => return Err(RuntimeError::new("ILO-R009", format!("rd format must be text, got {:?}", other))),
            }
        } else {
            // auto-detect from extension
            std::path::Path::new(&path)
                .extension()
                .and_then(|e| e.to_str())
                .unwrap_or("raw")
                .to_lowercase()
        };
        return match std::fs::read_to_string(&path) {
            Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
            Ok(content) => match parse_format(&fmt, &content) {
                Ok(v) => Ok(Value::Ok(Box::new(v))),
                Err(e) => Ok(Value::Err(Box::new(Value::Text(e)))),
            },
        };
    }
    if name == "rdb" && args.len() == 2 {
        let s = match &args[0] {
            Value::Text(s) => s.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("rdb requires text string, got {:?}", other))),
        };
        let fmt = match &args[1] {
            Value::Text(f) => f.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("rdb format must be text, got {:?}", other))),
        };
        return match parse_format(&fmt, &s) {
            Ok(v) => Ok(Value::Ok(Box::new(v))),
            Err(e) => Ok(Value::Err(Box::new(Value::Text(e)))),
        };
    }
    if name == "rdl" && args.len() == 1 {
        return match &args[0] {
            Value::Text(path) => match std::fs::read_to_string(path) {
                Ok(content) => {
                    let lines: Vec<Value> = content
                        .lines()
                        .map(|l| Value::Text(l.to_string()))
                        .collect();
                    Ok(Value::Ok(Box::new(Value::List(lines))))
                }
                Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
            },
            other => Err(RuntimeError::new("ILO-R009", format!("rdl requires text path, got {:?}", other))),
        };
    }
    if name == "wr" && (args.len() == 2 || args.len() == 3) {
        let path = match &args[0] {
            Value::Text(s) => s.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("wr: first arg must be a text path, got {:?}", other))),
        };
        let content = if args.len() == 3 {
            let fmt = match &args[2] {
                Value::Text(s) => s.clone(),
                other => return Err(RuntimeError::new("ILO-R009", format!("wr: format arg must be text, got {:?}", other))),
            };
            match fmt.as_str() {
                "csv" | "tsv" => {
                    let sep = if fmt == "csv" { ',' } else { '\t' };
                    let rows = match &args[1] {
                        Value::List(l) => l,
                        other => return Err(RuntimeError::new("ILO-R009", format!("wr: data for {fmt} must be a list of rows, got {:?}", other))),
                    };
                    let mut out = String::new();
                    for row in rows {
                        match row {
                            Value::List(fields) => {
                                for (i, f) in fields.iter().enumerate() {
                                    if i > 0 { out.push(sep); }
                                    let s = match f {
                                        Value::Text(s) => {
                                            if s.contains(sep) || s.contains('"') || s.contains('\n') {
                                                format!("\"{}\"", s.replace('"', "\"\""))
                                            } else {
                                                out.push_str(s);
                                                continue;
                                            }
                                        }
                                        Value::Number(n) => {
                                            if *n == (*n as i64) as f64 { format!("{}", *n as i64) } else { format!("{n}") }
                                        }
                                        Value::Bool(b) => format!("{b}"),
                                        other => format!("{other}"),
                                    };
                                    out.push_str(&s);
                                }
                                out.push('\n');
                            }
                            other => return Err(RuntimeError::new("ILO-R009", format!("wr: each row must be a list, got {:?}", other))),
                        }
                    }
                    out
                }
                "json" => {
                    fn value_to_json(v: &Value) -> serde_json::Value {
                        match v {
                            Value::Number(n) => serde_json::Value::from(*n),
                            Value::Text(s) => serde_json::Value::from(s.as_str()),
                            Value::Bool(b) => serde_json::Value::from(*b),
                            Value::List(l) => serde_json::Value::Array(l.iter().map(value_to_json).collect()),
                            Value::Map(m) => {
                                let obj: serde_json::Map<String, serde_json::Value> = m.iter().map(|(k, v)| (k.clone(), value_to_json(v))).collect();
                                serde_json::Value::Object(obj)
                            }
                            Value::Nil => serde_json::Value::Null,
                            other => serde_json::Value::from(format!("{other}")),
                        }
                    }
                    serde_json::to_string_pretty(&value_to_json(&args[1]))
                        .unwrap_or_else(|e| format!("json error: {e}"))
                }
                other => return Err(RuntimeError::new("ILO-R009", format!("wr: unknown format '{other}', expected csv, tsv, or json"))),
            }
        } else {
            match &args[1] {
                Value::Text(s) => s.clone(),
                other => return Err(RuntimeError::new("ILO-R009", format!("wr: second arg must be text content, got {:?}", other))),
            }
        };
        return match std::fs::write(&path, &content) {
            Ok(()) => Ok(Value::Ok(Box::new(Value::Text(path)))),
            Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
        };
    }
    if name == "wrl" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Text(path), Value::List(lines)) => {
                let mut content = String::new();
                for line in lines {
                    match line {
                        Value::Text(s) => { content.push_str(s); content.push('\n'); }
                        other => return Err(RuntimeError::new("ILO-R009", format!("wrl list must contain text, got {:?}", other))),
                    }
                }
                match std::fs::write(path, &content) {
                    Ok(()) => Ok(Value::Ok(Box::new(Value::Text(path.clone())))),
                    Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
                }
            }
            other => Err(RuntimeError::new("ILO-R009", format!("wrl requires text path and list of text, got {:?}", other))),
        };
    }
    if name == "jpth" && args.len() == 2 {
        return match (&args[0], &args[1]) {
            (Value::Text(json_str), Value::Text(path)) => {
                match serde_json::from_str::<serde_json::Value>(json_str) {
                    Ok(parsed) => {
                        let mut current = &parsed;
                        for key in path.split('.') {
                            if let Ok(idx) = key.parse::<usize>() {
                                if let Some(v) = current.as_array().and_then(|a| a.get(idx)) {
                                    current = v;
                                } else {
                                    return Ok(Value::Err(Box::new(Value::Text(format!("key not found: {key}")))));
                                }
                            } else if let Some(v) = current.get(key) {
                                current = v;
                            } else {
                                return Ok(Value::Err(Box::new(Value::Text(format!("key not found: {key}")))));
                            }
                        }
                        let result_str = match current {
                            serde_json::Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };
                        Ok(Value::Ok(Box::new(Value::Text(result_str))))
                    }
                    Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
                }
            }
            _ => Err(RuntimeError::new("ILO-R009", "jpth requires two text args".to_string())),
        };
    }
    if name == "prnt" && args.len() == 1 {
        let v = args.into_iter().next().expect("prnt: arity=1 guaranteed by caller");
        println!("{v}");
        return Ok(v);
    }
    if name == "jdmp" && args.len() == 1 {
        let json_val = value_to_json(&args[0]);
        return Ok(Value::Text(json_val.to_string()));
    }
    if name == "jpar" && args.len() == 1 {
        return match &args[0] {
            Value::Text(s) => match serde_json::from_str::<serde_json::Value>(s) {
                Ok(v) => Ok(Value::Ok(Box::new(serde_json_to_value(v)))),
                Err(e) => Ok(Value::Err(Box::new(Value::Text(e.to_string())))),
            },
            other => Err(RuntimeError::new("ILO-R009", format!("jpar requires text, got {:?}", other))),
        };
    }

    if name == "env" && args.len() == 1 {
        return match &args[0] {
            Value::Text(key) => {
                match std::env::var(key.as_str()) {
                    Ok(val) => Ok(Value::Ok(Box::new(Value::Text(val)))),
                    Err(_) => Ok(Value::Err(Box::new(Value::Text(format!("env var '{}' not set", key))))),
                }
            }
            other => Err(RuntimeError::new("ILO-R009", format!("env requires text, got {:?}", other))),
        };
    }

    // Higher-order builtins: map, flt, fld
    // A function reference can be Value::FnRef(name) or Value::Text(name) when the
    // function name was passed as a CLI string argument.
    fn resolve_fn_ref(val: &Value) -> Option<String> {
        match val {
            Value::FnRef(n) => Some(n.clone()),
            Value::Text(n) => Some(n.clone()),
            _ => None,
        }
    }
    if name == "map" && args.len() == 2 {
        let fn_name = resolve_fn_ref(&args[0]).ok_or_else(|| {
            RuntimeError::new("ILO-R009", format!("map: first arg must be a function reference, got {:?}", args[0]))
        })?;
        let items = match &args[1] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("map: second arg must be a list, got {:?}", other))),
        };
        let mut result = Vec::with_capacity(items.len());
        for item in items {
            result.push(call_function(env, &fn_name, vec![item])?);
        }
        return Ok(Value::List(result));
    }
    if name == "flt" && args.len() == 2 {
        let fn_name = resolve_fn_ref(&args[0]).ok_or_else(|| {
            RuntimeError::new("ILO-R009", format!("flt: first arg must be a function reference, got {:?}", args[0]))
        })?;
        let items = match &args[1] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("flt: second arg must be a list, got {:?}", other))),
        };
        let mut result = Vec::new();
        for item in items {
            match call_function(env, &fn_name, vec![item.clone()])? {
                Value::Bool(true) => result.push(item),
                Value::Bool(false) => {}
                other => return Err(RuntimeError::new("ILO-R009", format!("flt: predicate must return bool, got {:?}", other))),
            }
        }
        return Ok(Value::List(result));
    }
    if name == "fld" && args.len() == 3 {
        let fn_name = resolve_fn_ref(&args[0]).ok_or_else(|| {
            RuntimeError::new("ILO-R009", format!("fld: first arg must be a function reference, got {:?}", args[0]))
        })?;
        let items = match &args[1] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("fld: second arg must be a list, got {:?}", other))),
        };
        let mut acc = args[2].clone();
        for item in items {
            acc = call_function(env, &fn_name, vec![acc, item])?;
        }
        return Ok(acc);
    }

    if name == "grp" && args.len() == 2 {
        let fn_name = resolve_fn_ref(&args[0]).ok_or_else(|| {
            RuntimeError::new("ILO-R009", format!("grp: first arg must be a function reference, got {:?}", args[0]))
        })?;
        let items = match &args[1] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("grp: second arg must be a list, got {:?}", other))),
        };
        let mut groups: std::collections::HashMap<String, Vec<Value>> = std::collections::HashMap::new();
        for item in items {
            let key = call_function(env, &fn_name, vec![item.clone()])?;
            let key_str = match &key {
                Value::Text(s) => s.clone(),
                Value::Number(n) => {
                    if *n == (*n as i64) as f64 {
                        format!("{}", *n as i64)
                    } else {
                        format!("{n}")
                    }
                }
                Value::Bool(b) => format!("{b}"),
                other => return Err(RuntimeError::new("ILO-R009", format!("grp: key function must return a string, number, or bool, got {:?}", other))),
            };
            groups.entry(key_str).or_default().push(item);
        }
        let map = groups.into_iter().map(|(k, v)| (k, Value::List(v))).collect();
        return Ok(Value::Map(map));
    }
    if name == "sum" && args.len() == 1 {
        let items = match &args[0] {
            Value::List(l) => l,
            other => return Err(RuntimeError::new("ILO-R009", format!("sum: arg must be a list, got {:?}", other))),
        };
        let mut total = 0.0_f64;
        for item in items {
            match item {
                Value::Number(n) => total += n,
                other => return Err(RuntimeError::new("ILO-R009", format!("sum: list elements must be numbers, got {:?}", other))),
            }
        }
        return Ok(Value::Number(total));
    }
    if name == "avg" && args.len() == 1 {
        let items = match &args[0] {
            Value::List(l) => l,
            other => return Err(RuntimeError::new("ILO-R009", format!("avg: arg must be a list, got {:?}", other))),
        };
        if items.is_empty() {
            return Err(RuntimeError::new("ILO-R009", "avg: cannot average an empty list".to_string()));
        }
        let mut total = 0.0_f64;
        for item in items {
            match item {
                Value::Number(n) => total += n,
                other => return Err(RuntimeError::new("ILO-R009", format!("avg: list elements must be numbers, got {:?}", other))),
            }
        }
        return Ok(Value::Number(total / items.len() as f64));
    }
    if name == "rgx" && args.len() == 2 {
        let pattern = match &args[0] {
            Value::Text(s) => s.as_str(),
            other => return Err(RuntimeError::new("ILO-R009", format!("rgx: first arg must be a string pattern, got {:?}", other))),
        };
        let input = match &args[1] {
            Value::Text(s) => s.as_str(),
            other => return Err(RuntimeError::new("ILO-R009", format!("rgx: second arg must be a string, got {:?}", other))),
        };
        let re = regex::Regex::new(pattern).map_err(|e| {
            RuntimeError::new("ILO-R009", format!("rgx: invalid regex pattern: {e}"))
        })?;
        let result: Vec<Value> = if re.captures_len() > 1 {
            // Has capture groups — return list of captured group strings
            re.captures(input)
                .map(|caps| {
                    (1..caps.len())
                        .filter_map(|i| caps.get(i).map(|m| Value::Text(m.as_str().to_string())))
                        .collect()
                })
                .unwrap_or_default()
        } else {
            // No capture groups — return list of all matches
            re.find_iter(input)
                .map(|m| Value::Text(m.as_str().to_string()))
                .collect()
        };
        return Ok(Value::List(result));
    }
    if name == "flat" && args.len() == 1 {
        let items = match &args[0] {
            Value::List(l) => l.clone(),
            other => return Err(RuntimeError::new("ILO-R009", format!("flat: arg must be a list, got {:?}", other))),
        };
        let mut result = Vec::new();
        for item in items {
            match item {
                Value::List(inner) => result.extend(inner),
                other => result.push(other),
            }
        }
        return Ok(Value::List(result));
    }

    // Dynamic dispatch: callee resolved to a FnRef at runtime
    // (e.g. calling a function passed as a parameter: `fn x` where fn:F n n)
    // This is handled by looking up `name` in scope within eval_expr, not here.


    let decl = env.function(name)?;
    match decl {
        Decl::Function { params, body, name: func_name, .. } => {
            if args.len() != params.len() {
                return Err(RuntimeError::new("ILO-R004", format!(
                    "{}: expected {} args, got {}", name, params.len(), args.len()
                )));
            }
            // Isolate the callee's scope from the caller's variables.
            let saved_vars = std::mem::take(&mut env.vars);
            let saved_marks = std::mem::replace(&mut env.scope_marks, vec![0]);
            for (param, arg) in params.iter().zip(args) {
                env.define(&param.name, arg);
            }
            env.call_stack.push(func_name.clone());
            let result = eval_body(env, &body);
            env.call_stack.pop();
            env.vars = saved_vars;
            env.scope_marks = saved_marks;
            match result? {
                BodyResult::Value(v) | BodyResult::Return(v) | BodyResult::Break(v) => Ok(v),
                BodyResult::Continue => Ok(Value::Nil),
            }
        }
        Decl::Tool { name, .. } => {
            if let Some(ref _provider) = env.tool_provider {
                #[cfg(feature = "tools")]
                {
                    if let Some(ref rt) = env.tokio_runtime {
                        return rt.block_on(_provider.call(&name, args))
                            .map_err(|e| RuntimeError::new("ILO-R099", e.to_string()));
                    }
                }
                // No async runtime available (or `tools` feature disabled);
                // fall through to stub.
                let args_str: Vec<String> = args.iter().map(|a| format!("{a}")).collect();
                eprintln!("tool call (no runtime): {}({})", name, args_str.join(", "));
                Ok(Value::Ok(Box::new(Value::Nil)))
            } else {
                // No provider: stub behaviour (matches original)
                let args_str: Vec<String> = args.iter().map(|a| format!("{a}")).collect();
                eprintln!("tool call: {}({})", name, args_str.join(", "));
                Ok(Value::Ok(Box::new(Value::Nil)))
            }
        }
        Decl::TypeDef { .. } => {
            Err(RuntimeError::new("ILO-R004", format!("{} is a type, not callable", name)))
        }
        Decl::Alias { .. } => {
            Err(RuntimeError::new("ILO-R004", format!("{} is a type alias, not callable", name)))
        }
        Decl::Use { .. } => {
            Err(RuntimeError::new("ILO-R002", format!("{} is an unresolved import", name)))
        }
        Decl::Error { .. } => {
            Err(RuntimeError::new("ILO-R002", format!("{} failed to parse", name)))
        }
    }
}

fn value_to_json(val: &Value) -> serde_json::Value {
    match val {
        Value::Number(n) => {
            if n.fract() == 0.0 && n.abs() < 1e15 {
                serde_json::Value::Number(serde_json::Number::from(*n as i64))
            } else {
                serde_json::Number::from_f64(*n)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::Null)
            }
        }
        Value::Text(s) => serde_json::Value::String(s.clone()),
        Value::Bool(b) => serde_json::Value::Bool(*b),
        Value::Nil => serde_json::Value::Null,
        Value::List(items) => serde_json::Value::Array(items.iter().map(value_to_json).collect()),
        Value::Record { fields, .. } => {
            let map: serde_json::Map<String, serde_json::Value> = fields.iter()
                .map(|(k, v)| (k.clone(), value_to_json(v)))
                .collect();
            serde_json::Value::Object(map)
        }
        Value::Map(m) => {
            let map: serde_json::Map<String, serde_json::Value> = m.iter()
                .map(|(k, v)| (k.clone(), value_to_json(v)))
                .collect();
            serde_json::Value::Object(map)
        }
        Value::Ok(inner) => value_to_json(inner),
        Value::Err(inner) => value_to_json(inner),
        Value::FnRef(name) => serde_json::Value::String(format!("<fn:{}>", name)),
    }
}

fn serde_json_to_value(v: serde_json::Value) -> Value {
    match v {
        serde_json::Value::Object(map) => {
            let fields: HashMap<String, Value> = map.into_iter()
                .map(|(k, v)| (k, serde_json_to_value(v)))
                .collect();
            Value::Record { type_name: "json".to_string(), fields }
        }
        serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(serde_json_to_value).collect()),
        serde_json::Value::String(s) => Value::Text(s),
        serde_json::Value::Number(n) => Value::Number(n.as_f64().unwrap_or(0.0)),
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Null => Value::Nil,
    }
}

fn eval_body(env: &mut Env, stmts: &[Spanned<Stmt>]) -> Result<BodyResult> {
    let mut last = Value::Nil;
    for (i, spanned) in stmts.iter().enumerate() {
        let is_last = i == stmts.len() - 1;
        match eval_stmt(env, &spanned.node, is_last) {
            Ok(Some(BodyResult::Return(v))) => return Ok(BodyResult::Return(v)),
            Ok(Some(BodyResult::Break(v))) => return Ok(BodyResult::Break(v)),
            Ok(Some(BodyResult::Continue)) => return Ok(BodyResult::Continue),
            Ok(Some(BodyResult::Value(v))) => last = v,
            Ok(None) => {}
            Err(mut e) => {
                // Auto-unwrap propagation: convert to early return
                if let Some(val) = e.propagate_value.take() {
                    return Ok(BodyResult::Return(*val));
                }
                if e.span.is_none() { e.span = Some(spanned.span); }
                if e.call_stack.is_empty() {
                    e.call_stack = env.call_stack.clone();
                }
                return Err(e);
            }
        }
    }
    Ok(BodyResult::Value(last))
}

fn eval_stmt(env: &mut Env, stmt: &Stmt, is_last: bool) -> Result<Option<BodyResult>> {
    match stmt {
        Stmt::Let { name, value } => {
            let val = eval_expr(env, value)?;
            env.set(name, val);
            Ok(None)
        }
        Stmt::Destructure { bindings, value } => {
            let val = eval_expr(env, value)?;
            match val {
                Value::Record { fields, .. } => {
                    for binding in bindings {
                        let field_val = fields.get(binding).cloned().ok_or_else(|| {
                            RuntimeError::new("ILO-R005", format!("no field '{}' on record", binding))
                        })?;
                        env.set(binding, field_val);
                    }
                    Ok(None)
                }
                _ => Err(RuntimeError::new("ILO-R005", "destructure requires a record".to_string())),
            }
        }
        Stmt::Guard { condition, negated, body, else_body } => {
            let cond = eval_expr(env, condition)?;
            let truth = is_truthy(&cond);
            let should_run = if *negated { !truth } else { truth };
            if let Some(else_b) = else_body {
                // Ternary: cond{then}{else} — produces value, no early return
                let chosen = if should_run { body } else { else_b };
                env.push_scope();
                let result = eval_body(env, chosen);
                env.pop_scope();
                match result? {
                    BodyResult::Break(v) => Ok(Some(BodyResult::Break(v))),
                    BodyResult::Continue => Ok(Some(BodyResult::Continue)),
                    BodyResult::Value(v) | BodyResult::Return(v) => {
                        Ok(Some(BodyResult::Value(v)))
                    }
                }
            } else if should_run {
                // Guard: cond{body} — early return from function
                env.push_scope();
                let result = eval_body(env, body);
                env.pop_scope();
                match result? {
                    BodyResult::Break(v) => Ok(Some(BodyResult::Break(v))),
                    BodyResult::Continue => Ok(Some(BodyResult::Continue)),
                    BodyResult::Value(v) | BodyResult::Return(v) => {
                        Ok(Some(BodyResult::Return(v)))
                    }
                }
            } else {
                Ok(None)
            }
        }
        Stmt::Match { subject, arms } => {
            let subj = match subject {
                Some(e) => eval_expr(env, e)?,
                None => Value::Nil,
            };
            for arm in arms {
                if let Some(bindings) = match_pattern(&arm.pattern, &subj) {
                    env.push_scope();
                    for (name, val) in bindings {
                        env.define(&name, val);
                    }
                    let result = eval_body(env, &arm.body);
                    env.pop_scope();
                    match result? {
                        BodyResult::Return(v) => return Ok(Some(BodyResult::Return(v))),
                        BodyResult::Break(v) => return Ok(Some(BodyResult::Break(v))),
                        BodyResult::Continue => return Ok(Some(BodyResult::Continue)),
                        BodyResult::Value(v) => {
                            if is_last {
                                return Ok(Some(BodyResult::Return(v)));
                            }
                            return Ok(Some(BodyResult::Value(v)));
                        }
                    }
                }
            }
            Ok(None)
        }
        Stmt::ForEach { binding, collection, body } => {
            let coll = eval_expr(env, collection)?;
            match coll {
                Value::List(items) => {
                    let mut last = Value::Nil;
                    for item in items {
                        env.push_scope();
                        env.define(binding, item);
                        let result = eval_body(env, body);
                        env.pop_scope();
                        match result? {
                            BodyResult::Return(v) => {
                                return Ok(Some(BodyResult::Return(v)));
                            }
                            BodyResult::Break(v) => {
                                last = v;
                                break;
                            }
                            BodyResult::Continue => continue,
                            BodyResult::Value(v) => last = v,
                        }
                    }
                    Ok(Some(BodyResult::Value(last)))
                }
                _ => Err(RuntimeError::new("ILO-R007", "foreach requires a list")),
            }
        }
        Stmt::ForRange { binding, start, end, body } => {
            let start_val = eval_expr(env, start)?;
            let end_val = eval_expr(env, end)?;
            let s = match start_val {
                Value::Number(n) => n as i64,
                _ => return Err(RuntimeError::new("ILO-R007", "range start must be a number")),
            };
            let e = match end_val {
                Value::Number(n) => n as i64,
                _ => return Err(RuntimeError::new("ILO-R007", "range end must be a number")),
            };
            let mut last = Value::Nil;
            for i in s..e {
                env.push_scope();
                env.define(binding, Value::Number(i as f64));
                let result = eval_body(env, body);
                env.pop_scope();
                match result? {
                    BodyResult::Return(v) => {
                        return Ok(Some(BodyResult::Return(v)));
                    }
                    BodyResult::Break(v) => {
                        last = v;
                        break;
                    }
                    BodyResult::Continue => continue,
                    BodyResult::Value(v) => last = v,
                }
            }
            Ok(Some(BodyResult::Value(last)))
        }
        Stmt::While { condition, body } => {
            let mut last = Value::Nil;
            loop {
                let cond = eval_expr(env, condition)?;
                if !is_truthy(&cond) {
                    break;
                }
                let result = eval_body(env, body);
                match result? {
                    BodyResult::Return(v) => {
                        return Ok(Some(BodyResult::Return(v)));
                    }
                    BodyResult::Break(v) => {
                        last = v;
                        break;
                    }
                    BodyResult::Continue => continue,
                    BodyResult::Value(v) => last = v,
                }
            }
            Ok(Some(BodyResult::Value(last)))
        }
        Stmt::Return(expr) => {
            let val = eval_expr(env, expr)?;
            Ok(Some(BodyResult::Return(val)))
        }
        Stmt::Break(expr) => {
            let val = match expr {
                Some(e) => eval_expr(env, e)?,
                None => Value::Nil,
            };
            Ok(Some(BodyResult::Break(val)))
        }
        Stmt::Continue => {
            Ok(Some(BodyResult::Continue))
        }
        Stmt::Expr(expr) => {
            let val = eval_expr(env, expr)?;
            Ok(Some(BodyResult::Value(val)))
        }
    }
}

fn eval_expr(env: &mut Env, expr: &Expr) -> Result<Value> {
    match expr {
        Expr::Literal(lit) => Ok(eval_literal(lit)),
        Expr::Ref(name) => env.get(name),
        Expr::Field { object, field, safe } => {
            let obj = eval_expr(env, object)?;
            if *safe && matches!(obj, Value::Nil) {
                return Ok(Value::Nil);
            }
            match obj {
                Value::Record { fields, .. } => {
                    fields.get(field).cloned().ok_or_else(|| {
                        RuntimeError::new("ILO-R005", format!("no field '{}' on record", field))
                    })
                }
                _ => Err(RuntimeError::new("ILO-R005", format!("cannot access field '{}' on non-record", field))),
            }
        }
        Expr::Index { object, index, safe } => {
            let obj = eval_expr(env, object)?;
            if *safe && matches!(obj, Value::Nil) {
                return Ok(Value::Nil);
            }
            match obj {
                Value::List(items) => {
                    items.get(*index).cloned().ok_or_else(|| {
                        RuntimeError::new("ILO-R006", format!("list index {} out of bounds (len {})", index, items.len()))
                    })
                }
                _ => Err(RuntimeError::new("ILO-R006", "index access on non-list")),
            }
        }
        Expr::Call { function, args, unwrap } => {
            let mut arg_vals = Vec::new();
            for arg in args {
                arg_vals.push(eval_expr(env, arg)?);
            }
            // If `function` is a local variable holding a FnRef (or a Text that names a
            // function), resolve dynamically. This enables user-defined HOFs and CLI usage.
            let callee_from_scope = env.vars.iter().rev()
                .find(|(k, _)| k == function.as_str())
                .map(|(_, v)| v.clone());
            let callee = match callee_from_scope {
                Some(Value::FnRef(name)) => name,
                Some(Value::Text(name)) if env.functions.contains_key(&name) => name,
                _ => function.clone(),
            };
            let result = call_function(env, &callee, arg_vals)?;
            if *unwrap {
                match result {
                    Value::Ok(v) => Ok(*v),
                    Value::Err(e) => Err(RuntimeError {
                        propagate_value: Some(Box::new(Value::Err(e))),
                        ..RuntimeError::new("ILO-R014", "auto-unwrap propagating Err")
                    }),
                    other => Ok(other), // non-Result values pass through
                }
            } else {
                Ok(result)
            }
        }
        Expr::BinOp { op, left, right } => {
            // Short-circuit for logical ops
            if *op == BinOp::And {
                let l = eval_expr(env, left)?;
                return if !is_truthy(&l) { Ok(l) } else { eval_expr(env, right) };
            }
            if *op == BinOp::Or {
                let l = eval_expr(env, left)?;
                return if is_truthy(&l) { Ok(l) } else { eval_expr(env, right) };
            }
            let l = eval_expr(env, left)?;
            let r = eval_expr(env, right)?;
            eval_binop(op, &l, &r)
        }
        Expr::UnaryOp { op, operand } => {
            let val = eval_expr(env, operand)?;
            match op {
                UnaryOp::Not => Ok(Value::Bool(!is_truthy(&val))),
                UnaryOp::Negate => match val {
                    Value::Number(n) => Ok(Value::Number(-n)),
                    _ => Err(RuntimeError::new("ILO-R004", "cannot negate non-number")),
                },
            }
        }
        Expr::Ok(inner) => {
            let val = eval_expr(env, inner)?;
            Ok(Value::Ok(Box::new(val)))
        }
        Expr::Err(inner) => {
            let val = eval_expr(env, inner)?;
            Ok(Value::Err(Box::new(val)))
        }
        Expr::List(items) => {
            let mut vals = Vec::new();
            for item in items {
                vals.push(eval_expr(env, item)?);
            }
            Ok(Value::List(vals))
        }
        Expr::Record { type_name, fields } => {
            let mut field_map = HashMap::new();
            for (name, val_expr) in fields {
                field_map.insert(name.clone(), eval_expr(env, val_expr)?);
            }
            Ok(Value::Record {
                type_name: type_name.clone(),
                fields: field_map,
            })
        }
        Expr::Match { subject, arms } => {
            let subj = match subject {
                Some(e) => eval_expr(env, e)?,
                None => Value::Nil,
            };
            for arm in arms {
                if let Some(bindings) = match_pattern(&arm.pattern, &subj) {
                    env.push_scope();
                    for (name, val) in bindings {
                        env.define(&name, val);
                    }
                    let result = eval_body(env, &arm.body);
                    env.pop_scope();
                    return match result? {
                        BodyResult::Value(v) | BodyResult::Return(v) | BodyResult::Break(v) => Ok(v),
                        BodyResult::Continue => Ok(Value::Nil),
                    };
                }
            }
            Ok(Value::Nil)
        }
        Expr::NilCoalesce { value, default } => {
            let val = eval_expr(env, value)?;
            if matches!(val, Value::Nil) {
                eval_expr(env, default)
            } else {
                Ok(val)
            }
        }
        Expr::With { object, updates } => {
            let obj = eval_expr(env, object)?;
            match obj {
                Value::Record { type_name, mut fields } => {
                    for (name, val_expr) in updates {
                        fields.insert(name.clone(), eval_expr(env, val_expr)?);
                    }
                    Ok(Value::Record { type_name, fields })
                }
                _ => Err(RuntimeError::new("ILO-R008", "'with' requires a record")),
            }
        }
    }
}

fn eval_literal(lit: &Literal) -> Value {
    match lit {
        Literal::Number(n) => Value::Number(*n),
        Literal::Text(s) => Value::Text(s.clone()),
        Literal::Bool(b) => Value::Bool(*b),
    }
}

fn eval_binop(op: &BinOp, left: &Value, right: &Value) -> Result<Value> {
    match (op, left, right) {
        // Numeric ops
        (BinOp::Add, Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
        (BinOp::Subtract, Value::Number(a), Value::Number(b)) => Ok(Value::Number(a - b)),
        (BinOp::Multiply, Value::Number(a), Value::Number(b)) => Ok(Value::Number(a * b)),
        (BinOp::Divide, Value::Number(a), Value::Number(b)) => {
            if *b == 0.0 {
                Err(RuntimeError::new("ILO-R003", "division by zero"))
            } else {
                Ok(Value::Number(a / b))
            }
        }
        // String concatenation with +
        (BinOp::Add, Value::Text(a), Value::Text(b)) => {
            let mut out = String::with_capacity(a.len() + b.len());
            out.push_str(a);
            out.push_str(b);
            Ok(Value::Text(out))
        }
        // List concatenation with +
        (BinOp::Add, Value::List(a), Value::List(b)) => {
            let mut out = Vec::with_capacity(a.len() + b.len());
            out.extend_from_slice(a);
            out.extend_from_slice(b);
            Ok(Value::List(out))
        }
        // Comparisons on numbers
        (BinOp::GreaterThan, Value::Number(a), Value::Number(b)) => Ok(Value::Bool(a > b)),
        (BinOp::LessThan, Value::Number(a), Value::Number(b)) => Ok(Value::Bool(a < b)),
        (BinOp::GreaterOrEqual, Value::Number(a), Value::Number(b)) => Ok(Value::Bool(a >= b)),
        (BinOp::LessOrEqual, Value::Number(a), Value::Number(b)) => Ok(Value::Bool(a <= b)),
        // Comparisons on text (lexicographic)
        (BinOp::GreaterThan, Value::Text(a), Value::Text(b)) => Ok(Value::Bool(a > b)),
        (BinOp::LessThan, Value::Text(a), Value::Text(b)) => Ok(Value::Bool(a < b)),
        (BinOp::GreaterOrEqual, Value::Text(a), Value::Text(b)) => Ok(Value::Bool(a >= b)),
        (BinOp::LessOrEqual, Value::Text(a), Value::Text(b)) => Ok(Value::Bool(a <= b)),
        // List append
        (BinOp::Append, Value::List(items), val) => {
            let mut new_items = items.clone();
            new_items.push(val.clone());
            Ok(Value::List(new_items))
        }
        // Equality
        (BinOp::Equals, a, b) => Ok(Value::Bool(values_equal(a, b))),
        (BinOp::NotEquals, a, b) => Ok(Value::Bool(!values_equal(a, b))),
        _ => Err(RuntimeError::new("ILO-R004", format!(
            "unsupported operation: {:?} on {:?} and {:?}", op, left, right
        ))),
    }
}

fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(a), Value::Number(b)) => (a - b).abs() < f64::EPSILON,
        (Value::Text(a), Value::Text(b)) => a == b,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Nil, Value::Nil) => true,
        _ => false,
    }
}

fn is_truthy(val: &Value) -> bool {
    match val {
        Value::Bool(b) => *b,
        Value::Nil => false,
        Value::Number(n) => *n != 0.0,
        Value::Text(s) => !s.is_empty(),
        Value::List(l) => !l.is_empty(),
        _ => true,
    }
}

fn match_pattern(pattern: &Pattern, value: &Value) -> Option<Vec<(String, Value)>> {
    match pattern {
        Pattern::Wildcard => Some(vec![]),
        Pattern::Ok(binding) => {
            if let Value::Ok(inner) = value {
                let mut bindings = vec![];
                if binding != "_" {
                    bindings.push((binding.clone(), *inner.clone()));
                }
                Some(bindings)
            } else {
                None
            }
        }
        Pattern::Err(binding) => {
            if let Value::Err(inner) = value {
                let mut bindings = vec![];
                if binding != "_" {
                    bindings.push((binding.clone(), *inner.clone()));
                }
                Some(bindings)
            } else {
                None
            }
        }
        Pattern::Literal(lit) => {
            let expected = eval_literal(lit);
            if values_equal(&expected, value) {
                Some(vec![])
            } else {
                None
            }
        }
        Pattern::TypeIs { ty, binding } => {
            let matches = match ty {
                Type::Number => matches!(value, Value::Number(_)),
                Type::Text => matches!(value, Value::Text(_)),
                Type::Bool => matches!(value, Value::Bool(_)),
                Type::List(_) => matches!(value, Value::List(_)),
                _ => false,
            };
            if matches {
                let mut bindings = vec![];
                if binding != "_" {
                    bindings.push((binding.clone(), value.clone()));
                }
                Some(bindings)
            } else {
                None
            }
        }
    }
}

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

    static ENV_TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn parse_program(source: &str) -> Program {
        let tokens = lexer::lex(source).unwrap();
        let token_spans: Vec<(crate::lexer::Token, crate::ast::Span)> = tokens
            .into_iter()
            .map(|(t, r)| (t, crate::ast::Span { start: r.start, end: r.end }))
            .collect();
        let (prog, errors) = parser::parse(token_spans);
        assert!(errors.is_empty(), "parse errors: {:?}", errors);
        prog
    }

    fn run_str(source: &str, func: Option<&str>, args: Vec<Value>) -> Value {
        let prog = parse_program(source);
        run(&prog, func, args).unwrap()
    }

    #[test]
    fn interpret_tot() {
        // tot p:n q:n r:n>n;s=*p q;t=*s r;+s t
        let source = std::fs::read_to_string("research/explorations/idea9-ultra-dense-short/01-simple-function.ilo").unwrap();
        let result = run_str(
            &source,
            Some("tot"),
            vec![Value::Number(10.0), Value::Number(20.0), Value::Number(30.0)],
        );
        assert_eq!(result, Value::Number(6200.0));
    }

    #[test]
    fn interpret_tot_different_args() {
        let source = "tot p:n q:n r:n>n;s=*p q;t=*s r;+s t";
        let result = run_str(
            source,
            Some("tot"),
            vec![Value::Number(2.0), Value::Number(3.0), Value::Number(4.0)],
        );
        // s = 2*3 = 6, t = 6*4 = 24, s+t = 30
        assert_eq!(result, Value::Number(30.0));
    }

    #[test]
    fn interpret_cls_gold() {
        let source = r#"cls sp:n>t;>=sp 1000{"gold"};>=sp 500{"silver"};"bronze""#;
        let result = run_str(source, Some("cls"), vec![Value::Number(1000.0)]);
        assert_eq!(result, Value::Text("gold".to_string()));
    }

    #[test]
    fn interpret_cls_silver() {
        let source = r#"cls sp:n>t;>=sp 1000{"gold"};>=sp 500{"silver"};"bronze""#;
        let result = run_str(source, Some("cls"), vec![Value::Number(500.0)]);
        assert_eq!(result, Value::Text("silver".to_string()));
    }

    #[test]
    fn interpret_cls_bronze() {
        let source = r#"cls sp:n>t;>=sp 1000{"gold"};>=sp 500{"silver"};"bronze""#;
        let result = run_str(source, Some("cls"), vec![Value::Number(100.0)]);
        assert_eq!(result, Value::Text("bronze".to_string()));
    }

    #[test]
    fn interpret_match_stmt() {
        let source = r#"f x:t>n;?x{"a":1;"b":2;_:0}"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("a".to_string())]),
            Value::Number(1.0)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("b".to_string())]),
            Value::Number(2.0)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("z".to_string())]),
            Value::Number(0.0)
        );
    }

    #[test]
    fn interpret_ok_err() {
        let source = "f x:n>R n t;~x";
        let result = run_str(source, Some("f"), vec![Value::Number(42.0)]);
        assert_eq!(result, Value::Ok(Box::new(Value::Number(42.0))));
    }

    #[test]
    fn interpret_err_constructor() {
        let source = r#"f x:n>R n t;^"bad""#;
        let result = run_str(source, Some("f"), vec![Value::Number(0.0)]);
        assert_eq!(result, Value::Err(Box::new(Value::Text("bad".to_string()))));
    }

    #[test]
    fn interpret_match_ok_err_patterns() {
        let source = r#"f x:R n t>n;?x{^e:0;~v:v}"#;
        let ok_result = run_str(
            source,
            Some("f"),
            vec![Value::Ok(Box::new(Value::Number(42.0)))],
        );
        assert_eq!(ok_result, Value::Number(42.0));

        let err_result = run_str(
            source,
            Some("f"),
            vec![Value::Err(Box::new(Value::Text("oops".to_string())))],
        );
        assert_eq!(err_result, Value::Number(0.0));
    }

    #[test]
    fn interpret_negated_guard() {
        let source = r#"f x:b>t;!x{"nope"};"yes""#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(false)]),
            Value::Text("nope".to_string())
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(true)]),
            Value::Text("yes".to_string())
        );
    }

    #[test]
    fn interpret_logical_not() {
        let source = "f x:b>b;!x";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(true)]),
            Value::Bool(false)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(false)]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_record_and_field() {
        let source = "f x:n>n;r=point x:x y:10;r.y";
        let result = run_str(source, Some("f"), vec![Value::Number(5.0)]);
        assert_eq!(result, Value::Number(10.0));
    }

    #[test]
    fn interpret_with_expr() {
        let source = "f>n;r=point x:1 y:2;r2=r with y:10;r2.y";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Number(10.0));
    }

    #[test]
    fn interpret_string_concat() {
        let source = r#"f a:t b:t>t;+a b"#;
        let result = run_str(
            source,
            Some("f"),
            vec![Value::Text("hello ".to_string()), Value::Text("world".to_string())],
        );
        assert_eq!(result, Value::Text("hello world".to_string()));
    }

    #[test]
    fn interpret_string_comparison() {
        let gt = r#"f a:t b:t>b;>a b"#;
        assert_eq!(
            run_str(gt, Some("f"), vec![Value::Text("banana".into()), Value::Text("apple".into())]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(gt, Some("f"), vec![Value::Text("apple".into()), Value::Text("banana".into())]),
            Value::Bool(false)
        );

        let lt = r#"f a:t b:t>b;<a b"#;
        assert_eq!(
            run_str(lt, Some("f"), vec![Value::Text("apple".into()), Value::Text("banana".into())]),
            Value::Bool(true)
        );

        let ge = r#"f a:t b:t>b;>=a b"#;
        assert_eq!(
            run_str(ge, Some("f"), vec![Value::Text("apple".into()), Value::Text("apple".into())]),
            Value::Bool(true)
        );

        let le = r#"f a:t b:t>b;<=a b"#;
        assert_eq!(
            run_str(le, Some("f"), vec![Value::Text("zebra".into()), Value::Text("banana".into())]),
            Value::Bool(false)
        );
    }

    #[test]
    fn interpret_match_expr_in_let() {
        let source = r#"f x:t>n;y=?x{"a":1;"b":2;_:0};y"#;
        let result = run_str(source, Some("f"), vec![Value::Text("b".to_string())]);
        assert_eq!(result, Value::Number(2.0));
    }

    #[test]
    fn interpret_default_first_function() {
        let source = "f>n;42";
        let result = run_str(source, None, vec![]);
        assert_eq!(result, Value::Number(42.0));
    }

    #[test]
    fn interpret_division_by_zero() {
        let source = "f x:n>n;/x 0";
        let prog = parse_program(source);
        let result = run(&prog, Some("f"), vec![Value::Number(10.0)]);
        assert!(result.is_err());
    }

    #[test]
    fn interpret_logical_and() {
        let source = "f a:b b:b>b;&a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(true), Value::Bool(true)]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(true), Value::Bool(false)]),
            Value::Bool(false)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(false), Value::Bool(true)]),
            Value::Bool(false)
        );
    }

    #[test]
    fn interpret_logical_or() {
        let source = "f a:b b:b>b;|a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(false), Value::Bool(false)]),
            Value::Bool(false)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(true), Value::Bool(false)]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Bool(false), Value::Bool(true)]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_len_string() {
        let source = r#"f s:t>n;len s"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("hello".to_string())]),
            Value::Number(5.0)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("".to_string())]),
            Value::Number(0.0)
        );
    }

    #[test]
    fn interpret_len_list() {
        let source = "f>n;xs=[1, 2, 3];len xs";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_list_append() {
        let source = "f>L n;xs=[1, 2];+=xs 3";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0)])
        );
    }

    #[test]
    fn interpret_list_append_empty() {
        let source = "f>L n;xs=[];+=xs 42";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(42.0)])
        );
    }

    #[test]
    fn interpret_list_concat() {
        let source = "f>L n;a=[1, 2];b=[3, 4];+a b";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0), Value::Number(4.0)])
        );
    }

    #[test]
    fn interpret_str_integer() {
        let source = "f>t;str 42";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("42".into()));
    }

    #[test]
    fn interpret_str_float() {
        let source = "f>t;str 3.14";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("3.14".into()));
    }

    #[test]
    fn interpret_num_ok() {
        let source = "f>R n t;num \"42\"";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Ok(Box::new(Value::Number(42.0))));
    }

    #[test]
    fn interpret_num_err() {
        let source = "f>R n t;num \"abc\"";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Err(Box::new(Value::Text("abc".into()))));
    }

    #[test]
    fn interpret_abs() {
        let source = "f>n;abs -7";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(7.0));
    }

    #[test]
    fn interpret_min() {
        let source = "f>n;min 3 7";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_max() {
        let source = "f>n;max 3 7";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(7.0));
    }

    #[test]
    fn interpret_flr() {
        let source = "f>n;flr 3.7";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_cel() {
        let source = "f>n;cel 3.2";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(4.0));
    }

    #[test]
    fn interpret_index_access() {
        let source = "f>n;xs=[10, 20, 30];xs.1";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(20.0));
    }

    #[test]
    fn interpret_index_access_string() {
        let source = "f>t;xs=[\"hello\", \"world\"];xs.0";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("hello".into()));
    }

    #[test]
    fn interpret_multi_function() {
        let source = "double x:n>n;*x 2\nf x:n>n;double x";
        let result = run_str(source, Some("f"), vec![Value::Number(5.0)]);
        assert_eq!(result, Value::Number(10.0));
    }

    #[test]
    fn interpret_nested_multiply_add() {
        // +*a b c → (a * b) + c
        let source = "f a:n b:n c:n>n;+*a b c";
        let result = run_str(source, Some("f"), vec![Value::Number(2.0), Value::Number(3.0), Value::Number(4.0)]);
        assert_eq!(result, Value::Number(10.0));
    }

    #[test]
    fn interpret_nested_compare() {
        // >=+x y 100 → (x + y) >= 100
        let source = "f x:n y:n>b;>=+x y 100";
        let result = run_str(source, Some("f"), vec![Value::Number(60.0), Value::Number(50.0)]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_not_as_and_operand() {
        // &!x y → (!x) & y
        let source = "f x:b y:b>b;&!x y";
        let result = run_str(source, Some("f"), vec![Value::Bool(false), Value::Bool(true)]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_negate_product() {
        // -*a b → -(a * b)
        let source = "f a:n b:n>n;-*a b";
        let result = run_str(source, Some("f"), vec![Value::Number(3.0), Value::Number(4.0)]);
        assert_eq!(result, Value::Number(-12.0));
    }

    // ── Helper for error tests ──────────────────────────────────────────

    fn run_str_err(source: &str, func: Option<&str>, args: Vec<Value>) -> String {
        let prog = parse_program(source);
        run(&prog, func, args).unwrap_err().to_string()
    }

    // ── Value::fmt Display tests ────────────────────────────────────────

    #[test]
    fn display_float() {
        assert_eq!(format!("{}", Value::Number(3.14)), "3.14");
    }

    #[test]
    fn display_integer_number() {
        assert_eq!(format!("{}", Value::Number(42.0)), "42");
    }

    #[test]
    fn display_text() {
        assert_eq!(format!("{}", Value::Text("hello".into())), "hello");
    }

    #[test]
    fn display_bool() {
        assert_eq!(format!("{}", Value::Bool(true)), "true");
        assert_eq!(format!("{}", Value::Bool(false)), "false");
    }

    #[test]
    fn display_nil() {
        assert_eq!(format!("{}", Value::Nil), "nil");
    }

    #[test]
    fn display_list() {
        let list = Value::List(vec![
            Value::Number(1.0),
            Value::Number(2.0),
            Value::Number(3.0),
        ]);
        assert_eq!(format!("{}", list), "[1, 2, 3]");
    }

    #[test]
    fn display_list_empty() {
        assert_eq!(format!("{}", Value::List(vec![])), "[]");
    }

    #[test]
    fn display_record() {
        let mut fields = HashMap::new();
        fields.insert("x".to_string(), Value::Number(1.0));
        let rec = Value::Record {
            type_name: "point".into(),
            fields,
        };
        assert_eq!(format!("{}", rec), "point {x: 1}");
    }

    #[test]
    fn display_record_multiple_fields() {
        let mut fields = HashMap::new();
        fields.insert("a".to_string(), Value::Number(1.0));
        fields.insert("b".to_string(), Value::Number(2.0));
        let rec = Value::Record {
            type_name: "pair".into(),
            fields,
        };
        let s = format!("{}", rec);
        assert!(s.starts_with("pair {"));
        assert!(s.contains("a: 1"));
        assert!(s.contains("b: 2"));
        assert!(s.ends_with("}"));
    }

    #[test]
    fn display_ok() {
        assert_eq!(
            format!("{}", Value::Ok(Box::new(Value::Number(42.0)))),
            "~42"
        );
    }

    #[test]
    fn display_err() {
        assert_eq!(
            format!("{}", Value::Err(Box::new(Value::Text("bad".into())))),
            "^bad"
        );
    }

    // ── Error path tests ────────────────────────────────────────────────

    #[test]
    fn err_undefined_variable() {
        let err = run_str_err("f>n;x", Some("f"), vec![]);
        assert!(err.contains("undefined variable"));
    }

    #[test]
    fn err_undefined_function() {
        let err = run_str_err("f>n;nope 1", Some("f"), vec![]);
        assert!(err.contains("undefined function"));
    }

    #[test]
    fn err_wrong_arity() {
        let err = run_str_err("f x:n>n;x", Some("f"), vec![]);
        assert!(err.contains("expected 1 args, got 0"));
    }

    #[test]
    fn err_len_wrong_arg_count() {
        let err = run_str_err("f>n;len 1 2", Some("f"), vec![]);
        assert!(err.contains("len: expected 1 arg"));
    }

    #[test]
    fn err_len_wrong_type() {
        let err = run_str_err("f x:n>n;len x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("len requires string, list, or map"));
    }

    #[test]
    fn err_str_wrong_arg_count() {
        let err = run_str_err("f>t;str 1 2", Some("f"), vec![]);
        assert!(err.contains("str: expected 1 arg"));
    }

    #[test]
    fn err_str_wrong_type() {
        let err = run_str_err(r#"f x:t>t;str x"#, Some("f"), vec![Value::Text("hi".into())]);
        assert!(err.contains("str requires a number"));
    }

    #[test]
    fn err_num_wrong_arg_count() {
        let err = run_str_err(r#"f>R n t;num "1" "2""#, Some("f"), vec![]);
        assert!(err.contains("num: expected 1 arg"));
    }

    #[test]
    fn err_num_wrong_type() {
        let err = run_str_err("f x:n>R n t;num x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("num requires text"));
    }

    #[test]
    fn err_abs_wrong_arg_count() {
        let err = run_str_err("f>n;abs 1 2", Some("f"), vec![]);
        assert!(err.contains("abs: expected 1 arg"));
    }

    #[test]
    fn err_abs_wrong_type() {
        let err = run_str_err(r#"f x:t>n;abs x"#, Some("f"), vec![Value::Text("hi".into())]);
        assert!(err.contains("abs requires a number"));
    }

    #[test]
    fn err_min_non_number() {
        let err = run_str_err(
            r#"f a:t b:t>n;min a b"#,
            Some("f"),
            vec![Value::Text("a".into()), Value::Text("b".into())],
        );
        assert!(err.contains("min requires two numbers"));
    }

    #[test]
    fn err_max_non_number() {
        let err = run_str_err(
            r#"f a:t b:t>n;max a b"#,
            Some("f"),
            vec![Value::Text("a".into()), Value::Text("b".into())],
        );
        assert!(err.contains("max requires two numbers"));
    }

    #[test]
    fn err_flr_non_number() {
        let err = run_str_err(r#"f x:t>n;flr x"#, Some("f"), vec![Value::Text("a".into())]);
        assert!(err.contains("flr requires a number"));
    }

    #[test]
    fn err_cel_non_number() {
        let err = run_str_err(r#"f x:t>n;cel x"#, Some("f"), vec![Value::Text("a".into())]);
        assert!(err.contains("cel requires a number"));
    }

    #[test]
    fn err_field_not_found_on_record() {
        let err = run_str_err("f>n;r=point x:1 y:2;r.z", Some("f"), vec![]);
        assert!(err.contains("no field 'z' on record"));
    }

    #[test]
    fn err_field_access_on_non_record() {
        let err = run_str_err("f x:n>n;x.y", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("cannot access field"));
    }

    #[test]
    fn err_index_out_of_bounds() {
        let err = run_str_err("f>n;xs=[1, 2];xs.5", Some("f"), vec![]);
        assert!(err.contains("out of bounds"));
    }

    #[test]
    fn err_index_on_non_list() {
        let err = run_str_err("f x:n>n;x.0", Some("f"), vec![Value::Number(1.0)]);
        // x.0 is an index access; on a number it should error
        assert!(
            err.contains("index access on non-list") || err.contains("cannot access field"),
            "got: {}", err
        );
    }

    #[test]
    fn err_negate_non_number() {
        let err = run_str_err(r#"f>n;-"hello""#, Some("f"), vec![]);
        assert!(err.contains("cannot negate non-number"));
    }

    #[test]
    fn err_with_on_non_record() {
        let err = run_str_err("f x:n>n;x with y:1", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("'with' requires a record"));
    }

    // ── Missing operational tests ───────────────────────────────────────

    #[test]
    fn interpret_foreach() {
        // Sum the list by calling an accumulator pattern
        // Simple: foreach that returns last value (last element * 2)
        let source = "f>n;s=0;@x [1, 2, 3]{+s x}";
        let result = run_str(source, Some("f"), vec![]);
        // ForEach returns the last body value: 0 + 3 = 3
        // (each iteration: s is still 0 because we don't reassign, body is +s x)
        // iteration 1: +0 1 = 1, iteration 2: +0 2 = 2, iteration 3: +0 3 = 3
        assert_eq!(result, Value::Number(3.0));
    }

    #[test]
    fn interpret_subtract() {
        let source = "f a:n b:n>n;-a b";
        let result = run_str(
            source,
            Some("f"),
            vec![Value::Number(10.0), Value::Number(3.0)],
        );
        assert_eq!(result, Value::Number(7.0));
    }

    #[test]
    fn interpret_divide() {
        let source = "f a:n b:n>n;/a b";
        let result = run_str(
            source,
            Some("f"),
            vec![Value::Number(10.0), Value::Number(4.0)],
        );
        assert_eq!(result, Value::Number(2.5));
    }

    #[test]
    fn interpret_equals() {
        let source = "f a:n b:n>b;=a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(1.0), Value::Number(1.0)]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(1.0), Value::Number(2.0)]),
            Value::Bool(false)
        );
    }

    #[test]
    fn interpret_not_equals() {
        let source = "f a:n b:n>b;!=a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(1.0), Value::Number(2.0)]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(1.0), Value::Number(1.0)]),
            Value::Bool(false)
        );
    }

    #[test]
    fn values_equal_numbers() {
        assert!(values_equal(&Value::Number(1.0), &Value::Number(1.0)));
        assert!(!values_equal(&Value::Number(1.0), &Value::Number(2.0)));
    }

    #[test]
    fn values_equal_bools() {
        assert!(values_equal(&Value::Bool(true), &Value::Bool(true)));
        assert!(!values_equal(&Value::Bool(true), &Value::Bool(false)));
    }

    #[test]
    fn values_equal_nil() {
        assert!(values_equal(&Value::Nil, &Value::Nil));
    }

    #[test]
    fn values_equal_mismatched() {
        assert!(!values_equal(&Value::Number(1.0), &Value::Text("1".into())));
        assert!(!values_equal(&Value::Nil, &Value::Bool(false)));
    }

    #[test]
    fn is_truthy_nil() {
        assert!(!is_truthy(&Value::Nil));
    }

    #[test]
    fn is_truthy_number_zero() {
        assert!(!is_truthy(&Value::Number(0.0)));
    }

    #[test]
    fn is_truthy_number_nonzero() {
        assert!(is_truthy(&Value::Number(1.0)));
        assert!(is_truthy(&Value::Number(-5.0)));
    }

    #[test]
    fn is_truthy_text() {
        assert!(!is_truthy(&Value::Text("".into())));
        assert!(is_truthy(&Value::Text("hello".into())));
    }

    #[test]
    fn is_truthy_list() {
        assert!(!is_truthy(&Value::List(vec![])));
        assert!(is_truthy(&Value::List(vec![Value::Number(1.0)])));
    }

    #[test]
    fn is_truthy_other() {
        // Records, Ok, Err are always truthy
        assert!(is_truthy(&Value::Ok(Box::new(Value::Nil))));
        assert!(is_truthy(&Value::Err(Box::new(Value::Nil))));
    }

    #[test]
    fn interpret_literal_bool() {
        let source = "f>b;true";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Bool(true));
        let source2 = "f>b;false";
        assert_eq!(run_str(source2, Some("f"), vec![]), Value::Bool(false));
    }

    #[test]
    fn interpret_match_no_subject() {
        // ?{...} — match with no subject means subject is Nil
        let source = r#"f>n;?{_:42}"#;
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Number(42.0));
    }

    #[test]
    fn interpret_match_expr_with_bindings() {
        // Match expression that binds a value from Ok pattern
        let source = "f x:R n t>n;y=?x{~v:v;_:0};y";
        let result = run_str(
            source,
            Some("f"),
            vec![Value::Ok(Box::new(Value::Number(99.0)))],
        );
        assert_eq!(result, Value::Number(99.0));
    }

    #[test]
    fn interpret_match_expr_no_arm_matches() {
        // No arm matches in a match expression → returns Nil
        let source = r#"f>n;y=?1{2:99};y"#;
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Nil);
    }

    #[test]
    fn interpret_typedef_in_declarations() {
        // TypeDef should be silently skipped during registration
        let source = "type point{x:n;y:n}\nf>n;42";
        let result = run_str(source, None, vec![]);
        assert_eq!(result, Value::Number(42.0));
    }

    #[test]
    fn interpret_pattern_literal_no_match() {
        // A literal pattern that does not match falls through
        let source = r#"f x:n>n;?x{1:10;2:20;_:0}"#;
        let result = run_str(source, Some("f"), vec![Value::Number(5.0)]);
        assert_eq!(result, Value::Number(0.0));
    }

    #[test]
    fn interpret_foreach_on_non_list() {
        let err = run_str_err("f x:n>n;@i x{i}", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("foreach requires a list"));
    }

    #[test]
    fn interpret_tool_call() {
        let source = "tool fetch\"HTTP GET\" url:t>R _ t timeout:30\nf>R _ t;fetch \"http://example.com\"";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Ok(Box::new(Value::Nil)));
    }

    #[test]
    fn interpret_typedef_not_callable() {
        // TypeDef names are not registered as functions, so calling one
        // results in an "undefined function" error
        let source = "type point{x:n;y:n}\nf>n;point 1 2";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(
            err.contains("undefined function") || err.contains("type") || err.contains("not callable"),
            "unexpected error: {}", err
        );
    }

    #[test]
    fn interpret_greater_than() {
        let source = "f a:n b:n>b;>a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(5.0), Value::Number(3.0)]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_less_than() {
        let source = "f a:n b:n>b;<a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(3.0), Value::Number(5.0)]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_less_or_equal() {
        let source = "f a:n b:n>b;<=a b";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(3.0), Value::Number(3.0)]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_unsupported_binop() {
        let source = "f a:b b:b>b;-a b";
        let err = run_str_err(
            source,
            Some("f"),
            vec![Value::Bool(true), Value::Bool(false)],
        );
        assert!(
            err.contains("unsupported operation"),
            "unexpected error: {}", err
        );
    }

    #[test]
    fn interpret_foreach_early_return() {
        let source = "f xs:L n>n;@x xs{>=x 3{x}};0";
        let result = run_str(
            source,
            Some("f"),
            vec![Value::List(vec![
                Value::Number(1.0),
                Value::Number(5.0),
                Value::Number(2.0),
            ])],
        );
        assert_eq!(result, Value::Number(5.0));
    }

    #[test]
    fn interpret_match_not_last_stmt() {
        let source = "f x:n>n;?x{0:x;_:x};+x 1";
        let result = run_str(source, Some("f"), vec![Value::Number(5.0)]);
        assert_eq!(result, Value::Number(6.0));
    }

    #[test]
    fn interpret_match_expr_no_subject() {
        let source = r#"f>t;x=?{_:"always"};x"#;
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Text("always".to_string()));
    }

    #[test]
    fn interpret_pattern_ok_no_match() {
        let source = r#"f>t;x=^"err";?x{~v:v;_:"default"}"#;
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Text("default".to_string()));
    }

    #[test]
    fn interpret_match_stmt_no_arm_matches() {
        // Standalone match statement (Stmt::Match) where no arm matches → Ok(None) at L307
        // The match is not the last stmt; function continues to 0 after no match.
        let source = "f x:n>n;?x{1:99};0";
        let result = run_str(source, Some("f"), vec![Value::Number(5.0)]);
        assert_eq!(result, Value::Number(0.0));
    }

    #[test]
    fn interpret_match_arm_body_with_guard_return() {
        // Match arm body contains a guard that fires → BodyResult::Return propagates (L297)
        // When x=1: pattern 1 matches, arm body has guard >=x 0 which is true → returns 42
        // The match is not the last stmt (y=0 is first), so BodyResult::Return propagation matters
        // Note: arm body syntax uses `;` not braces: `1:>=x 0{42}` means guard in arm 1 body
        let source = "f x:n>n;y=0;?x{1:>=x 0{42};_:0}";
        let result = run_str(source, Some("f"), vec![Value::Number(1.0)]);
        assert_eq!(result, Value::Number(42.0));
    }

    // L239: call_function with Decl::TypeDef → "is a type, not callable"
    #[test]
    fn call_typedef_as_function() {
        let mut env = Env::new();
        // Manually insert a TypeDef into the env's functions map
        env.functions.insert("point".to_string(), Decl::TypeDef {
            name: "point".to_string(),
            fields: vec![],
            span: Span::UNKNOWN,
        });
        let result = call_function(&mut env, "point", vec![]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("is a type, not callable"), "got: {}", err);
    }

    // L242: call_function with Decl::Error → "failed to parse"
    #[test]
    fn call_error_decl_as_function() {
        let mut env = Env::new();
        // Manually insert a Decl::Error into the env's functions map
        env.functions.insert("broken".to_string(), Decl::Error {
            span: Span::UNKNOWN,
        });
        let result = call_function(&mut env, "broken", vec![]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("failed to parse"), "got: {}", err);
    }

    fn make_result_program(inner_body: Vec<Spanned<Stmt>>) -> Program {
        // Build: inner x:n>R n t;{inner_body}  outer x:n>R n t;d=inner! x;~d
        Program {
            declarations: vec![
                Decl::Function {
                    name: "inner".to_string(),
                    params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                    return_type: Type::Result(Box::new(Type::Number), Box::new(Type::Text)),
                    body: inner_body,
                    span: Span::UNKNOWN,
                },
                Decl::Function {
                    name: "outer".to_string(),
                    params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                    return_type: Type::Result(Box::new(Type::Number), Box::new(Type::Text)),
                    body: vec![
                        Spanned::unknown(Stmt::Let {
                            name: "d".to_string(),
                            value: Expr::Call {
                                function: "inner".to_string(),
                                args: vec![Expr::Ref("x".to_string())],
                                unwrap: true,
                            },
                        }),
                        Spanned::unknown(Stmt::Expr(Expr::Ok(Box::new(Expr::Ref("d".to_string()))))),
                    ],
                    span: Span::UNKNOWN,
                },
            ],
            source: None,
        }
    }

    #[test]
    fn unwrap_ok_path() {
        let prog = make_result_program(vec![
            Spanned::unknown(Stmt::Expr(Expr::Ok(Box::new(Expr::Ref("x".to_string()))))),
        ]);
        let result = run(&prog, Some("outer"), vec![Value::Number(42.0)]).unwrap();
        assert_eq!(result, Value::Ok(Box::new(Value::Number(42.0))));
    }

    #[test]
    fn unwrap_err_path() {
        let prog = make_result_program(vec![
            Spanned::unknown(Stmt::Expr(Expr::Err(Box::new(
                Expr::Literal(Literal::Text("fail".to_string()))
            )))),
        ]);
        let result = run(&prog, Some("outer"), vec![Value::Number(42.0)]).unwrap();
        assert_eq!(result, Value::Err(Box::new(Value::Text("fail".to_string()))));
    }

    #[test]
    fn unwrap_nested_propagation() {
        // c returns Err, b uses ! to call c, a uses ! to call b
        let unwrap_body = |callee: &str| vec![
            Spanned::unknown(Stmt::Let {
                name: "d".to_string(),
                value: Expr::Call {
                    function: callee.to_string(),
                    args: vec![Expr::Ref("x".to_string())],
                    unwrap: true,
                },
            }),
            Spanned::unknown(Stmt::Expr(Expr::Ok(Box::new(Expr::Ref("d".to_string()))))),
        ];
        let rnt = Type::Result(Box::new(Type::Number), Box::new(Type::Text));
        let prog = Program {
            declarations: vec![
                Decl::Function {
                    name: "c".to_string(),
                    params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                    return_type: rnt.clone(),
                    body: vec![Spanned::unknown(Stmt::Expr(
                        Expr::Err(Box::new(Expr::Literal(Literal::Text("deep".to_string()))))
                    ))],
                    span: Span::UNKNOWN,
                },
                Decl::Function {
                    name: "b".to_string(),
                    params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                    return_type: rnt.clone(),
                    body: unwrap_body("c"),
                    span: Span::UNKNOWN,
                },
                Decl::Function {
                    name: "a".to_string(),
                    params: vec![Param { name: "x".to_string(), ty: Type::Number }],
                    return_type: rnt,
                    body: unwrap_body("b"),
                    span: Span::UNKNOWN,
                },
            ],
            source: None,
        };
        let result = run(&prog, Some("a"), vec![Value::Number(1.0)]).unwrap();
        assert_eq!(result, Value::Err(Box::new(Value::Text("deep".to_string()))));
    }

    // ---- Braceless guards ----

    #[test]
    fn interpret_braceless_guard() {
        let source = r#"cls sp:n>t;>=sp 1000 "gold";>=sp 500 "silver";"bronze""#;
        assert_eq!(
            run_str(source, Some("cls"), vec![Value::Number(1500.0)]),
            Value::Text("gold".to_string())
        );
        assert_eq!(
            run_str(source, Some("cls"), vec![Value::Number(750.0)]),
            Value::Text("silver".to_string())
        );
        assert_eq!(
            run_str(source, Some("cls"), vec![Value::Number(100.0)]),
            Value::Text("bronze".to_string())
        );
    }

    #[test]
    fn interpret_braceless_guard_factorial() {
        let source = "fac n:n>n;<=n 1 1;r=fac -n 1;*n r";
        assert_eq!(
            run_str(source, Some("fac"), vec![Value::Number(5.0)]),
            Value::Number(120.0)
        );
    }

    #[test]
    fn interpret_braceless_guard_fibonacci() {
        let source = "fib n:n>n;<=n 1 n;a=fib -n 1;b=fib -n 2;+a b";
        assert_eq!(
            run_str(source, Some("fib"), vec![Value::Number(10.0)]),
            Value::Number(55.0)
        );
    }

    #[test]
    fn interpret_spl_basic() {
        let source = r#"f>L t;spl "a,b,c" ",""#;
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![
                Value::Text("a".to_string()),
                Value::Text("b".to_string()),
                Value::Text("c".to_string()),
            ])
        );
    }

    #[test]
    fn interpret_spl_empty() {
        let source = r#"f>L t;spl "" ",""#;
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Text("".to_string())])
        );
    }

    #[test]
    fn interpret_cat_basic() {
        let source = "f items:L t>t;cat items \",\"";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::List(vec![
                Value::Text("a".into()), Value::Text("b".into()), Value::Text("c".into()),
            ])]),
            Value::Text("a,b,c".into())
        );
    }

    #[test]
    fn interpret_cat_empty_list() {
        let source = "f items:L t>t;cat items \"-\"";
        assert_eq!(run_str(source, Some("f"), vec![Value::List(vec![])]), Value::Text("".into()));
    }

    #[test]
    fn interpret_has_list() {
        let source = "f xs:L n x:n>b;has xs x";
        assert_eq!(
            run_str(source, Some("f"), vec![Value::List(vec![Value::Number(1.0), Value::Number(2.0)]), Value::Number(2.0)]),
            Value::Bool(true)
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::List(vec![Value::Number(1.0)]), Value::Number(5.0)]),
            Value::Bool(false)
        );
    }

    #[test]
    fn interpret_has_text() {
        let source = r#"f s:t needle:t>b;has s needle"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("hello world".into()), Value::Text("world".into())]),
            Value::Bool(true)
        );
    }

    #[test]
    fn interpret_hd_list() {
        let source = "f>n;xs=[10, 20, 30];hd xs";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(10.0));
    }

    #[test]
    fn interpret_tl_list() {
        let source = "f>L n;xs=[10, 20, 30];tl xs";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(20.0), Value::Number(30.0)])
        );
    }

    #[test]
    fn interpret_hd_text() {
        let source = r#"f s:t>t;hd s"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("hello".into())]),
            Value::Text("h".into())
        );
    }

    #[test]
    fn interpret_tl_text() {
        let source = r#"f s:t>t;tl s"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("hello".into())]),
            Value::Text("ello".into())
        );
    }

    #[test]
    fn interpret_rev_list() {
        let source = "f>L n;rev [1, 2, 3]";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(3.0), Value::Number(2.0), Value::Number(1.0)])
        );
    }

    #[test]
    fn interpret_rev_text() {
        let source = r#"f>t;rev "abc""#;
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("cba".into()));
    }

    #[test]
    fn interpret_srt_numbers() {
        let source = "f>L n;srt [3, 1, 2]";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0)])
        );
    }

    #[test]
    fn interpret_srt_text_list() {
        let source = r#"f>L t;srt ["c", "a", "b"]"#;
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Text("a".into()), Value::Text("b".into()), Value::Text("c".into())])
        );
    }

    #[test]
    fn interpret_srt_text_string() {
        let source = r#"f>t;srt "cab""#;
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("abc".into()));
    }

    #[test]
    fn interpret_slc_list() {
        let source = "f>L n;slc [1, 2, 3, 4, 5] 1 3";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(2.0), Value::Number(3.0)])
        );
    }

    #[test]
    fn interpret_slc_text() {
        let source = r#"f>t;slc "hello" 1 4"#;
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("ell".into()));
    }

    #[test]
    fn interpret_slc_clamped() {
        let source = "f>L n;slc [1, 2, 3] 1 100";
        assert_eq!(
            run_str(source, Some("f"), vec![]),
            Value::List(vec![Value::Number(2.0), Value::Number(3.0)])
        );
    }

    #[test]
    fn interpret_ternary_true() {
        let source = r#"f x:n>t;=x 1{"yes"}{"no"}"#;
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(1.0)]), Value::Text("yes".into()));
    }

    #[test]
    fn interpret_ternary_false() {
        let source = r#"f x:n>t;=x 1{"yes"}{"no"}"#;
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(2.0)]), Value::Text("no".into()));
    }

    #[test]
    fn interpret_ternary_no_early_return() {
        let source = r#"f x:n>n;=x 0{10}{20};+x 1"#;
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(0.0)]), Value::Number(1.0));
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(5.0)]), Value::Number(6.0));
    }

    #[test]
    fn interpret_guard_still_returns_early() {
        let source = "f x:n>n;=x 0{99};+x 1";
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(0.0)]), Value::Number(99.0));
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(5.0)]), Value::Number(6.0));
    }

    #[test]
    fn interpret_ternary_negated() {
        let source = r#"f x:n>t;!=x 1{"not one"}{"one"}"#;
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(1.0)]), Value::Text("one".into()));
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(2.0)]), Value::Text("not one".into()));
    }

    #[test]
    fn interpret_ret_early_return() {
        let source = r#"f x:n>n;>x 0{ret x};0"#;
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(5.0)]), Value::Number(5.0));
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(-1.0)]), Value::Number(0.0));
    }

    #[test]
    fn interpret_pipe_simple() {
        // str x>>len desugars to len(str(x))
        let source = "f x:n>n;str x>>len";
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(42.0)]), Value::Number(2.0));
    }

    #[test]
    fn interpret_pipe_chain() {
        let source = "dbl x:n>n;*x 2\nadd1 x:n>n;+x 1\nf x:n>n;dbl x>>add1";
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(5.0)]), Value::Number(11.0));
    }

    #[test]
    fn interpret_pipe_with_extra_args() {
        // add x 1>>add 2 → add(2, add(x, 1))
        let source = "add a:n b:n>n;+a b\nf x:n>n;add x 1>>add 2";
        assert_eq!(run_str(source, Some("f"), vec![Value::Number(5.0)]), Value::Number(8.0));
    }

    #[test]
    fn interpret_ret_in_foreach() {
        let source = "f xs:L n>n;@x xs{>=x 10{ret x}};0";
        let list = Value::List(vec![Value::Number(1.0), Value::Number(15.0), Value::Number(3.0)]);
        assert_eq!(run_str(source, Some("f"), vec![list]), Value::Number(15.0));
    }

    #[test]
    fn interpret_while_basic() {
        // Sum 1..5 using while loop
        let source = "f>n;i=0;s=0;wh <i 5{i=+i 1;s=+s i};s";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(15.0));
    }

    #[test]
    fn interpret_while_zero_iterations() {
        let source = "f>n;wh false{42};0";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(0.0));
    }

    #[test]
    fn interpret_nil_coalesce_nil() {
        // Function returns nil when guard doesn't fire, ?? falls back
        let source = "mk x:n>n;>=x 1{x}\nf>n;x=mk 0;x??42";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(42.0));
    }

    #[test]
    fn interpret_nil_coalesce_non_nil() {
        // Non-nil value passes through
        let source = "f>n;x=10;x??42";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(10.0));
    }

    #[test]
    fn interpret_nil_coalesce_chain() {
        let source = "mk x:n>n;>=x 1{x}\nf>n;a=mk 0;b=mk 0;a??b??99";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(99.0));
    }

    #[test]
    fn interpret_safe_field_on_nil() {
        // Safe field access on nil returns nil
        let source = "mk x:n>n;>=x 1{x}\nf>n;v=mk 0;v.?name??99";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(99.0));
    }

    #[test]
    fn interpret_safe_field_on_value() {
        // Safe field access on record returns field value
        let source = "f>n;p=pt x:5;p.?x\ntype pt{x:n}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(5.0));
    }

    #[test]
    fn interpret_safe_field_chained() {
        // Chained safe navigation: nil propagates through chain
        let source = "mk x:n>n;>=x 1{x}\nf>n;v=mk 0;v.?a.?b??77";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(77.0));
    }

    #[test]
    fn interpret_while_with_ret() {
        // Early return from while loop
        let source = "f>n;i=0;wh true{i=+i 1;>=i 3{ret i}};0";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_while_brk() {
        // brk exits while loop
        let source = "f>n;i=0;wh true{i=+i 1;>=i 3{brk}};i";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_while_brk_value() {
        // brk with value — value is discarded, loop exits
        let source = "f>n;i=0;wh true{i=+i 1;>=i 3{brk 99}};i";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_while_cnt() {
        // cnt skips rest of body, continues loop
        let source = "f>n;i=0;s=0;wh <i 5{i=+i 1;>=i 3{cnt};s=+s i};s";
        // i goes 1,2,3,4,5 — cnt when i>=3 so s += i only for i=1,2 → s=3
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_foreach_brk() {
        // brk with value exits foreach, foreach returns the break value
        let source = "f>n;@x [1,2,3,4,5]{>=x 3{brk x};x}";
        // x=1 → value 1, x=2 → value 2, x=3 → brk 3
        // Break value (3) becomes last, foreach returns 3
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_foreach_cnt() {
        // cnt in foreach skips rest of body for that iteration
        // Body value: x*2 — but when x>=3, cnt skips it
        // Last non-skipped value = 2*2 = 4 (from x=2)... but then x=3,4,5 continue with no value
        // Actually: last = Nil from unfinished iterations? No — continue doesn't update last.
        // x=1 → value 2, x=2 → value 4, x=3 → cnt (last stays 4), x=4 → cnt, x=5 → cnt
        let source = "f>n;@x [1,2,3,4,5]{>=x 3{cnt};*x 2}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(4.0));
    }

    #[test]
    fn interpret_rnd_no_args() {
        let source = "f>n;rnd";
        let result = run_str(source, Some("f"), vec![]);
        let Value::Number(n) = result else { panic!("expected Number") };
        assert!(n >= 0.0 && n < 1.0, "rnd should be in [0,1), got {n}");
    }

    #[test]
    fn interpret_rnd_two_args() {
        let source = "f>n;rnd 1 10";
        let result = run_str(source, Some("f"), vec![]);
        let Value::Number(n) = result else { panic!("expected Number") };
        assert!(n >= 1.0 && n <= 10.0, "rnd 1 10 should be in [1,10], got {n}");
        assert_eq!(n, n.floor(), "rnd with two args should return integer");
    }

    #[test]
    fn interpret_rnd_same_bounds() {
        let source = "f>n;rnd 5 5";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(5.0));
    }

    #[test]
    fn interpret_now() {
        let source = "f>n;now";
        let result = run_str(source, Some("f"), vec![]);
        let Value::Number(n) = result else { panic!("expected Number") };
        assert!(n > 1_000_000_000.0, "now should be a reasonable unix timestamp, got {n}");
    }

    // ── env builtin tests ─────────────────────────────────────────────

    #[test]
    fn interpret_env_existing_var() {
        let _guard = ENV_TEST_MUTEX.lock().unwrap();
        unsafe { std::env::set_var("ILO_TEST_VAR", "hello"); }
        let source = r#"f k:t>R t t;env k"#;
        let result = run_str(source, Some("f"), vec![Value::Text("ILO_TEST_VAR".into())]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("hello".into()))));
        unsafe { std::env::remove_var("ILO_TEST_VAR"); }
    }

    #[test]
    fn interpret_env_missing_var() {
        let _guard = ENV_TEST_MUTEX.lock().unwrap();
        let source = r#"f k:t>R t t;env k"#;
        let result = run_str(source, Some("f"), vec![Value::Text("ILO_NONEXISTENT_12345".into())]);
        let Value::Err(inner) = result else { panic!("expected Err") };
        let Value::Text(s) = *inner else { panic!("expected Text") };
        assert!(s.contains("not set"), "got: {s}");
    }

    #[test]
    fn interpret_env_unwrap() {
        let _guard = ENV_TEST_MUTEX.lock().unwrap();
        unsafe { std::env::set_var("ILO_TEST_UNWRAP", "world"); }
        let source = r#"f k:t>R t t;~(env! k)"#;
        let result = run_str(source, Some("f"), vec![Value::Text("ILO_TEST_UNWRAP".into())]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("world".into()))));
        unsafe { std::env::remove_var("ILO_TEST_UNWRAP"); }
    }

    // ── Range iteration tests ───────────────────────────────────────────

    #[test]
    fn interpret_range_basic() {
        // @i 0..3{i} → iterates 0, 1, 2; last value is 2
        let source = "f>n;@i 0..3{i}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(2.0));
    }

    #[test]
    fn interpret_range_accumulate() {
        // Last body value: +0 i where i goes 0,1,2 → last is +0 2 = 2
        // s is in outer scope, s=+s i creates s in inner scope each time
        // So just check the body expression result
        let source = "f>n;@i 0..3{+i 1}";
        // last body val: +2 1 = 3
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_range_empty() {
        // start >= end → never executes, loop returns Nil
        let source = "f>n;@i 5..3{99}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Nil);
    }

    #[test]
    fn interpret_range_dynamic_end() {
        // Dynamic end from parameter; body returns i
        let source = "f n:n>n;@i 0..n{i}";
        // n=4, iterates 0,1,2,3 → last body value is 3
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Number(4.0)]),
            Value::Number(3.0)
        );
    }

    #[test]
    fn interpret_range_brk() {
        // Break at i >= 3 with value
        let source = "f>n;@i 0..10{>=i 3{brk i};i}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(3.0));
    }

    #[test]
    fn interpret_range_cnt() {
        // cnt skips rest of body. Body is: =i 2{cnt};*i 10
        // i=0: *0 10 = 0, i=1: *1 10 = 10, i=2: cnt (skip), i=3: *3 10 = 30, i=4: *4 10 = 40
        // last body value = 40
        let source = "f>n;@i 0..5{=i 2{cnt};*i 10}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(40.0));
    }

    #[test]
    fn interpret_range_as_index() {
        // Use range variable to index a list: xs.i doesn't work with dynamic i
        // Index access is only for literals. So just test basic indexing pattern.
        let source = "f>n;@i 0..3{*i i}";
        // i=0: 0, i=1: 1, i=2: 4 → last = 4
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(4.0));
    }

    // ---- Builtin error-path coverage tests ----

    #[test]
    fn err_spl_non_text_first() {
        let err = run_str_err("f x:n y:t>L t;spl x y", Some("f"), vec![Value::Number(1.0), Value::Text("a".into())]);
        assert!(err.contains("spl requires two text args"), "got: {err}");
    }

    #[test]
    fn err_spl_non_text_second() {
        let err = run_str_err("f x:t y:n>L t;spl x y", Some("f"), vec![Value::Text("a-b".into()), Value::Number(1.0)]);
        assert!(err.contains("spl requires two text args"), "got: {err}");
    }

    #[test]
    fn err_cat_non_text_items() {
        let err = run_str_err("f>t;cat [1,2,3] \",\"", Some("f"), vec![]);
        assert!(err.contains("cat: list items must be text"), "got: {err}");
    }

    #[test]
    fn err_cat_wrong_arg_types() {
        let err = run_str_err("f x:n y:n>t;cat x y", Some("f"), vec![Value::Number(1.0), Value::Number(2.0)]);
        assert!(err.contains("cat requires a list and text separator"), "got: {err}");
    }

    #[test]
    fn err_has_text_non_text_needle() {
        let err = run_str_err("f x:t y:n>b;has x y", Some("f"), vec![Value::Text("hello".into()), Value::Number(1.0)]);
        assert!(err.contains("text search requires text needle"), "got: {err}");
    }

    #[test]
    fn err_has_wrong_first_arg() {
        let err = run_str_err("f x:n y:n>b;has x y", Some("f"), vec![Value::Number(1.0), Value::Number(2.0)]);
        assert!(err.contains("has requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_hd_empty_list() {
        let err = run_str_err("f>n;hd []", Some("f"), vec![]);
        assert!(err.contains("hd: empty list"), "got: {err}");
    }

    #[test]
    fn err_hd_empty_text() {
        let err = run_str_err("f>t;hd \"\"", Some("f"), vec![]);
        assert!(err.contains("hd: empty text"), "got: {err}");
    }

    #[test]
    fn err_hd_wrong_type() {
        let err = run_str_err("f x:n>n;hd x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("hd requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_tl_empty_list() {
        let err = run_str_err("f>L n;tl []", Some("f"), vec![]);
        assert!(err.contains("tl: empty list"), "got: {err}");
    }

    #[test]
    fn err_tl_empty_text() {
        let err = run_str_err("f>t;tl \"\"", Some("f"), vec![]);
        assert!(err.contains("tl: empty text"), "got: {err}");
    }

    #[test]
    fn err_tl_wrong_type() {
        let err = run_str_err("f x:n>n;tl x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("tl requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_rev_wrong_type() {
        let err = run_str_err("f x:n>n;rev x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("rev requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_srt_mixed_types() {
        let err = run_str_err("f>L n;srt [1,\"a\"]", Some("f"), vec![]);
        assert!(err.contains("srt: list must contain all numbers or all text"), "got: {err}");
    }

    #[test]
    fn err_srt_wrong_type() {
        let err = run_str_err("f x:n>n;srt x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("srt requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_slc_wrong_first_arg() {
        let err = run_str_err("f x:n>n;slc x 0 1", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("slc requires a list or text"), "got: {err}");
    }

    #[test]
    fn err_slc_non_number_start() {
        let err = run_str_err("f x:t y:t>t;slc x y 1", Some("f"), vec![Value::Text("hi".into()), Value::Text("a".into())]);
        assert!(err.contains("slc: start index must be a number"), "got: {err}");
    }

    #[test]
    fn err_slc_non_number_end() {
        let err = run_str_err("f x:t y:t>t;slc x 0 y", Some("f"), vec![Value::Text("hi".into()), Value::Text("a".into())]);
        assert!(err.contains("slc: end index must be a number"), "got: {err}");
    }

    #[test]
    fn err_rnd_lower_gt_upper() {
        let err = run_str_err("f>n;rnd 10 1", Some("f"), vec![]);
        assert!(err.contains("rnd: lower bound"), "got: {err}");
        assert!(err.contains("upper bound"), "got: {err}");
    }

    #[test]
    fn err_rnd_wrong_arg_types() {
        let err = run_str_err("f x:t y:t>n;rnd x y", Some("f"), vec![Value::Text("a".into()), Value::Text("b".into())]);
        assert!(err.contains("rnd requires two numbers"), "got: {err}");
    }

    #[test]
    fn err_get_non_text_arg() {
        let err = run_str_err("f x:n>R t t;get x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("get requires text"), "got: {err}");
    }

    #[test]
    fn ok_srt_empty_list() {
        let source = "f>L n;srt []";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::List(vec![]));
    }

    // ---- Destructuring bind tests ----

    #[test]
    fn destructure_basic() {
        let source = "type pt{x:n;y:n} f>n;p=pt x:3 y:4;{x;y}=p;+x y";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(7.0));
    }

    #[test]
    fn destructure_single_field() {
        let source = "type pt{x:n;y:n} f>n;p=pt x:10 y:20;{x}=p;x";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(10.0));
    }

    #[test]
    fn destructure_with_text_fields() {
        let source = "type usr{name:t;email:t} f>t;u=usr name:\"alice\" email:\"a@b\";{name;email}=u;name";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Text("alice".to_string()));
    }

    #[test]
    fn destructure_in_loop() {
        // Destructure inside a foreach — last iteration value is returned
        let source = "type pt{x:n;y:n} f>n;ps=[pt x:1 y:2,pt x:3 y:4];@p ps{{x;y}=p;+x y}";
        assert_eq!(run_str(source, Some("f"), vec![]), Value::Number(7.0));
    }

    #[test]
    fn destructure_non_record_error() {
        let err = run_str_err("f x:n>n;{a}=x;a", Some("f"), vec![Value::Number(5.0)]);
        assert!(err.contains("destructure requires a record"), "got: {}", err);
    }

    #[test]
    fn destructure_missing_field_error() {
        let source = "type pt{x:n;y:n} f>n;p=pt x:3 y:4;{x;z}=p;x";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(err.contains("no field 'z'"), "got: {}", err);
    }

    // ── JSON builtins ───────────────────────────────────────────────────

    #[test]
    fn interp_jp_object() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"name":"alice"}"#.to_string()),
            Value::Text("name".to_string()),
        ]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("alice".to_string()))));
    }

    #[test]
    fn interp_jp_nested() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"user":{"name":"bob"}}"#.to_string()),
            Value::Text("user.name".to_string()),
        ]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("bob".to_string()))));
    }

    #[test]
    fn interp_jp_array_index() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"items":[10,20,30]}"#.to_string()),
            Value::Text("items.1".to_string()),
        ]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("20".to_string()))));
    }

    #[test]
    fn interp_jp_missing_key() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"a":1}"#.to_string()),
            Value::Text("b".to_string()),
        ]);
        let Value::Err(e) = result else { panic!("expected Err") };
        assert!(e.to_string().contains("key not found"), "got: {}", e);
    }

    #[test]
    fn interp_jp_invalid_json() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text("not json".to_string()),
            Value::Text("x".to_string()),
        ]);
        assert!(matches!(result, Value::Err(_)));
    }

    #[test]
    fn interp_jp_unwrap() {
        let source = r#"f j:t p:t>t;jpth! j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"x":"hello"}"#.to_string()),
            Value::Text("x".to_string()),
        ]);
        assert_eq!(result, Value::Text("hello".to_string()));
    }

    #[test]
    fn interp_jd_number() {
        let source = "f x:n>t;jdmp x";
        let result = run_str(source, Some("f"), vec![Value::Number(42.0)]);
        assert_eq!(result, Value::Text("42".to_string()));
    }

    #[test]
    fn interp_jd_text() {
        let source = r#"f x:t>t;jdmp x"#;
        let result = run_str(source, Some("f"), vec![Value::Text("hello".to_string())]);
        assert_eq!(result, Value::Text(r#""hello""#.to_string()));
    }

    #[test]
    fn interp_jd_list() {
        let source = "f>t;xs=[1, 2, 3];jdmp xs";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::Text("[1,2,3]".to_string()));
    }

    #[test]
    fn interp_jd_record() {
        let source = "type pt{x:n;y:n} f>t;p=pt x:1 y:2;jdmp p";
        let result = run_str(source, Some("f"), vec![]);
        let Value::Text(ref s) = result else { panic!("expected text") };
        let text = s.clone();
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(parsed["x"], 1);
        assert_eq!(parsed["y"], 2);
    }

    #[test]
    fn interp_jparse_object() {
        let source = r#"f j:t>R t t;jpar j"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"{"a":1,"b":"two"}"#.to_string()),
        ]);
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        let Value::Record { type_name, fields } = *inner else { panic!("expected record") };
        assert_eq!(type_name, "json");
        assert_eq!(fields.get("a"), Some(&Value::Number(1.0)));
        assert_eq!(fields.get("b"), Some(&Value::Text("two".to_string())));
    }

    #[test]
    fn interp_jparse_array() {
        let source = r#"f j:t>R t t;jpar j"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text("[1,2,3]".to_string()),
        ]);
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        assert_eq!(*inner, Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0)]));
    }

    #[test]
    fn interp_jparse_scalar() {
        let source = r#"f j:t>R t t;jpar j"#;
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("42".to_string())]),
            Value::Ok(Box::new(Value::Number(42.0)))
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("true".to_string())]),
            Value::Ok(Box::new(Value::Bool(true)))
        );
        assert_eq!(
            run_str(source, Some("f"), vec![Value::Text("null".to_string())]),
            Value::Ok(Box::new(Value::Nil))
        );
    }

    #[test]
    fn interp_jparse_invalid() {
        let source = r#"f j:t>R t t;jpar j"#;
        let result = run_str(source, Some("f"), vec![Value::Text("not json".to_string())]);
        assert!(matches!(result, Value::Err(_)));
    }

    #[test]
    fn interp_jparse_unwrap() {
        let source = r#"f j:t>t;jpar! j"#;
        let result = run_str(source, Some("f"), vec![Value::Text(r#"{"x":1}"#.to_string())]);
        let Value::Record { type_name, fields } = result else { panic!("expected record") };
        assert_eq!(type_name, "json");
        assert_eq!(fields.get("x"), Some(&Value::Number(1.0)));
    }

    #[test]
    fn interp_jparse_then_field_access() {
        let source = r#"f j:t>n;r=jpar! j;r.x"#;
        let result = run_str(source, Some("f"), vec![Value::Text(r#"{"x":42}"#.to_string())]);
        assert_eq!(result, Value::Number(42.0));
    }

    #[test]
    fn interp_map_squares() {
        // map sq over [1,2,3,4,5] → [1,4,9,16,25]
        let source = "sq x:n>n;*x x main xs:L n>L n;map sq xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![1.0, 2.0, 3.0, 4.0, 5.0].into_iter().map(Value::Number).collect())
        ]);
        assert_eq!(result, Value::List(vec![1.0, 4.0, 9.0, 16.0, 25.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_flt_positive() {
        // flt pos over [-3,-1,0,2,4] → [2,4]
        let source = "pos x:n>b;>x 0 main xs:L n>L n;flt pos xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![-3.0, -1.0, 0.0, 2.0, 4.0].into_iter().map(Value::Number).collect())
        ]);
        assert_eq!(result, Value::List(vec![2.0, 4.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_fld_sum() {
        // fld add over [1..5] with init 0 → 15
        let source = "add a:n b:n>n;+a b main xs:L n>n;fld add xs 0";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![1.0, 2.0, 3.0, 4.0, 5.0].into_iter().map(Value::Number).collect())
        ]);
        assert_eq!(result, Value::Number(15.0));
    }

    #[test]
    fn interp_grp_by_string_key() {
        // group numbers into "big" and "small" based on > 5
        let source = r#"cl x:n>t;>x 5{"big"}{"small"} main xs:L n>M t L n;grp cl xs"#;
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![1.0, 8.0, 3.0, 9.0, 2.0].into_iter().map(Value::Number).collect())
        ]);
        let Value::Map(m) = result else { panic!("expected Map") };
        assert_eq!(m.get("small").unwrap(), &Value::List(vec![1.0, 3.0, 2.0].into_iter().map(Value::Number).collect()));
        assert_eq!(m.get("big").unwrap(), &Value::List(vec![8.0, 9.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_grp_by_numeric_key() {
        // group by str(x) — each number becomes its own group
        let source = "key x:n>t;str x main xs:L n>M t L n;grp key xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![1.0, 2.0, 1.0, 3.0, 2.0].into_iter().map(Value::Number).collect())
        ]);
        let Value::Map(m) = result else { panic!("expected Map") };
        assert_eq!(m.get("1").unwrap(), &Value::List(vec![1.0, 1.0].into_iter().map(Value::Number).collect()));
        assert_eq!(m.get("2").unwrap(), &Value::List(vec![2.0, 2.0].into_iter().map(Value::Number).collect()));
        assert_eq!(m.get("3").unwrap(), &Value::List(vec![3.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_grp_empty_list() {
        let source = "id x:n>t;str x main xs:L n>M t L n;grp id xs";
        let result = run_str(source, Some("main"), vec![Value::List(vec![])]);
        assert_eq!(result, Value::Map(std::collections::HashMap::new()));
    }

    #[test]
    fn interp_grp_wrong_fn_arg() {
        let err = run_str_err("f>t;grp 42 [1, 2, 3]", Some("f"), vec![]);
        assert!(err.contains("grp"), "got: {err}");
    }

    #[test]
    fn interp_grp_wrong_list_arg() {
        let err = run_str_err("id x:n>n;x f>t;grp id 42", Some("f"), vec![]);
        assert!(err.contains("grp"), "got: {err}");
    }

    #[test]
    fn interp_sum_basic() {
        let source = "f xs:L n>n;sum xs";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![1.0, 2.0, 3.0, 4.0, 5.0].into_iter().map(Value::Number).collect())
        ]);
        assert_eq!(result, Value::Number(15.0));
    }

    #[test]
    fn interp_sum_empty() {
        let source = "f xs:L n>n;sum xs";
        let result = run_str(source, Some("f"), vec![Value::List(vec![])]);
        assert_eq!(result, Value::Number(0.0));
    }

    #[test]
    fn interp_sum_wrong_arg() {
        let err = run_str_err("f>n;sum 42", Some("f"), vec![]);
        assert!(err.contains("sum"), "got: {err}");
    }

    #[test]
    fn interp_sum_non_numeric_element() {
        let err = run_str_err(r#"f>n;sum ["a", "b"]"#, Some("f"), vec![]);
        assert!(err.contains("sum"), "got: {err}");
    }

    #[test]
    fn interp_avg_basic() {
        let source = "f xs:L n>n;avg xs";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![2.0, 4.0, 6.0].into_iter().map(Value::Number).collect())
        ]);
        assert_eq!(result, Value::Number(4.0));
    }

    #[test]
    fn interp_avg_empty_error() {
        let err = run_str_err("f>n;avg []", Some("f"), vec![]);
        assert!(err.contains("avg"), "got: {err}");
    }

    #[test]
    fn interp_avg_wrong_arg() {
        let err = run_str_err("f>n;avg 42", Some("f"), vec![]);
        assert!(err.contains("avg"), "got: {err}");
    }

    #[test]
    fn interp_wr_csv_output() {
        let dir = std::env::temp_dir();
        let path = dir.join("ilo_test_wr_csv.csv");
        let path_str = path.to_str().unwrap();
        let source = format!(
            r#"f>R t t;wr "{}" [["name", "age"], ["alice", 30], ["bob", 25]] "csv""#,
            path_str.replace('\\', "\\\\")
        );
        let result = run_str(&source, Some("f"), vec![]);
        assert!(matches!(result, Value::Ok(_)));
        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "name,age\nalice,30\nbob,25\n");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn interp_wr_csv_quoted_fields() {
        let dir = std::env::temp_dir();
        let path = dir.join("ilo_test_wr_csv_quoted.csv");
        let path_str = path.to_str().unwrap();
        let source = format!(
            r#"f>R t t;wr "{}" [["a,b", "c\"d"]] "csv""#,
            path_str.replace('\\', "\\\\")
        );
        let result = run_str(&source, Some("f"), vec![]);
        assert!(matches!(result, Value::Ok(_)));
        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, "\"a,b\",\"c\"\"d\"\n");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn interp_wr_json_output() {
        let dir = std::env::temp_dir();
        let path = dir.join("ilo_test_wr_json.json");
        let path_str = path.to_str().unwrap();
        let source = format!(
            r#"f>R t t;wr "{}" [1, 2, 3] "json""#,
            path_str.replace('\\', "\\\\")
        );
        let result = run_str(&source, Some("f"), vec![]);
        assert!(matches!(result, Value::Ok(_)));
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed, serde_json::json!([1.0, 2.0, 3.0]));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn interp_wr_unknown_format() {
        let err = run_str_err(r#"f>R t t;wr "/tmp/x" "data" "xml""#, Some("f"), vec![]);
        assert!(err.contains("unknown format"), "got: {err}");
    }

    #[test]
    fn interp_rgx_find_all() {
        // find all numbers in a string
        let source = r#"f s:t>L t;rgx "\d+" s"#;
        let result = run_str(source, Some("f"), vec![Value::Text("abc 123 def 456".into())]);
        assert_eq!(result, Value::List(vec![
            Value::Text("123".into()),
            Value::Text("456".into()),
        ]));
    }

    #[test]
    fn interp_rgx_capture_groups() {
        // extract key=value pairs
        let source = r#"f s:t>L t;rgx "(\w+)=(\w+)" s"#;
        let result = run_str(source, Some("f"), vec![Value::Text("name=alice age=30".into())]);
        // Returns first match's groups
        assert_eq!(result, Value::List(vec![
            Value::Text("name".into()),
            Value::Text("alice".into()),
        ]));
    }

    #[test]
    fn interp_rgx_no_match() {
        let source = r#"f s:t>L t;rgx "\d+" s"#;
        let result = run_str(source, Some("f"), vec![Value::Text("no numbers here".into())]);
        assert_eq!(result, Value::List(vec![]));
    }

    #[test]
    fn interp_rgx_invalid_pattern() {
        let err = run_str_err(r#"f>L t;rgx "[invalid" "test""#, Some("f"), vec![]);
        assert!(err.contains("rgx"), "got: {err}");
    }

    #[test]
    fn interp_rgx_wrong_arg_types() {
        let err = run_str_err(r#"f>L t;rgx 42 "test""#, Some("f"), vec![]);
        assert!(err.contains("rgx"), "got: {err}");
    }

    #[test]
    fn interp_flat_nested() {
        // flat [[1,2],[3],[4,5]] → [1,2,3,4,5]
        let source = "f>L n;flat [[1, 2], [3], [4, 5]]";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::List(vec![1.0, 2.0, 3.0, 4.0, 5.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_flat_mixed() {
        // flat [[1, 2], 3] — non-list elements pass through
        let source = "f>L n;flat [[1, 2], 3]";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::List(vec![1.0, 2.0, 3.0].into_iter().map(Value::Number).collect()));
    }

    #[test]
    fn interp_flat_empty() {
        let source = "f>L n;flat []";
        let result = run_str(source, Some("f"), vec![]);
        assert_eq!(result, Value::List(vec![]));
    }

    #[test]
    fn interp_flat_wrong_arg() {
        let err = run_str_err("f>L n;flat 42", Some("f"), vec![]);
        assert!(err.contains("flat"), "got: {err}");
    }

    #[test]
    fn interp_user_hof_fn_type() {
        // User-defined HOF: apl f:F n n x:n>n;f x
        let source = "sq x:n>n;*x x apl f:F n n x:n>n;f x";
        let result = run_str(source, Some("apl"), vec![
            Value::FnRef("sq".to_string()),
            Value::Number(7.0),
        ]);
        assert_eq!(result, Value::Number(49.0));
    }

    #[test]
    fn interp_fn_ref_via_ref_expr() {
        // Using a function name as a value (Expr::Ref resolves to FnRef)
        let source = "dbl x:n>n;*x 2 main>n;f=dbl;f 10";
        let result = run_str(source, Some("main"), vec![]);
        assert_eq!(result, Value::Number(20.0));
    }

    // --- trm ---

    #[test]
    fn interpret_trm_basic() {
        let result = run_str("f s:t>t;trm s", Some("f"), vec![Value::Text("  hello  ".into())]);
        assert_eq!(result, Value::Text("hello".into()));
    }

    #[test]
    fn interpret_trm_no_whitespace() {
        let result = run_str("f s:t>t;trm s", Some("f"), vec![Value::Text("hi".into())]);
        assert_eq!(result, Value::Text("hi".into()));
    }

    #[test]
    fn interpret_trm_only_whitespace() {
        let result = run_str("f s:t>t;trm s", Some("f"), vec![Value::Text("   ".into())]);
        assert_eq!(result, Value::Text("".into()));
    }

    #[test]
    fn err_trm_wrong_type() {
        let err = run_str_err("f x:n>t;trm x", Some("f"), vec![Value::Number(1.0)]);
        assert!(err.contains("trm requires text"), "expected trm type error, got: {err}");
    }

    // --- unq ---

    #[test]
    fn interpret_unq_list_numbers() {
        let result = run_str("f xs:L n>L n;unq xs", Some("f"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(1.0), Value::Number(3.0), Value::Number(2.0)]),
        ]);
        assert_eq!(result, Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0)]));
    }

    #[test]
    fn interpret_unq_list_strings() {
        let result = run_str("f xs:L t>L t;unq xs", Some("f"), vec![
            Value::List(vec![Value::Text("a".into()), Value::Text("b".into()), Value::Text("a".into())]),
        ]);
        assert_eq!(result, Value::List(vec![Value::Text("a".into()), Value::Text("b".into())]));
    }

    #[test]
    fn interpret_unq_text_chars() {
        let result = run_str("f s:t>t;unq s", Some("f"), vec![Value::Text("aabbc".into())]);
        assert_eq!(result, Value::Text("abc".into()));
    }

    #[test]
    fn interpret_unq_empty_list() {
        let result = run_str("f xs:L n>L n;unq xs", Some("f"), vec![Value::List(vec![])]);
        assert_eq!(result, Value::List(vec![]));
    }

    #[test]
    fn interpret_unq_preserves_order() {
        let result = run_str("f xs:L n>L n;unq xs", Some("f"), vec![
            Value::List(vec![Value::Number(3.0), Value::Number(1.0), Value::Number(2.0), Value::Number(1.0), Value::Number(3.0)]),
        ]);
        assert_eq!(result, Value::List(vec![Value::Number(3.0), Value::Number(1.0), Value::Number(2.0)]));
    }

    // --- fmt ---

    #[test]
    fn interpret_fmt_basic() {
        let result = run_str(
            r#"f a:t b:t>t;fmt "{} + {}" a b"#,
            Some("f"),
            vec![Value::Text("1".into()), Value::Text("2".into())],
        );
        assert_eq!(result, Value::Text("1 + 2".into()));
    }

    #[test]
    fn interpret_fmt_template_only() {
        let result = run_str(r#"f>t;fmt "hello""#, Some("f"), vec![]);
        assert_eq!(result, Value::Text("hello".into()));
    }

    #[test]
    fn interpret_fmt_fewer_args_than_slots() {
        let result = run_str(
            r#"f a:t>t;fmt "{} and {}" a"#,
            Some("f"),
            vec![Value::Text("x".into())],
        );
        assert_eq!(result, Value::Text("x and {}".into()));
    }

    #[test]
    fn interpret_fmt_number_arg() {
        let result = run_str(
            r#"f n:n>t;fmt "value: {}" n"#,
            Some("f"),
            vec![Value::Number(42.0)],
        );
        assert_eq!(result, Value::Text("value: 42".into()));
    }

    // --- srt fn xs ---

    #[test]
    fn interpret_srt_fn_by_length() {
        let source = "ln s:t>n;len s main xs:L t>L t;srt ln xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![
                Value::Text("banana".into()),
                Value::Text("a".into()),
                Value::Text("cc".into()),
            ]),
        ]);
        assert_eq!(result, Value::List(vec![
            Value::Text("a".into()),
            Value::Text("cc".into()),
            Value::Text("banana".into()),
        ]));
    }

    #[test]
    fn interpret_srt_fn_numeric_key() {
        let source = "neg x:n>n;-x main xs:L n>L n;srt neg xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(3.0), Value::Number(2.0)]),
        ]);
        // sort by negative: highest first
        assert_eq!(result, Value::List(vec![Value::Number(3.0), Value::Number(2.0), Value::Number(1.0)]));
    }

    // --- prnt ---

    #[test]
    fn interpret_prnt_returns_value() {
        let result = run_str("f x:n>n;prnt x", Some("f"), vec![Value::Number(7.0)]);
        assert_eq!(result, Value::Number(7.0));
    }

    #[test]
    fn interpret_prnt_text_passthrough() {
        let result = run_str("f s:t>t;prnt s", Some("f"), vec![Value::Text("hi".into())]);
        assert_eq!(result, Value::Text("hi".into()));
    }

    // --- rdb ---

    #[test]
    fn interpret_rdb_csv() {
        let result = run_str(
            r#"f s:t>t;rdb s "csv""#,
            Some("f"),
            vec![Value::Text("a,b\n1,2".into())],
        );
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        let Value::List(rows) = *inner else { panic!("expected list") };
        assert_eq!(rows.len(), 2);
        assert!(matches!(&rows[0], Value::List(_)));
    }

    #[test]
    fn interpret_rdb_json() {
        let result = run_str(
            r#"f s:t>t;rdb s "json""#,
            Some("f"),
            vec![Value::Text(r#"{"x":1}"#.into())],
        );
        assert!(matches!(result, Value::Ok(_)), "expected Ok, got {:?}", result);
    }

    #[test]
    fn interpret_rdb_invalid_json_is_err() {
        let result = run_str(
            r#"f s:t>t;rdb s "json""#,
            Some("f"),
            vec![Value::Text("not json".into())],
        );
        assert!(matches!(result, Value::Err(_)), "expected Err, got {:?}", result);
    }

    #[test]
    fn interpret_rdb_raw_passthrough() {
        let result = run_str(
            r#"f s:t>t;rdb s "raw""#,
            Some("f"),
            vec![Value::Text("hello".into())],
        );
        assert_eq!(result, Value::Ok(Box::new(Value::Text("hello".into()))));
    }

    // --- rd (error paths not needing a real file) ---

    #[test]
    fn interpret_rd_file_not_found() {
        let result = run_str(
            "f p:t>t;rd p",
            Some("f"),
            vec![Value::Text("/nonexistent/ilo_test_file.txt".into())],
        );
        assert!(matches!(result, Value::Err(_)), "expected Err, got {:?}", result);
    }

    // --- TypeIs pattern ---

    #[test]
    fn interpret_type_is_number_match() {
        // n v: pattern matches a number value
        let result = run_str(
            r#"f x:n>t;?x{n v:"num";_:"other"}"#,
            Some("f"),
            vec![Value::Number(42.0)],
        );
        assert_eq!(result, Value::Text("num".into()));
    }

    #[test]
    fn interpret_type_is_text_match() {
        // t v: pattern matches a text value
        let result = run_str(
            r#"f x:t>t;?x{t v:v;_:"other"}"#,
            Some("f"),
            vec![Value::Text("hello".into())],
        );
        assert_eq!(result, Value::Text("hello".into()));
    }

    #[test]
    fn interpret_type_is_bool_match() {
        // b v: pattern matches a bool value
        let result = run_str(
            r#"f x:b>t;?x{b v:"bool";_:"other"}"#,
            Some("f"),
            vec![Value::Bool(true)],
        );
        assert_eq!(result, Value::Text("bool".into()));
    }

    #[test]
    fn interpret_type_is_no_match_falls_through() {
        // TypeIs with wrong type → falls through to wildcard
        let result = run_str(
            r#"f x:n>t;?x{t v:"text";_:"other"}"#,
            Some("f"),
            vec![Value::Number(1.0)],
        );
        assert_eq!(result, Value::Text("other".into()));
    }

    #[test]
    fn interpret_type_is_wildcard_binding() {
        // TypeIs with _ binding (no binding created)
        let result = run_str(
            r#"f x:n>t;?x{n _:"matched";_:"other"}"#,
            Some("f"),
            vec![Value::Number(5.0)],
        );
        assert_eq!(result, Value::Text("matched".into()));
    }

    // --- Text comparison operators ---

    #[test]
    fn interpret_text_greater_than() {
        let result = run_str("f a:t b:t>b;>a b", Some("f"), vec![
            Value::Text("b".into()), Value::Text("a".into()),
        ]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_text_less_than() {
        let result = run_str("f a:t b:t>b;<a b", Some("f"), vec![
            Value::Text("a".into()), Value::Text("b".into()),
        ]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_text_greater_or_equal() {
        let result = run_str("f a:t b:t>b;>=a b", Some("f"), vec![
            Value::Text("a".into()), Value::Text("a".into()),
        ]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_text_less_or_equal() {
        let result = run_str("f a:t b:t>b;<=a b", Some("f"), vec![
            Value::Text("a".into()), Value::Text("b".into()),
        ]);
        assert_eq!(result, Value::Bool(true));
    }

    // --- Destructure error path ---

    #[test]
    fn interpret_destructure_non_record_error() {
        let prog = parse_program("type pt{x:n;y:n} f p:pt>n;{x;y}=p;+x y");
        // Pass a non-record at runtime (bypass type checking)
        let result = run(&prog, Some("f"), vec![Value::Number(42.0)]);
        assert!(result.is_err(), "expected error for destructure on non-record");
    }

    // --- Safe field/index on nil ---

    #[test]
    fn interpret_safe_field_on_nil_returns_nil() {
        // mget on missing key returns nil; safe field access on nil short-circuits to nil
        let result = run_str("f>n;x=mget mmap \"key\";x.?field", Some("f"), vec![]);
        assert_eq!(result, Value::Nil);
    }

    #[test]
    fn interpret_safe_index_on_nil_returns_nil() {
        // mget on missing key returns nil; safe index access on nil short-circuits to nil
        let result = run_str("f>n;xs=mget mmap \"key\";xs.?0", Some("f"), vec![]);
        assert_eq!(result, Value::Nil);
    }

    // --- values_equal for texts ---

    #[test]
    fn values_equal_texts() {
        assert!(values_equal(&Value::Text("a".into()), &Value::Text("a".into())));
        assert!(!values_equal(&Value::Text("a".into()), &Value::Text("b".into())));
    }

    // ── New coverage tests ────────────────────────────────────────────────────

    // L62: Value::FnRef Display
    #[test]
    fn display_fnref() {
        assert_eq!(format!("{}", Value::FnRef("add".into())), "<fn:add>");
    }

    // L268-279: parse_csv_row with quoted fields
    #[test]
    fn parse_csv_row_quoted_fields() {
        // quoted field + escaped double-quote inside
        let rows = parse_csv_row(r#""he said ""hello""","world""#, ',');
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], r#"he said "hello""#);
        assert_eq!(rows[1], "world");
    }

    #[test]
    fn parse_csv_row_simple_quoted() {
        // plain quoted field (no escaped quotes)
        let rows = parse_csv_row(r#""hello","world""#, ',');
        assert_eq!(rows[0], "hello");
        assert_eq!(rows[1], "world");
    }

    // L299: len on Map
    #[test]
    fn interpret_len_map() {
        let result = run_str(
            r#"f>n;m=mset (mset mmap "a" 1) "b" 2;len m"#,
            Some("f"),
            vec![],
        );
        assert_eq!(result, Value::Number(2.0));
    }

    // L310: mget wrong args
    #[test]
    fn interpret_mget_wrong_args() {
        let err = run_str_err("f>n;mget 42 \"key\"", Some("f"), vec![]);
        assert!(err.contains("mget"), "got: {err}");
    }

    // L320: mset wrong args
    #[test]
    fn interpret_mset_wrong_args() {
        let err = run_str_err("f>n;mset 42 \"key\" 1", Some("f"), vec![]);
        assert!(err.contains("mset"), "got: {err}");
    }

    // L324-326: mhas wrong args
    #[test]
    fn interpret_mhas_wrong_args() {
        let err = run_str_err("f>n;mhas 42 \"key\"", Some("f"), vec![]);
        assert!(err.contains("mhas"), "got: {err}");
    }

    // L330-336: mkeys wrong args
    #[test]
    fn interpret_mkeys_wrong_args() {
        let err = run_str_err("f>n;mkeys 42", Some("f"), vec![]);
        assert!(err.contains("mkeys"), "got: {err}");
    }

    // L340-346: mvals wrong args
    #[test]
    fn interpret_mvals_wrong_args() {
        let err = run_str_err("f>n;mvals 42", Some("f"), vec![]);
        assert!(err.contains("mvals"), "got: {err}");
    }

    // L350-356: mdel wrong args
    #[test]
    fn interpret_mdel_wrong_args() {
        let err = run_str_err("f>n;mdel 42 \"key\"", Some("f"), vec![]);
        assert!(err.contains("mdel"), "got: {err}");
    }

    // L437: rnd wrong types (two non-number args)
    #[test]
    fn interpret_rnd_wrong_types() {
        let err = run_str_err(r#"f>n;rnd "a" "b""#, Some("f"), vec![]);
        assert!(err.contains("rnd"), "got: {err}");
    }

    // L566-570: srt with key fn — second arg not a list
    #[test]
    fn interpret_srt_key_fn_wrong_second_arg() {
        let source = "sq x:n>n;*x x f>n;srt sq 42";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(err.contains("srt"), "got: {err}");
    }

    // L582-583: srt with key fn — text keys
    #[test]
    fn interpret_srt_key_fn_text_keys() {
        let source = "id x:t>t;x main xs:L t>L t;srt id xs";
        let result = run_str(source, Some("main"), vec![
            Value::List(vec![
                Value::Text("banana".into()),
                Value::Text("apple".into()),
                Value::Text("cherry".into()),
            ]),
        ]);
        assert_eq!(result, Value::List(vec![
            Value::Text("apple".into()),
            Value::Text("banana".into()),
            Value::Text("cherry".into()),
        ]));
    }

    // L622: get with invalid (non-map) headers
    #[test]
    fn interpret_get_invalid_headers() {
        let err = run_str_err(r#"f>t;get "http://x" 42"#, Some("f"), vec![]);
        assert!(err.contains("headers") || err.contains("M t t"), "got: {err}");
    }

    // L648: post wrong arg types
    #[test]
    fn interpret_post_wrong_arg_types() {
        let err = run_str_err(r#"f>t;post 42 "body""#, Some("f"), vec![]);
        assert!(err.contains("post"), "got: {err}");
    }

    // L656: post with invalid headers
    #[test]
    fn interpret_post_invalid_headers() {
        let err = run_str_err(r#"f>t;post "http://x" "body" 42"#, Some("f"), vec![]);
        assert!(err.contains("headers") || err.contains("post"), "got: {err}");
    }

    // L703: unq wrong type
    #[test]
    fn interpret_unq_wrong_type() {
        let err = run_str_err("f>n;unq 42", Some("f"), vec![]);
        assert!(err.contains("unq"), "got: {err}");
    }

    // L709: fmt wrong first arg
    #[test]
    fn interpret_fmt_wrong_first_arg() {
        let err = run_str_err("f>n;fmt 42", Some("f"), vec![]);
        assert!(err.contains("fmt"), "got: {err}");
    }

    // L732: rd wrong arg type
    #[test]
    fn interpret_rd_wrong_arg_type() {
        let err = run_str_err("f>t;rd 42", Some("f"), vec![]);
        assert!(err.contains("rd"), "got: {err}");
    }

    // L735-737: rd with explicit format, wrong format arg type
    #[test]
    fn interpret_rd_with_wrong_format_type() {
        let err = run_str_err("f>t;rd \"/tmp\" 42", Some("f"), vec![]);
        assert!(err.contains("rd") || err.contains("format"), "got: {err}");
    }

    // L758: rdb wrong first arg
    #[test]
    fn interpret_rdb_wrong_first_arg() {
        let err = run_str_err(r#"f>t;rdb 42 "raw""#, Some("f"), vec![]);
        assert!(err.contains("rdb"), "got: {err}");
    }

    // L762: rdb wrong format arg
    #[test]
    fn interpret_rdb_wrong_format_arg() {
        let err = run_str_err(r#"f>t;rdb "hello" 42"#, Some("f"), vec![]);
        assert!(err.contains("rdb") || err.contains("format"), "got: {err}");
    }

    // L770-777: rdl returns list of lines
    #[test]
    fn interpret_rdl_basic() {
        let mut path = std::env::temp_dir();
        path.push("ilo_interp_rdl_test.txt");
        std::fs::write(&path, "line1\nline2\nline3").unwrap();
        let path_str = path.to_str().unwrap().to_string();
        let result = run_str(
            "f p:t>t;rdl p",
            Some("f"),
            vec![Value::Text(path_str)],
        );
        std::fs::remove_file(&path).ok();
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        let Value::List(lines) = *inner else { panic!("expected list") };
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], Value::Text("line1".into()));
    }

    // L779: rdl file not found
    #[test]
    fn interpret_rdl_not_found() {
        let result = run_str(
            "f p:t>t;rdl p",
            Some("f"),
            vec![Value::Text("/nonexistent/ilo_rdl_test.txt".into())],
        );
        assert!(matches!(result, Value::Err(_)), "expected Err, got {:?}", result);
    }

    // L781: rdl wrong arg type
    #[test]
    fn interpret_rdl_wrong_arg() {
        let err = run_str_err("f>t;rdl 42", Some("f"), vec![]);
        assert!(err.contains("rdl"), "got: {err}");
    }

    // L785-788: wr basic (write to temp file)
    #[test]
    fn interpret_wr_basic() {
        let mut path = std::env::temp_dir();
        path.push("ilo_interp_wr_test.txt");
        let path_str = path.to_str().unwrap().to_string();
        let result = run_str(
            "f p:t>t;wr p \"hello\"",
            Some("f"),
            vec![Value::Text(path_str.clone())],
        );
        std::fs::remove_file(&path).ok();
        assert!(matches!(result, Value::Ok(_)), "expected Ok, got {:?}", result);
    }

    // L790: wr wrong arg types
    #[test]
    fn interpret_wr_wrong_args() {
        let err = run_str_err("f>t;wr 42 \"hello\"", Some("f"), vec![]);
        assert!(err.contains("wr"), "got: {err}");
    }

    // L794-805: wrl basic
    #[test]
    fn interpret_wrl_basic() {
        let mut path = std::env::temp_dir();
        path.push("ilo_interp_wrl_test.txt");
        let path_str = path.to_str().unwrap().to_string();
        let result = run_str(
            "f p:t>t;wrl p [\"a\", \"b\", \"c\"]",
            Some("f"),
            vec![Value::Text(path_str.clone())],
        );
        std::fs::remove_file(&path).ok();
        assert!(matches!(result, Value::Ok(_)), "expected Ok, got {:?}", result);
    }

    // L800: wrl list with non-text item
    #[test]
    fn interpret_wrl_non_text_item() {
        let mut path = std::env::temp_dir();
        path.push("ilo_interp_wrl_nontxt_test.txt");
        let path_str = path.to_str().unwrap().to_string();
        let mut env = Env::new();
        let result = call_function(
            &mut env,
            "wrl",
            vec![
                Value::Text(path_str.clone()),
                Value::List(vec![Value::Text("ok".into()), Value::Number(99.0)]),
            ],
        );
        std::fs::remove_file(&path).ok();
        assert!(result.is_err(), "expected error for non-text wrl item");
        let err = result.unwrap_err().to_string();
        assert!(err.contains("wrl"), "got: {err}");
    }

    // L808: wrl wrong arg types
    #[test]
    fn interpret_wrl_wrong_args() {
        let err = run_str_err("f>t;wrl 42 [\"a\"]", Some("f"), vec![]);
        assert!(err.contains("wrl"), "got: {err}");
    }

    // L822: jpth array index navigation
    #[test]
    fn interpret_jpth_array_index() {
        let source = r#"f j:t p:t>R t t;jpth j p"#;
        let result = run_str(source, Some("f"), vec![
            Value::Text(r#"[10,20,30]"#.to_string()),
            Value::Text("1".to_string()),
        ]);
        assert_eq!(result, Value::Ok(Box::new(Value::Text("20".into()))));
    }

    // L839: jpth non-text/non-map args
    #[test]
    fn interpret_jpth_wrong_args() {
        let err = run_str_err(r#"f>t;jpth 42 "path""#, Some("f"), vec![]);
        assert!(err.contains("jpth"), "got: {err}");
    }

    // L857: jdmp on Ok value
    #[test]
    fn interp_jdmp_ok_value() {
        let result = run_str("f>t;jdmp ~42", Some("f"), vec![]);
        assert_eq!(result, Value::Text("42".into()));
    }

    // L869: jdmp on FnRef (goes through value_to_json FnRef branch)
    #[test]
    fn interp_jdmp_fnref() {
        let source = "sq x:n>n;*x x f>t;r=sq;jdmp r";
        let result = run_str(source, Some("f"), vec![]);
        // FnRef displays as "<fn:sq>"
        let Value::Text(s) = result else { panic!("expected Text") };
        assert!(s.contains("fn:sq") || s.contains("sq"), "got: {s}");
    }

    // L879-880: jpar wrong arg type
    #[test]
    fn interp_jpar_wrong_arg_type() {
        let err = run_str_err("f>t;jpar 42", Some("f"), vec![]);
        assert!(err.contains("jpar"), "got: {err}");
    }

    // L885-886: env wrong arg type
    #[test]
    fn interpret_env_wrong_arg_type() {
        let err = run_str_err("f>t;env 42", Some("f"), vec![]);
        assert!(err.contains("env"), "got: {err}");
    }

    // L889: map wrong first arg (not a fn ref)
    #[test]
    fn interpret_map_wrong_fn_arg() {
        let err = run_str_err("f>t;map 42 [1, 2]", Some("f"), vec![]);
        assert!(err.contains("map"), "got: {err}");
    }

    // L899-900: map wrong second arg (not a list)
    #[test]
    fn interpret_map_wrong_list_arg() {
        let source = "sq x:n>n;*x x f>t;map sq 42";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(err.contains("map"), "got: {err}");
    }

    // L903: flt predicate returns non-bool
    #[test]
    fn interpret_flt_predicate_returns_non_bool() {
        let source = "id x:n>n;x f xs:L n>L n;flt id xs";
        let err = run_str_err(source, Some("f"), vec![
            Value::List(vec![Value::Number(1.0)]),
        ]);
        assert!(err.contains("flt") || err.contains("bool"), "got: {err}");
    }

    // L910: flt wrong list arg
    #[test]
    fn interpret_flt_wrong_list_arg() {
        let source = "pos x:n>b;>x 0 f>t;flt pos 42";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(err.contains("flt"), "got: {err}");
    }

    // L917-918: fld wrong list arg
    #[test]
    fn interpret_fld_wrong_list_arg() {
        let source = "add a:n b:n>n;+a b f>n;fld add 42 0";
        let err = run_str_err(source, Some("f"), vec![]);
        assert!(err.contains("fld"), "got: {err}");
    }

    // L921: fld wrong first arg (not a fn ref)
    #[test]
    fn interpret_fld_wrong_fn_arg() {
        let err = run_str_err("f>n;fld 42 [1, 2] 0", Some("f"), vec![]);
        assert!(err.contains("fld"), "got: {err}");
    }

    // L956: Decl::Use branch in call_function
    #[test]
    fn interpret_call_use_decl_errors() {
        use crate::ast::{Decl, Span};
        let mut env = Env::new();
        env.functions.insert(
            "fake_use".to_string(),
            Decl::Use { path: "x.ilo".to_string(), only: None, span: Span { start: 0, end: 0 } },
        );
        let result = call_function(&mut env, "fake_use", vec![]);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unresolved import"));
    }

    // L984: Alias branch in call_function
    #[test]
    fn interpret_call_alias_decl_errors() {
        use crate::ast::{Decl, Span, Type};
        let mut env = Env::new();
        env.functions.insert(
            "myalias".to_string(),
            Decl::Alias { name: "myalias".to_string(), target: Type::Number, span: Span { start: 0, end: 0 } },
        );
        let result = call_function(&mut env, "myalias", vec![]);
        assert!(result.is_err());
    }

    // L987: Error decl branch in call_function
    #[test]
    fn interpret_call_error_decl_errors() {
        use crate::ast::{Decl, Span};
        let mut env = Env::new();
        env.functions.insert(
            "bad_decl".to_string(),
            Decl::Error { span: Span { start: 0, end: 0 } },
        );
        let result = call_function(&mut env, "bad_decl", vec![]);
        assert!(result.is_err());
    }

    // L1001-1003: Expr::Match arms — Continue from body
    // The Continue path in match-expr eval_body → BodyResult::Continue → Value::Nil
    #[test]
    fn interpret_match_continue_arm_returns_nil() {
        // A match where the matched arm body triggers continue (cnt) — only valid in for loop
        let source = "f xs:L n>n;@x xs{?x{1:cnt;_:x}}";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(2.0)]),
        ]);
        // Iteration: x=1 → cnt (continue), x=2 → 2. Last value of foreach body = 2.
        assert_eq!(result, Value::Number(2.0));
    }

    // L1103-1104: Guard ternary with else body — exercises BodyResult::Value in ternary branch
    #[test]
    fn interpret_guard_ternary_in_foreach() {
        // Ternary `=x 0{yes}{no}` used inside a foreach body
        let source = "f xs:L n>n;@x xs{=x 0{10}{20}}";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![Value::Number(0.0), Value::Number(1.0)]),
        ]);
        // x=0: true → 10, x=1: false → 20. Last value = 20.
        assert_eq!(result, Value::Number(20.0));
    }

    // L1140-1141: Match arm Continue path in match-stmt
    #[test]
    fn interpret_match_stmt_continue_propagates() {
        let source = "f xs:L n>n;@x xs{?x{1:cnt;_:x}}";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(5.0)]),
        ]);
        assert_eq!(result, Value::Number(5.0));
    }

    // L1185: ForEach — early return propagated via match-arm returning value
    #[test]
    fn interpret_foreach_return_from_nested_match() {
        // Match arm returns a value; foreach body value propagates
        let source = "f xs:L n>n;@x xs{?x{5:x;_:0}}";
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(5.0), Value::Number(9.0)]),
        ]);
        // x=1 → 0, x=5 → 5, x=9 → 0; last value of foreach = 0
        assert_eq!(result, Value::Number(0.0));
    }

    // L1189: ForRange — range end not a number
    #[test]
    fn interpret_range_end_not_number() {
        // ForRange where end is not a number — needs tricky setup
        // The range start/end are evaluated, if end is text it errors
        let source = "f s:n e:n>n;@i s..e{i}";
        let result = run_str(source, Some("f"), vec![
            Value::Number(0.0), Value::Number(3.0),
        ]);
        assert_eq!(result, Value::Number(2.0));
    }

    // L1298: value_to_json large float (uses Number::from_f64)
    #[test]
    fn interp_jdmp_large_float() {
        let source = "f x:n>t;jdmp x";
        // Very large float that won't be an integer — exercises from_f64 path
        let result = run_str(source, Some("f"), vec![Value::Number(1.23456789e20)]);
        assert!(matches!(result, Value::Text(_)));
    }

    // L1309: value_to_json Err inner
    #[test]
    fn interp_jdmp_err_value() {
        let result = run_str("f>t;jdmp ^42", Some("f"), vec![]);
        assert_eq!(result, Value::Text("42".into()));
    }

    // L1379: value_to_json Map variant
    #[test]
    fn interp_jdmp_map_value() {
        let result = run_str(r#"f>t;m=mset mmap "k" 1;jdmp m"#, Some("f"), vec![]);
        let Value::Text(s) = result else { panic!("expected text") };
        assert!(s.contains("k"), "got: {s}");
    }

    // L1527-1528: TypeIs List pattern (uses `l` token for list)
    #[test]
    fn interpret_type_is_list_match() {
        let source = r#"f x:L n>t;?x{l v:"list";_:"other"}"#;
        let result = run_str(source, Some("f"), vec![
            Value::List(vec![Value::Number(1.0)]),
        ]);
        assert_eq!(result, Value::Text("list".into()));
    }

    // L2376: Decl::TypeDef is not callable error (duplicate name avoided — already tested above)
    // (see earlier interpret_typedef_not_callable test)

    // L3669/3671: rdb csv header-only / single row
    #[test]
    fn interpret_rdb_csv_single_row() {
        let result = run_str(
            r#"f s:t>t;rdb s "csv""#,
            Some("f"),
            vec![Value::Text("a,b,c".into())],
        );
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        let Value::List(rows) = *inner else { panic!("expected list") };
        assert_eq!(rows.len(), 1);
    }

    // ── mhas/mkeys/mvals/mdel happy paths ─────────────────────────────────

    // L325: mhas Map+Text → true/false
    #[test]
    fn interpret_mhas_found() {
        let result = run_str(r#"f>b;m=mset mmap "x" 1;mhas m "x""#, Some("f"), vec![]);
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn interpret_mhas_not_found() {
        let result = run_str(r#"f>b;m=mset mmap "x" 1;mhas m "y""#, Some("f"), vec![]);
        assert_eq!(result, Value::Bool(false));
    }

    // L331-334: mkeys happy path — sorted keys
    #[test]
    fn interpret_mkeys_happy_path() {
        let result = run_str(r#"f>L t;m=mset (mset mmap "b" 2) "a" 1;mkeys m"#, Some("f"), vec![]);
        assert_eq!(result, Value::List(vec![Value::Text("a".into()), Value::Text("b".into())]));
    }

    // L341-344: mvals happy path — values sorted by key
    #[test]
    fn interpret_mvals_happy_path() {
        let result = run_str(r#"f>L n;m=mset (mset mmap "b" 2) "a" 1;mvals m"#, Some("f"), vec![]);
        assert_eq!(result, Value::List(vec![Value::Number(1.0), Value::Number(2.0)]));
    }

    // L351-354: mdel happy path — delete key from map
    #[test]
    fn interpret_mdel_happy_path() {
        let result = run_str(r#"f>n;m=mset (mset mmap "a" 1) "b" 2;m2=mdel m "a";len m2"#, Some("f"), vec![]);
        assert_eq!(result, Value::Number(1.0));
    }

    // ── srt 2-arg key not fn-ref (line 566-567) ────────────────────────────

    #[test]
    fn interpret_srt_key_not_fn_ref() {
        // 42 is a Number, resolve_fn_ref returns None → line 566-567 error
        let err = run_str_err("f xs:L n>L n;srt 42 xs", Some("f"),
            vec![Value::List(vec![Value::Number(1.0)])]);
        assert!(err.contains("srt"), "got: {err}");
    }

    // ── flt first arg not fn-ref (lines 968-969) ────────────────────────────

    #[test]
    fn interpret_flt_key_not_fn_ref() {
        let err = run_str_err("f xs:L n>L n;flt 42 xs", Some("f"),
            vec![Value::List(vec![Value::Number(1.0)])]);
        assert!(err.contains("flt"), "got: {err}");
    }

    // ── resolve_fn_ref Text path (line 948) via map with text fn name ───────

    #[test]
    fn interpret_map_with_text_fn_name() {
        // Pass fn name as text arg; resolve_fn_ref hits Text branch (line 948)
        let source = "sq x:n>n;*x x f cb:t xs:L n>L n;map cb xs";
        let result = run_str(source, Some("f"), vec![
            Value::Text("sq".into()),
            Value::List(vec![Value::Number(3.0)]),
        ]);
        assert_eq!(result, Value::List(vec![Value::Number(9.0)]));
    }

    // ── rd 2-arg explicit format (lines 736, 749, 750-751) ──────────────────

    #[test]
    fn interpret_rd_explicit_raw_format() {
        // Write a temp file, read with explicit "raw" format → lines 736, 749
        let path = "/tmp/ilo_test_rd_explicit.txt";
        std::fs::write(path, "hello").unwrap();
        let source = format!(r#"f>R t t;rd "{path}" "raw""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(inner) = result else { panic!("expected Ok") };
        assert_eq!(*inner, Value::Text("hello".into()));
    }

    #[test]
    fn interpret_rd_explicit_format_parse_error() {
        // Write invalid JSON to a temp file, read with "json" format → line 750-751
        let path = "/tmp/ilo_test_rd_badjson.txt";
        std::fs::write(path, "not json at all!!!").unwrap();
        let source = format!(r#"f>R t t;rd "{path}" "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Err(_) = result else { panic!("expected Err") };
        // parse_format returns Err → line 750-751
    }

    // ── wr 3-arg csv/json (lines 792, 799, 819-820, 835-843) ───────────────

    #[test]
    fn interpret_wr_csv_format() {
        // wr path data "csv" — csv format path → lines 795, 804, 816-817, 824
        let path = "/tmp/ilo_test_wr.csv";
        let source = format!(r#"f>R t t;wr "{path}" [[1,2],[3,4]] "csv""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("1,2"));
    }

    #[test]
    fn interpret_wr_csv_bool_field() {
        // Bool field in csv row → line 819
        let path = "/tmp/ilo_test_wr_bool.csv";
        let source = format!(r#"f>R t t;wr "{path}" [[true,false]] "csv""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("true"));
    }

    #[test]
    fn interpret_wr_json_format() {
        // wr path data "json" → lines 831, 834-848
        let path = "/tmp/ilo_test_wr.json";
        let source = format!(r#"f>R t t;wr "{path}" [1,2,3] "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("1"));
    }

    // ── grp Number/Bool key (lines 1012-1016, 1019-1020) ───────────────────

    #[test]
    fn interpret_grp_number_key() {
        // Key fn returns Number → lines 1012-1016
        let source = "id x:n>n;x g xs:L n>_;grp id xs";
        let result = run_str(source, Some("g"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(1.0)]),
        ]);
        let Value::Map(m) = result else { panic!("expected map") };
        assert_eq!(m.len(), 2);
    }

    #[test]
    fn interpret_grp_bool_key() {
        // Key fn returns Bool → lines 1019-1020
        let source = "pos x:n>b;>x 0 g xs:L n>_;grp pos xs";
        let result = run_str(source, Some("g"), vec![
            Value::List(vec![Value::Number(-1.0), Value::Number(1.0), Value::Number(2.0)]),
        ]);
        let Value::Map(m) = result else { panic!("expected map") };
        assert!(m.contains_key("true"));
        assert!(m.contains_key("false"));
    }

    // ── avg non-number element (line 1053) ──────────────────────────────────

    #[test]
    fn interpret_avg_non_number_element() {
        let err = run_str_err("f xs:L n>n;avg xs", Some("f"),
            vec![Value::List(vec![Value::Text("x".into())])]);
        assert!(err.contains("avg"), "got: {err}");
    }

    // ── rgx non-text second arg (line 1065) ─────────────────────────────────

    #[test]
    fn interpret_rgx_non_text_second_arg() {
        let err = run_str_err(r#"f>L t;rgx "." 42"#, Some("f"), vec![]);
        assert!(err.contains("rgx"), "got: {err}");
    }

    // ── jdmp Bool/Nil → value_to_json lines 1179-1180 ───────────────────────

    #[test]
    fn interpret_jdmp_bool_value() {
        // value_to_json Bool branch (line 1179)
        let result = run_str("f>t;jdmp true", Some("f"), vec![]);
        assert_eq!(result, Value::Text("true".into()));
    }

    #[test]
    fn interpret_jdmp_nil_value() {
        // value_to_json Nil branch (line 1180) — mget on empty map returns Nil
        let result = run_str(r#"f>t;jdmp (mget mmap "k")"#, Some("f"), vec![]);
        assert_eq!(result, Value::Text("null".into()));
    }

    // ── wr json — text/bool/map/nil value types (lines 835-843) ───────────────

    #[test]
    fn interpret_wr_json_text_value() {
        // value_to_json Text branch (line 835)
        let path = "/tmp/ilo_test_wr_json_text.json";
        let source = format!(r#"f>R t t;wr "{path}" "hello world" "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("hello world"));
    }

    #[test]
    fn interpret_wr_json_bool_value() {
        // value_to_json Bool branch (line 836)
        let path = "/tmp/ilo_test_wr_json_bool.json";
        let source = format!(r#"f>R t t;wr "{path}" true "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("true"));
    }

    #[test]
    fn interpret_wr_json_map_value() {
        // value_to_json Map branch (lines 838-841)
        let path = "/tmp/ilo_test_wr_json_map.json";
        let source = format!(r#"f>R t t;m=mset mmap "k" 42;wr "{path}" m "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(content.contains("\"k\""));
        assert!(content.contains("42"));
    }

    #[test]
    fn interpret_wr_json_nil_value() {
        // value_to_json Nil branch (line 842) — mget on missing key returns Nil
        let path = "/tmp/ilo_test_wr_json_nil.json";
        let source = format!(r#"f>R t t;v=mget mmap "x";wr "{path}" v "json""#);
        let result = run_str(&source, Some("f"), vec![]);
        let Value::Ok(_) = result else { panic!("expected Ok") };
        let content = std::fs::read_to_string(path).unwrap();
        assert_eq!(content.trim(), "null");
    }

    // ── wr — error paths (lines 792, 799, 826) ────────────────────────────────

    #[test]
    fn interpret_wr_non_text_format_arg_errors() {
        // wr format arg must be text (line 792)
        let path = "/tmp/ilo_test_wr_fmt_err.csv";
        let source = format!(r#"f>R t t;wr "{path}" [1] 42"#);
        let err = run_str_err(&source, Some("f"), vec![]);
        assert!(err.contains("wr"), "got: {err}");
    }

    #[test]
    fn interpret_wr_csv_non_list_data_errors() {
        // wr csv data must be a list (line 799)
        let path = "/tmp/ilo_test_wr_csv_nonlist.csv";
        let source = format!(r#"f>R t t;wr "{path}" 42 "csv""#);
        let err = run_str_err(&source, Some("f"), vec![]);
        assert!(err.contains("wr"), "got: {err}");
    }

    #[test]
    fn interpret_wr_csv_row_not_a_list_errors() {
        // each csv row must be a list (line 826)
        let path = "/tmp/ilo_test_wr_csv_row_err.csv";
        // [42] is a list with element 42 (number, not a list of fields)
        let source = format!(r#"f>R t t;wr "{path}" [42] "csv""#);
        let err = run_str_err(&source, Some("f"), vec![]);
        assert!(err.contains("wr"), "got: {err}");
    }

    // ── grp — float key (line 1016) ──────────────────────────────────────────

    #[test]
    fn interpret_grp_float_key() {
        // Key function returns a fractional number → format!("{n}") path (line 1016)
        // Use floor-then-half: key = x/2 for x in [1,2,3] → keys 0.5, 1.0, 1.5
        let source = "half x:n>n;/x 2 g xs:L n>_;grp half xs";
        let result = run_str(source, Some("g"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(2.0), Value::Number(3.0)]),
        ]);
        let Value::Map(m) = result else { panic!("expected Map") };
        // 1/2=0.5, 2/2=1, 3/2=1.5 → 3 groups
        assert!(m.contains_key("0.5") || m.contains_key("1.5"),
            "expected float key, got: {:?}", m.keys().collect::<Vec<_>>());
    }

    // ── ForRange early return (lines 1370-1371) ───────────────────────────────

    #[test]
    fn interpret_for_range_early_return_via_guard() {
        // A guard inside a for-range body causes early return from the function.
        // When i >= 3, the guard returns i → BodyResult::Return propagates out of loop.
        // Syntax: @binding start..end{body}
        let result = run_str("f>n;@i 0..5{>=i 3{i};i}", Some("f"), vec![]);
        assert_eq!(result, Value::Number(3.0));
    }

    // ── wr csv with Nil field (line 820) ─────────────────────────────────────

    #[test]
    fn interpret_wr_csv_nil_field() {
        // Nil in a csv row → `other => format!("{other}")` path (line 820)
        // Pass Nil as a z-typed arg to bypass the verifier
        let path = "/tmp/ilo_test_wr_nil.csv";
        let source = format!(r#"f x:z>R t t;wr "{path}" [[x,1]] "csv""#);
        let result = run_str(&source, Some("f"), vec![Value::Nil]);
        let Value::Ok(_) = result else { panic!("expected Ok, got {:?}", result) };
        let content = std::fs::read_to_string(path).unwrap();
        assert!(!content.is_empty());
    }

    // ── wr json with Ok value (line 843) ─────────────────────────────────────

    #[test]
    fn interpret_wr_json_with_ok_value() {
        // `other => Value::from(format!("{other}"))` path in json value_to_json (line 843)
        // Pass Value::Ok as a z-typed arg to bypass the verifier
        let path = "/tmp/ilo_test_wr_ok.json";
        let source = format!(r#"f x:z>R t t;wr "{path}" x "json""#);
        let result = run_str(&source, Some("f"), vec![
            Value::Ok(Box::new(Value::Number(1.0))),
        ]);
        let Value::Ok(_) = result else { panic!("expected Ok, got {:?}", result) };
    }

    // ── wr 2-arg non-text content (line 854) ─────────────────────────────────

    #[test]
    fn interpret_wr_two_arg_non_text_content_error() {
        // wr path 42 — second arg is a number, not text (line 854 other => Err)
        let err = run_str_err(
            r#"f>R t t;wr "/tmp/ilo_test_bad_wr.txt" 42"#,
            Some("f"), vec![],
        );
        assert!(err.contains("wr") || err.contains("text") || err.contains("content"), "got: {err}");
    }

    // ── wr fs::write failure (line 859) ──────────────────────────────────────

    #[test]
    fn interpret_wr_write_failure_returns_err() {
        // Write to a non-existent directory → fs::write Err → Value::Err (line 859)
        let source = r#"f>R t t;wr "/no/such/dir/ilo_test.txt" "hello""#;
        let result = run_str(source, Some("f"), vec![]);
        let Value::Err(_) = result else { panic!("expected Err for bad path, got {:?}", result) };
    }

    // ── wrl fs::write failure (line 874) ─────────────────────────────────────

    #[test]
    fn interpret_wrl_write_failure_returns_err() {
        // Write to a non-existent directory → fs::write Err → Value::Err (line 874)
        let source = r#"f>R t t;wrl "/no/such/dir/ilo_test.txt" ["a","b"]"#;
        let result = run_str(source, Some("f"), vec![]);
        let Value::Err(_) = result else { panic!("expected Err for bad path, got {:?}", result) };
    }

    // ── jpth array index out of bounds (line 891) ────────────────────────────

    #[test]
    fn interpret_jpth_array_index_out_of_bounds() {
        // jpth where numeric key is out of bounds in array → Err (line 891)
        let source = r#"f>R t t;jpth "[1,2,3]" "5""#;
        let result = run_str(source, Some("f"), vec![]);
        let Value::Err(inner) = result else { panic!("expected Err, got {:?}", result) };
        let s = inner.to_string();
        assert!(s.contains("not found") || s.contains("5"), "got: {s}");
    }

    // ── grp key returns non-basic type (line 1020) ───────────────────────────

    #[test]
    fn interpret_grp_key_returns_list_error() {
        // Key function returns a List → grp errors at line 1020
        let source = "mk x:n>L n;[x] g xs:L n>_;grp mk xs";
        let err = run_str_err(source, Some("g"), vec![
            Value::List(vec![Value::Number(1.0), Value::Number(2.0)]),
        ]);
        assert!(err.contains("grp") || err.contains("key") || err.contains("string"), "got: {err}");
    }

    // ── ForRange non-number start/end (lines 1357, 1361) ─────────────────────

    #[test]
    fn interpret_for_range_non_number_start_error() {
        // @i "a"..3{i} — start is text → error at line 1357
        let err = run_str_err("f s:t>n;@i s..3{i}", Some("f"), vec![
            Value::Text("a".into()),
        ]);
        assert!(err.contains("range") || err.contains("number") || err.contains("start"), "got: {err}");
    }

    #[test]
    fn interpret_for_range_non_number_end_error() {
        // @i 0..z{i} — end is text → error at line 1361
        let err = run_str_err("f e:t>n;@i 0..e{i}", Some("f"), vec![
            Value::Text("b".into()),
        ]);
        assert!(err.contains("range") || err.contains("number") || err.contains("end"), "got: {err}");
    }

    // ── FnRef callee from scope (line 1470) ──────────────────────────────────

    #[test]
    fn interpret_fnref_callee_from_scope() {
        // A FnRef stored in a variable is used as a callee (line 1470)
        let source = "sq x:n>n;*x x f cb:z>n;cb 3";
        let result = run_str(source, Some("f"), vec![Value::FnRef("sq".into())]);
        assert_eq!(result, Value::Number(9.0));
    }

    // ── bang on non-Result value passes through (line 1481) ──────────────────

    #[test]
    fn interpret_bang_on_non_result_passes_through() {
        // id! where id returns a Number (not Result) → `other => Ok(other)` (line 1481)
        // id has z return type so verifier doesn't reject !, result passes through
        let source = "id x:n>z;x f>z;id! 42";
        let result = run_str(source, Some("f"), vec![]);
        // id returns Number(42), bang passes it through via the `other` arm
        assert_eq!(result, Value::Number(42.0));
    }

    // ── TypeIs pattern _ => false (line 1700) ────────────────────────────────

    #[test]
    fn interpret_typeis_pattern_non_basic_type_no_match() {
        // TypeIs with a type other than n/t/b/l → `_ => false` (line 1700)
        // Pattern `?x{n _:true;_:false}` for a Record value
        let source = "f x:z>b;?x{n _:true;_:false}";
        let result = run_str(source, Some("f"), vec![
            Value::Record { type_name: "pt".into(), fields: std::collections::HashMap::new() },
        ]);
        assert_eq!(result, Value::Bool(false));
    }

    // ── brk inside match arm propagates Break (line 1312) ────────────────────

    #[test]
    fn interpret_brk_inside_match_arm_propagates() {
        // ?x { 2: brk x; _ : x } — when x==2 break propagates out of match arm (L1312)
        // The match must NOT be the last stmt in the foreach body; otherwise the _:x arm
        // converts Value(1.0) → Return(1.0) on the first iteration, exiting the function
        // before x=2 is ever reached. Adding ;x as a trailing stmt keeps match non-last.
        let src = "f>n;@x [1,2,3]{?x{2:brk x;_:x};x}";
        let result = run_str(src, Some("f"), vec![]);
        assert_eq!(result, Value::Number(2.0));
    }

    // ── text variable used as callee (line 1470) ─────────────────────────────

    #[test]
    fn interpret_text_callee_from_scope() {
        // When a variable holds a Text naming a known function, it is used as the callee (L1470)
        let source = "sq x:n>n;*x x f cb:z>n;cb 3";
        let result = run_str(source, Some("f"), vec![Value::Text("sq".into())]);
        assert_eq!(result, Value::Number(9.0));
    }

    // ── srt with bool key hits _ => Equal arm (line 583) ─────────────────────

    #[test]
    fn interpret_srt_bool_key_equal_ordering() {
        // Key fn returns Bool → neither Number nor Text arm matches in sort_by → L583 _ => Equal
        let source = "pos x:n>b;> x 0 f>L n;srt pos [3,-1,2,-2]";
        let result = run_str(source, Some("f"), vec![]);
        // All elements are compared as Bool keys → Equal ordering → list unchanged
        let Value::List(items) = result else { panic!("expected List, got {:?}", result) };
        assert_eq!(items.len(), 4);
    }

    // ── brk inside guard body propagates Break (line 1287) ───────────────────

    #[test]
    fn interpret_brk_inside_guard_body_propagates() {
        // Guard body containing brk: when x>2, break with x → ForEach exits early (L1287)
        let src = "f>n;@x [1,2,3,4]{>x 2{brk x};x}";
        let result = run_str(src, Some("f"), vec![]);
        assert_eq!(result, Value::Number(3.0));
    }

    // ── cnt inside guard body propagates Continue (line 1288) ────────────────

    #[test]
    fn interpret_cnt_inside_guard_body_propagates() {
        // Guard body containing cnt: when x==1, skip iteration → ForEach gets last=3 (L1288)
        let src = "f>n;@x [1,2,3]{=x 1{cnt};x}";
        let result = run_str(src, Some("f"), vec![]);
        assert_eq!(result, Value::Number(3.0));
    }

    // ── brk inside ternary then-body propagates Break (line 1275) ─────────────

    #[test]
    fn interpret_brk_inside_ternary_body_propagates() {
        // Ternary cond{then}{else}: then-body contains brk → Break propagates (L1275)
        // When x==2: ternary true → brk x → Break(2.0) exits ForEach early
        let src = "f>n;@x [1,2,3]{=x 2{brk x}{0};0}";
        let result = run_str(src, Some("f"), vec![]);
        assert_eq!(result, Value::Number(2.0));
    }

    // ── cnt inside ternary then-body propagates Continue (line 1276) ──────────

    #[test]
    fn interpret_cnt_inside_ternary_body_propagates() {
        // Ternary cond{then}{else}: then-body contains cnt → Continue propagates (L1276)
        // When x==1: ternary true → cnt → Continue skips that iteration
        let src = "f>n;@x [1,2,3]{=x 1{cnt}{0};x}";
        let result = run_str(src, Some("f"), vec![]);
        assert_eq!(result, Value::Number(3.0));
    }

    // ── cnt inside match-expression arm returns Nil (line 1551) ──────────────

    #[test]
    fn interpret_cnt_in_match_expr_arm_returns_nil() {
        // Expr::Match arm body returns Continue → match expr yields Nil (L1551)
        // cnt inside match arm is "consumed" — the match expression returns Nil for that arm
        let src = "f>n;@x [1,2,3]{r=?x{1:cnt;_:x};r}";
        let result = run_str(src, Some("f"), vec![]);
        // x=1: match arm 1 runs cnt → Continue consumed → Nil, r=Nil
        // x=2: match arm _ matches → 2, r=2
        // x=3: match arm _ matches → 3, r=3 → foreach last=3
        assert_eq!(result, Value::Number(3.0));
    }

    // ── BodyResult::Continue in eval_call → Ok(Nil) (line 1128) ─────────────

    #[test]
    fn interpret_continue_in_function_body_returns_nil() {
        // cnt at top level of function body → eval_body returns BodyResult::Continue
        // eval_call L1128: BodyResult::Continue => Ok(Value::Nil)
        // Verifier rejects this pattern (ILO-T028), but run_str bypasses the verifier
        let result = run_str("f>_;cnt", Some("f"), vec![]);
        assert_eq!(result, Value::Nil);
    }
}