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
#![warn(clippy::all)]

mod ast;
mod codegen;
mod diagnostic;
mod interpreter;
mod lexer;
mod parser;
mod tools;
mod verify;
mod vm;

use diagnostic::{Diagnostic, ansi::AnsiRenderer, json};

/// Compact spec for LLM consumption — generated from SPEC.md at compile time.
fn compact_spec() -> &'static str {
    include_str!(concat!(env!("OUT_DIR"), "/spec_ai.txt"))
}

// ── `ilo tools` subcommand ─────────────────────────────────────────────────

#[derive(Clone, Copy, PartialEq, Eq)]
enum ToolsOutputFmt {
    Human, // human-readable table (default)
    Ilo,   // valid Decl::Tool ilo syntax
    Json,  // JSON array
}

/// Load and display tool signatures from MCP / HTTP sources.
fn tools_cmd(args: &[String]) {
    let mut mcp_path: Option<String> = None;
    let mut http_path: Option<String> = None;
    let mut fmt = ToolsOutputFmt::Human;
    let mut full = false;
    let mut graph = false;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--mcp" | "-m" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --mcp requires a path");
                    std::process::exit(1);
                }
                mcp_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--tools" | "-t" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --tools requires a path");
                    std::process::exit(1);
                }
                http_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--human" => {
                fmt = ToolsOutputFmt::Human;
                i += 1;
            }
            "--ilo" => {
                fmt = ToolsOutputFmt::Ilo;
                i += 1;
            }
            "--json" => {
                fmt = ToolsOutputFmt::Json;
                i += 1;
            }
            "--full" | "-f" => {
                full = true;
                i += 1;
            }
            "--graph" | "-g" => {
                graph = true;
                i += 1;
            }
            _ => {
                eprintln!("unknown flag: {}", args[i]);
                eprintln!(
                    "Usage: ilo tools [-m <path>] [-t <path>] \
                     [--human|--ilo|--json] [--full] [--graph]"
                );
                std::process::exit(1);
            }
        }
    }

    if mcp_path.is_none() && http_path.is_none() {
        eprintln!(
            "error: ilo tools requires at least one of --mcp <path> or --tools <path>"
        );
        eprintln!(
            "Usage: ilo tools [--mcp <path>] [--tools <path>] \
             [--human|--ilo|--json] [--full] [--graph]"
        );
        std::process::exit(1);
    }

    // --ilo, --json, and --graph always show full signatures.
    if matches!(fmt, ToolsOutputFmt::Ilo | ToolsOutputFmt::Json) || graph {
        full = true;
    }

    // ── HTTP tools (sync, no feature gate) ───────────────────────────────────
    let mut http_names: Vec<String> = Vec::new();
    if let Some(ref path) = http_path {
        let config = tools::http_provider::ToolsConfig::from_file(path)
            .unwrap_or_else(|e| {
                eprintln!("{}", e);
                std::process::exit(1);
            });
        let mut names: Vec<String> = config.tools.keys().cloned().collect();
        names.sort();
        http_names = names;
    }

    // ── MCP tools (async, feature-gated) ─────────────────────────────────────
    let mcp_decls = collect_mcp_tool_decls(mcp_path.as_deref());

    // ── Render ────────────────────────────────────────────────────────────────
    match fmt {
        ToolsOutputFmt::Human => {
            for name in &http_names {
                if full {
                    println!("{:<32} (http tool — no type info)", name);
                } else {
                    println!("{}", name);
                }
            }
            for decl in &mcp_decls {
                if let ast::Decl::Tool { name, description, params, return_type, .. } = decl {
                    if full {
                        let sig = tool_sig_str(params, return_type);
                        println!("{:<32} {:<44} {}", name, description, sig);
                    } else {
                        println!("{}", name);
                    }
                }
            }
        }
        ToolsOutputFmt::Ilo => {
            for name in &http_names {
                // No type info: emit with empty description and generic R t t.
                println!("tool {}\"\" > R t t", name);
            }
            for decl in &mcp_decls {
                println!("{}", codegen::fmt::format_decl(decl, codegen::fmt::FmtMode::Dense));
            }
        }
        ToolsOutputFmt::Json => {
            let mut items: Vec<serde_json::Value> = Vec::new();
            for name in &http_names {
                items.push(serde_json::json!({
                    "name": name,
                    "source": "http",
                    "description": null,
                    "params": [],
                    "return": null
                }));
            }
            for decl in &mcp_decls {
                if let ast::Decl::Tool { name, description, params, return_type, .. } = decl {
                    let params_json: Vec<serde_json::Value> = params
                        .iter()
                        .map(|p| {
                            serde_json::json!({
                                "name": p.name,
                                "type": codegen::fmt::type_str(&p.ty)
                            })
                        })
                        .collect();
                    items.push(serde_json::json!({
                        "name": name,
                        "source": "mcp",
                        "description": description,
                        "params": params_json,
                        "return": codegen::fmt::type_str(return_type)
                    }));
                }
            }
            match serde_json::to_string_pretty(&items) {
                Ok(s) => println!("{}", s),
                Err(e) => {
                    eprintln!("failed to render JSON: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }

    // ── Graph (additive — shown after or instead of table) ───────────────────
    if graph {
        print_tool_graph(&mcp_decls);
    }
}

/// Print a type-level composition graph: for each tool, which tools can consume its output.
fn print_tool_graph(decls: &[ast::Decl]) {
    // Collect (name, params, return_type) for all typed tools.
    let tools: Vec<(&str, &[ast::Param], &ast::Type)> = decls
        .iter()
        .filter_map(|d| {
            if let ast::Decl::Tool { name, params, return_type, .. } = d {
                Some((name.as_str(), params.as_slice(), return_type))
            } else {
                None
            }
        })
        .collect();

    if tools.is_empty() {
        println!("(no typed tools — graph requires MCP source)");
        return;
    }

    // Name column width.
    let name_w = tools.iter().map(|(n, _, _)| n.len()).max().unwrap_or(8).max(8);
    // Sig column width — cap at 36 for readability.
    let sig_w: usize = 36;

    println!("Tool composition graph\n");
    println!("{:<name_w$}  {:<sig_w$}  feeds →", "tool", "signature");
    println!("{}", "".repeat(name_w + 2 + sig_w + 2 + 40));

    for &(src_name, src_params, src_ret) in &tools {
        let sig = tool_sig_str(src_params, src_ret);
        // The "output" is the ok branch of R, or the type itself.
        let out_ty = tool_ok_type(src_ret);

        // Find tools whose first param (or any param) accepts out_ty.
        let mut consumers: Vec<&str> = tools
            .iter()
            .filter(|&&(dst_name, dst_params, _)| {
                dst_name != src_name
                    && dst_params.iter().any(|p| types_pipe_compatible(out_ty, &p.ty))
            })
            .map(|&(n, _, _)| n)
            .collect();
        consumers.sort();

        let feeds = if consumers.is_empty() {
            "".to_string()
        } else {
            consumers.join(", ")
        };

        let sig_char_len = sig.chars().count();
        let sig_display = if sig_char_len > sig_w {
            let truncated: String = sig.chars().take(sig_w.saturating_sub(1)).collect();
            format!("{}", truncated)
        } else {
            sig
        };
        println!("{:<name_w$}  {:<sig_w$}  {}", src_name, sig_display, feeds);
    }
    println!();
}

/// Unwrap `R ok err` → `ok`; otherwise return the type itself.
fn tool_ok_type(ty: &ast::Type) -> &ast::Type {
    if let ast::Type::Result(ok, _) = ty { ok } else { ty }
}

/// True if a value of type `out` can be piped into a parameter of type `param`.
/// Intentionally permissive: unknown/named types match anything.
fn types_pipe_compatible(out: &ast::Type, param: &ast::Type) -> bool {
    use ast::Type::*;
    // Unwrap Optional on the param side — Optional(T) accepts T.
    let param = if let Optional(inner) = param { inner } else { param };
    match (out, param) {
        // Named / unknown types — treat as wildcard.
        (Named(_), _) | (_, Named(_)) => true,
        // Exact matches.
        (Number, Number) | (Text, Text) | (Bool, Bool) | (Nil, Nil) => true,
        // List element type must match.
        (List(a), List(b)) => types_pipe_compatible(a, b),
        // Map — key and value types must match.
        (Map(ak, av), Map(bk, bv)) => {
            types_pipe_compatible(ak, bk) && types_pipe_compatible(av, bv)
        }
        // Result ok branch feeds a result-accepting param.
        (Result(ao, ae), Result(bo, be)) => {
            types_pipe_compatible(ao, bo) && types_pipe_compatible(ae, be)
        }
        // Sum types are text at runtime — compatible with text params.
        (Sum(_), Text) | (Text, Sum(_)) | (Sum(_), Sum(_)) => true,
        _ => false,
    }
}

/// Format params + return type as a human-readable signature string.
fn tool_sig_str(params: &[ast::Param], ret: &ast::Type) -> String {
    let ps: Vec<String> = params
        .iter()
        .map(|p| format!("{}:{}", p.name, codegen::fmt::type_str(&p.ty)))
        .collect();
    if ps.is_empty() {
        format!("> {}", codegen::fmt::type_str(ret))
    } else {
        format!("{} > {}", ps.join(" "), codegen::fmt::type_str(ret))
    }
}

/// Connect to MCP servers and return synthesized `Decl::Tool` nodes.
/// Exits with error if `tools` feature is not enabled and a path is given.
#[cfg(feature = "tools")]
fn collect_mcp_tool_decls(path: Option<&str>) -> Vec<ast::Decl> {
    let path = match path {
        Some(p) => p,
        None => return vec![],
    };
    let config = tools::mcp_provider::McpConfig::from_file(path).unwrap_or_else(|e| {
        eprintln!("{}", e);
        std::process::exit(1);
    });
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    let provider = rt
        .block_on(tools::mcp_provider::McpProvider::connect(&config))
        .unwrap_or_else(|e| {
            eprintln!("MCP error: {}", e);
            std::process::exit(1);
        });
    provider.tool_decls()
}

#[cfg(not(feature = "tools"))]
fn collect_mcp_tool_decls(path: Option<&str>) -> Vec<ast::Decl> {
    if path.is_some() {
        eprintln!(
            "error: --mcp requires the 'tools' feature \
             (build with: cargo build --features tools)"
        );
        std::process::exit(1);
    }
    vec![]
}

// ── `ilo serv` subcommand ──────────────────────────────────────────────────

/// Render a `Diagnostic` as a `serde_json::Value` for inclusion in serve responses.
fn diag_to_json(d: &Diagnostic) -> serde_json::Value {
    let s = diagnostic::json::render(d);
    serde_json::from_str(&s).unwrap_or(serde_json::json!({"message": s}))
}

/// Process a single serve request line and return the JSON response.
fn process_serv_request(
    line: &str,
    mcp_tool_decls: &[ast::Decl],
    #[cfg(feature = "tools")] provider: Option<std::sync::Arc<dyn tools::ToolProvider>>,
    #[cfg_attr(not(feature = "tools"), allow(unused_variables))]
    http_config: Option<&tools::http_provider::ToolsConfig>,
    #[cfg(feature = "tools")] rt: std::sync::Arc<tokio::runtime::Runtime>,
) -> serde_json::Value {
    #[derive(serde::Deserialize)]
    struct Req {
        program: String,
        #[serde(default)]
        args: Vec<String>,
        func: Option<String>,
    }

    let req: Req = match serde_json::from_str(line) {
        Ok(r) => r,
        Err(e) => {
            return serde_json::json!({
                "error": {"phase": "request", "message": format!("invalid JSON: {e}")}
            })
        }
    };

    let start = std::time::Instant::now();
    let source = req.program.clone();

    // Lex
    let tokens = match lexer::lex(&source) {
        Ok(t) => t,
        Err(e) => {
            return serde_json::json!({
                "error": {
                    "phase": "lex",
                    "diagnostics": [diag_to_json(&Diagnostic::from(&e))]
                }
            })
        }
    };

    // Parse
    let token_spans: Vec<_> = tokens
        .into_iter()
        .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
        .collect();
    let (mut program, parse_errors) = parser::parse(token_spans);
    program.source = Some(source.clone());

    if !parse_errors.is_empty() {
        let diags: Vec<_> =
            parse_errors.iter().map(|e| diag_to_json(&Diagnostic::from(e))).collect();
        return serde_json::json!({"error": {"phase": "parse", "diagnostics": diags}});
    }

    // Inject static MCP tool decls so the verifier sees them
    if !mcp_tool_decls.is_empty() {
        let mut decls = mcp_tool_decls.to_vec();
        decls.append(&mut program.declarations);
        program.declarations = decls;
    }

    // Verify
    let vr = verify::verify(&program);
    if !vr.errors.is_empty() {
        let diags: Vec<_> = vr
            .errors
            .iter()
            .map(|e| diag_to_json(&Diagnostic::from(e).with_source(source.clone())))
            .collect();
        return serde_json::json!({"error": {"phase": "verify", "diagnostics": diags}});
    }

    // Run
    let run_args: Vec<interpreter::Value> =
        req.args.iter().map(|a| parse_cli_arg(a)).collect();
    let func_name = req.func.as_deref();

    #[cfg(feature = "tools")]
    let result = if let Some(p) = provider {
        interpreter::run_with_tools(&program, func_name, run_args, p, rt)
    } else if let Some(cfg) = http_config {
        let p = std::sync::Arc::new(tools::http_provider::HttpProvider::new(cfg.clone()));
        interpreter::run_with_tools(&program, func_name, run_args, p, rt)
    } else {
        interpreter::run(&program, func_name, run_args)
    };

    #[cfg(not(feature = "tools"))]
    let result = interpreter::run(&program, func_name, run_args);

    let ms = start.elapsed().as_millis() as u64;

    match result {
        Ok(value) => match value {
            interpreter::Value::Ok(inner) => {
                let v = inner.to_json().unwrap_or(serde_json::Value::Null);
                serde_json::json!({"ok": v, "ms": ms})
            }
            interpreter::Value::Err(inner) => {
                let v = inner.to_json().unwrap_or_else(|_| {
                    serde_json::Value::String(inner.to_string())
                });
                serde_json::json!({"error": {"phase": "program", "value": v}, "ms": ms})
            }
            other => {
                let v = other.to_json().unwrap_or_else(|_| {
                    serde_json::Value::String(other.to_string())
                });
                serde_json::json!({"ok": v, "ms": ms})
            }
        },
        Err(e) => {
            let d = Diagnostic::from(&e).with_source(source);
            serde_json::json!({"error": {"phase": "runtime", "diagnostics": [diag_to_json(&d)]}})
        }
    }
}

fn type_to_ilo(ty: &ast::Type) -> String {
    match ty {
        ast::Type::Number => "n".to_string(),
        ast::Type::Text => "t".to_string(),
        ast::Type::Bool => "b".to_string(),
        ast::Type::Nil => "_".to_string(),
        ast::Type::Optional(inner) => format!("O {}", type_to_ilo(inner)),
        ast::Type::List(inner) => format!("L {}", type_to_ilo(inner)),
        ast::Type::Map(k, v) => format!("M {} {}", type_to_ilo(k), type_to_ilo(v)),
        ast::Type::Result(ok, err) => format!("R {} {}", type_to_ilo(ok), type_to_ilo(err)),
        ast::Type::Sum(variants) => format!("S {}", variants.join(" ")),
        ast::Type::Fn(params, ret) => {
            let ps: Vec<_> = params.iter().map(type_to_ilo).collect();
            format!("F {} {}", ps.join(" "), type_to_ilo(ret))
        }
        ast::Type::Named(name) => name.clone(),
    }
}

/// Interactive REPL — define functions, evaluate expressions, accumulate state.
fn repl_cmd() {
    use std::io::{BufRead, Write};

    let version = env!("CARGO_PKG_VERSION");
    let renderer = AnsiRenderer { use_color: true };
    println!("ilo {version} — type :help for commands, :q to quit\n");

    // Accumulated function definitions across the session
    let mut defs: Vec<String> = Vec::new();

    let stdin = std::io::stdin();
    let mut reader = stdin.lock();

    loop {
        print!("> ");
        std::io::stdout().flush().ok();

        let mut line = String::new();
        match reader.read_line(&mut line) {
            Ok(0) => break, // Ctrl+D / EOF
            Ok(_) => {}
            Err(_) => break,
        }

        let input = line.trim();
        if input.is_empty() {
            continue;
        }

        // Meta-commands (nvim-style)
        if input.starts_with(':') {
            match input {
                ":q" | ":q!" | ":x" | ":quit" | ":exit" => break,
                ":wq" => {
                    if defs.is_empty() {
                        eprintln!("no definitions to save");
                    } else {
                        eprintln!("usage: :w <file.ilo>");
                    }
                    continue;
                }
                _ if input.starts_with(":wq ") || input.starts_with(":w ") => {
                    let is_wq = input.starts_with(":wq");
                    let path = input.split_once(' ').unwrap().1.trim();
                    if defs.is_empty() {
                        eprintln!("no definitions to save");
                    } else if let Err(e) = std::fs::write(path, defs.join(" ") + "\n") {
                        eprintln!("error: {e}");
                    } else {
                        println!("saved {} definition(s) to {path}", defs.len());
                    }
                    if is_wq { break; } else { continue; }
                }
                ":defs" => {
                    if defs.is_empty() {
                        println!("(no definitions)");
                    } else {
                        for d in &defs {
                            println!("  {d}");
                        }
                    }
                    continue;
                }
                ":clear" => {
                    defs.clear();
                    println!("cleared all definitions");
                    continue;
                }
                ":help" => {
                    println!(":q :q! :x :quit :exit   quit");
                    println!(":w <file>               save definitions to file");
                    println!(":wq <file>              save and quit");
                    println!(":defs                   list defined functions");
                    println!(":clear                  clear all definitions");
                    println!(":help                   show this help");
                    continue;
                }
                _ => {
                    eprintln!("unknown command: {input}  (type :help)");
                    continue;
                }
            }
        }

        // Also support bare "exit"
        if input == "exit" || input == "quit" {
            break;
        }

        // Try to parse input as function definition(s) first
        let source = input.to_string();
        let def_program = {
            let tokens = lexer::lex(&source);
            if let Ok(tokens) = tokens {
                let token_spans: Vec<_> = tokens
                    .into_iter()
                    .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
                    .collect();
                let (program, errors) = parser::parse(token_spans);
                if errors.is_empty()
                    && !program.declarations.is_empty()
                    && program.declarations.iter().all(|d| matches!(d, ast::Decl::Function { .. }))
                {
                    Some(program)
                } else {
                    None
                }
            } else {
                None
            }
        };

        if let Some(program) = def_program {
            defs.push(input.to_string());

            for d in &program.declarations {
                if let ast::Decl::Function { name, params, return_type, .. } = d {
                    let params_str: Vec<_> = params.iter().map(|p| format!("{}:{}", p.name, type_to_ilo(&p.ty))).collect();
                    println!("defined: {}({}) -> {}", name, params_str.join(", "), type_to_ilo(return_type));
                }
            }
            continue;
        }

        // Expression or function call — wrap in a repl function with all accumulated defs
        // Use `repleval` as name (starts with letter, won't collide)
        let full_source = if defs.is_empty() {
            format!("repleval>n;{input}")
        } else {
            format!("{} repleval>n;{input}", defs.join(" "))
        };

        let tokens = match lexer::lex(&full_source) {
            Ok(t) => t,
            Err(e) => {
                let d = Diagnostic::from(&e);
                eprintln!("{}", renderer.render(&d));
                continue;
            }
        };

        let token_spans: Vec<_> = tokens
            .into_iter()
            .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
            .collect();
        let (mut full_program, parse_errors) = parser::parse(token_spans);
        full_program.source = Some(full_source.clone());

        if !parse_errors.is_empty() {
            // Show errors relative to user input, not the wrapper
            for e in &parse_errors {
                let d = Diagnostic::from(e);
                eprintln!("{}", renderer.render(&d));
            }
            continue;
        }

        // Skip type checking for the repl wrapper — just run it
        // This allows expressions of any type to be evaluated
        match interpreter::run(&full_program, Some("repleval"), vec![]) {
            Ok(value) => println!("{value}"),
            Err(e) => {
                let d = Diagnostic::from(&e).with_source(full_source);
                eprintln!("{}", renderer.render(&d));
            }
        }
    }
}

/// Stdio-based agent serve loop.
/// Reads one JSON request per line from stdin, writes one JSON response per line to stdout.
fn serv_cmd(args_slice: &[String]) {
    let mut mcp_path: Option<String> = None;
    let mut http_path: Option<String> = None;

    let mut i = 0;
    while i < args_slice.len() {
        match args_slice[i].as_str() {
            "--mcp" | "-m" => {
                if i + 1 >= args_slice.len() {
                    eprintln!("error: --mcp requires a path");
                    std::process::exit(1);
                }
                mcp_path = Some(args_slice[i + 1].clone());
                i += 2;
            }
            "--tools" | "-t" => {
                if i + 1 >= args_slice.len() {
                    eprintln!("error: --tools requires a path");
                    std::process::exit(1);
                }
                http_path = Some(args_slice[i + 1].clone());
                i += 2;
            }
            "-j" | "--json" => {
                // JSON protocol is always on in repl/serv; flag is a no-op (accepted for alias compat)
                i += 1;
            }
            _ => {
                eprintln!("unknown flag: {}", args_slice[i]);
                eprintln!("Usage: ilo repl [-j] [--mcp <path>] [--tools <path>]");
                std::process::exit(1);
            }
        }
    }

    // Load HTTP config (sync)
    let http_config: Option<tools::http_provider::ToolsConfig> =
        http_path.as_ref().map(|p| {
            tools::http_provider::ToolsConfig::from_file(p).unwrap_or_else(|e| {
                eprintln!("{}", e);
                std::process::exit(1);
            })
        });

    // Create tokio runtime once (used for MCP connect + all tool calls)
    #[cfg(feature = "tools")]
    let rt = std::sync::Arc::new(
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("tokio runtime"),
    );

    // Connect to MCP once, keep provider + static decls alive for all requests
    #[cfg(feature = "tools")]
    let (mcp_tool_decls, mcp_provider_arc): (
        Vec<ast::Decl>,
        Option<std::sync::Arc<dyn tools::ToolProvider>>,
    ) = if let Some(ref path) = mcp_path {
        let config = tools::mcp_provider::McpConfig::from_file(path).unwrap_or_else(|e| {
            eprintln!("{}", e);
            std::process::exit(1);
        });
        let provider =
            rt.block_on(tools::mcp_provider::McpProvider::connect(&config))
                .unwrap_or_else(|e| {
                    eprintln!("MCP error: {}", e);
                    std::process::exit(1);
                });
        let decls = provider.tool_decls();
        (decls, Some(std::sync::Arc::new(provider)))
    } else {
        (vec![], None)
    };

    #[cfg(not(feature = "tools"))]
    let mcp_tool_decls: Vec<ast::Decl> = {
        if mcp_path.is_some() {
            eprintln!(
                "error: --mcp requires the 'tools' feature \
                 (build with: cargo build --features tools)"
            );
            std::process::exit(1);
        }
        vec![]
    };

    // Signal ready
    println!("{}", serde_json::json!({"ready": true}));

    use std::io::BufRead;
    let stdin = std::io::stdin();
    for line in stdin.lock().lines() {
        let line = match line {
            Ok(l) => l,
            Err(e) => {
                eprintln!("stdin read error: {}", e);
                break;
            }
        };
        if line.trim().is_empty() {
            continue;
        }

        let resp = process_serv_request(
            &line,
            &mcp_tool_decls,
            #[cfg(feature = "tools")]
            mcp_provider_arc.as_ref().map(std::sync::Arc::clone),
            http_config.as_ref(),
            #[cfg(feature = "tools")]
            std::sync::Arc::clone(&rt),
        );
        println!("{}", resp);
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum OutputMode {
    Ansi,
    Text,
    Json,
}

/// Scan args for --json/-j, --text/-t, --ansi/-a, --no-hints/-nh.
/// Return (mode, explicit_json, no_hints, remaining_args).
/// Multiple format flags → error + exit(1).
/// `explicit_json` is true only when the user passed --json/-j; auto-detection never sets it.
fn detect_output_mode(args: Vec<String>) -> (OutputMode, bool, bool, Vec<String>) {
    let mut mode: Option<OutputMode> = None;
    let mut remaining = Vec::with_capacity(args.len());
    let mut conflict = false;
    let mut no_hints = false;

    for arg in args {
        match arg.as_str() {
            "--json" | "-j" => {
                if mode.is_some() { conflict = true; } else { mode = Some(OutputMode::Json); }
            }
            "--text" | "-t" => {
                if mode.is_some() { conflict = true; } else { mode = Some(OutputMode::Text); }
            }
            "--ansi" | "-a" => {
                if mode.is_some() { conflict = true; } else { mode = Some(OutputMode::Ansi); }
            }
            "--no-hints" | "-nh" => {
                no_hints = true;
            }
            _ => remaining.push(arg),
        }
    }

    if conflict {
        eprintln!("error: --json, --text, and --ansi are mutually exclusive");
        std::process::exit(1);
    }

    let explicit_json = matches!(mode, Some(OutputMode::Json));

    let resolved = mode.unwrap_or_else(|| {
        // Auto-detect: isatty(stderr) && !NO_COLOR → Ansi; isatty && NO_COLOR → Text; !isatty → Json
        use std::io::IsTerminal;
        let is_tty = std::io::stderr().is_terminal();
        let no_color = std::env::var("NO_COLOR").is_ok();
        if is_tty && !no_color {
            OutputMode::Ansi
        } else if is_tty {
            OutputMode::Text
        } else {
            OutputMode::Json
        }
    });

    (resolved, explicit_json, no_hints, remaining)
}

/// Replace the contents of string literals with spaces, preserving length.
/// `"https://x.com"` → `"               "`. This prevents cross-language pattern
/// detection from matching inside strings (e.g. `//` in URLs).
fn strip_string_contents(source: &str) -> String {
    let mut result = String::with_capacity(source.len());
    let mut in_string = false;
    let mut chars = source.chars().peekable();
    while let Some(c) = chars.next() {
        if in_string {
            if c == '\\' {
                // Escaped character — skip both backslash and next char
                result.push(' ');
                if chars.next().is_some() {
                    result.push(' ');
                }
            } else if c == '"' {
                result.push('"');
                in_string = false;
            } else {
                result.push(' ');
            }
        } else if c == '"' {
            result.push('"');
            in_string = true;
        } else {
            result.push(c);
        }
    }
    result
}

/// Collect idiomatic hints by scanning source text for non-canonical forms.
/// Returns a list of human-readable hint strings.
fn collect_hints(source: &str) -> Vec<String> {
    let mut hints = Vec::new();
    // Hint: == → = saves 1 character
    // Scan for `==` outside string literals (reuse strip_string_contents)
    let stripped = strip_string_contents(source);
    let mut pos = 0;
    let bytes = stripped.as_bytes();
    while pos + 1 < bytes.len() {
        if bytes[pos] == b'=' && bytes[pos + 1] == b'=' {
            hints.push("hint: `==` → `=` saves 1 char (both mean equality in ilo)".to_string());
            break; // one hint per pattern type is enough
        }
        pos += 1;
    }
    hints
}

/// Emit hints to the appropriate output channel.
/// TTY → stderr, JSON → adds to JSON output (caller handles), pipe → nothing.
fn emit_hints(hints: &[String], mode: OutputMode) {
    if hints.is_empty() {
        return;
    }
    match mode {
        OutputMode::Ansi | OutputMode::Text => {
            for hint in hints {
                eprintln!("{hint}");
            }
        }
        OutputMode::Json => {
            // JSON mode: hints go to stderr as JSON array
            let json = serde_json::json!({ "hints": hints });
            eprintln!("{}", json);
        }
    }
}

/// Scan source for common cross-language patterns and emit a single warning if found.
/// Non-fatal — program still attempts to run.
fn warn_cross_language_syntax(source: &str, mode: OutputMode) {
    let patterns: &[(&str, &str)] = &[
        ("&&", "'&&' — ilo uses '&' for AND"),
        ("||", "'||' — ilo uses '|' for OR"),
        ("->", "'->' — ilo uses '>' for return type separator"),
        ("//", "'//' — ilo uses '--' for comments"),
    ];

    // Strip string literal contents so patterns inside "..." don't trigger warnings.
    // This avoids false positives for URLs like "https://example.com".
    let stripped = strip_string_contents(source);

    let details: Vec<&str> = patterns
        .iter()
        .filter(|(pat, _)| stripped.contains(*pat))
        .map(|(_, desc)| *desc)
        .collect();

    if details.is_empty() {
        return;
    }

    let msg = format!(
        "source contains syntax from another language: {}",
        details.join(", ")
    );
    let d = Diagnostic::warning(msg);
    report_diagnostic(&d, mode);
}

/// Return the declared name of a `Decl`, if it has one.
fn decl_name(decl: &ast::Decl) -> Option<&str> {
    match decl {
        ast::Decl::Function { name, .. } => Some(name),
        ast::Decl::Tool { name, .. } => Some(name),
        ast::Decl::TypeDef { name, .. } => Some(name),
        ast::Decl::Alias { name, .. } => Some(name),
        ast::Decl::Use { .. } | ast::Decl::Error { .. } => None,
    }
}

/// Resolve all `Decl::Use` nodes in `decls` recursively, returning a flat
/// merged list with imported declarations prepended and `Use` nodes stripped.
///
/// - `base_dir`: directory of the importing file (used to resolve relative paths).
///   `None` means inline code — `use` is not supported without a file context.
/// - `visited`: canonical paths already in the import chain; circular imports are errors.
/// - `diagnostics`: errors are pushed here (file-not-found, circular, parse failures).
fn resolve_imports(
    decls: Vec<ast::Decl>,
    base_dir: Option<&std::path::Path>,
    visited: &mut std::collections::HashSet<std::path::PathBuf>,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<ast::Decl> {
    let mut result: Vec<ast::Decl> = Vec::new();

    for decl in decls {
        if let ast::Decl::Use { path, only, span } = decl {
            let Some(dir) = base_dir else {
                diagnostics.push(
                    Diagnostic::error("`use` requires a file path context — not supported in inline code")
                        .with_code("ILO-P017")
                        .with_span(span, "here"),
                );
                continue;
            };

            let file_path = dir.join(&path);
            let canonical = match file_path.canonicalize() {
                Ok(c) => c,
                Err(_) => {
                    diagnostics.push(
                        Diagnostic::error(format!("use \"{}\": file not found", path))
                            .with_code("ILO-P017")
                            .with_span(span, "imported here"),
                    );
                    continue;
                }
            };

            if visited.contains(&canonical) {
                diagnostics.push(
                    Diagnostic::error(format!("use \"{}\": circular import", path))
                        .with_code("ILO-P018")
                        .with_span(span, "imported here"),
                );
                continue;
            }

            let source = match std::fs::read_to_string(&canonical) {
                Ok(s) => s,
                Err(e) => {
                    diagnostics.push(
                        Diagnostic::error(format!("use \"{}\": {}", path, e))
                            .with_code("ILO-P017")
                            .with_span(span, "imported here"),
                    );
                    continue;
                }
            };

            let tokens = match lexer::lex(&source) {
                Ok(t) => t,
                Err(e) => {
                    diagnostics.push(Diagnostic::from(&e));
                    continue;
                }
            };

            let token_spans: Vec<(lexer::Token, ast::Span)> = tokens
                .into_iter()
                .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
                .collect();

            let (imported_prog, parse_errors) = parser::parse(token_spans);
            for e in &parse_errors {
                diagnostics.push(Diagnostic::from(e));
            }

            visited.insert(canonical.clone());
            let imported_dir = canonical.parent();
            let imported_decls = resolve_imports(
                imported_prog.declarations,
                imported_dir,
                visited,
                diagnostics,
            );
            visited.remove(&canonical);

            // Apply `only [...]` filter if specified
            let filtered = if let Some(ref names) = only {
                // Warn about any requested names that weren't found
                for name in names {
                    let found = imported_decls.iter().any(|d| decl_name(d) == Some(name.as_str()));
                    if !found {
                        diagnostics.push(
                            Diagnostic::error(format!("use \"{}\": name '{}' not found in imported file", path, name))
                                .with_code("ILO-P019")
                                .with_span(span, "imported here"),
                        );
                    }
                }
                imported_decls
                    .into_iter()
                    .filter(|d| decl_name(d).map(|n| names.iter().any(|s| s == n)).unwrap_or(false))
                    .collect::<Vec<_>>()
            } else {
                imported_decls
            };

            // Prepend imported declarations (so they appear before the importer's own decls)
            result.extend(filtered);
        } else {
            result.push(decl);
        }
    }

    result
}

fn report_diagnostic(d: &Diagnostic, mode: OutputMode) {
    let s = match mode {
        OutputMode::Ansi => AnsiRenderer { use_color: true }.render(d),
        OutputMode::Text => AnsiRenderer { use_color: false }.render(d),
        // JSON mode: one object per line (NDJSON) so multiple errors are parseable.
        OutputMode::Json => format!("{}\n", json::render(d)),
    };
    eprint!("{}", s);
}

/// Load a single env file into the process environment.
/// Lines starting with `#` are comments. Blank lines are skipped.
/// Format: `KEY=VALUE` — no quoting, no variable expansion.
/// Does NOT overwrite variables already set in the environment.
fn load_env_file(path: &str) {
    let Ok(contents) = std::fs::read_to_string(path) else { return };
    for line in contents.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') { continue; }
        if let Some((key, val)) = line.split_once('=') {
            let key = key.trim();
            let val = val.trim();
            if !key.is_empty() && std::env::var(key).is_err() {
                // SAFETY: single-threaded at startup, no concurrent env access
                unsafe { std::env::set_var(key, val) };
            }
        }
    }
}

/// Load `.env.local` then `.env` from the current working directory.
/// `.env.local` takes priority (loaded first; later files don't overwrite).
fn load_dotenv() {
    load_env_file(".env.local");
    load_env_file(".env");
}

fn main() {
    load_dotenv();
    let raw_args: Vec<String> = std::env::args().collect();

    // `ilo tools` is handled before output-mode detection so that --json/--ilo
    // can be used as *tool format* flags without conflicting with error format flags.
    if matches!(raw_args.get(1).map(|s| s.as_str()), Some("tools") | Some("tool")) {
        tools_cmd(&raw_args[2..]);
        std::process::exit(0);
    }

    if matches!(raw_args.get(1).map(|s| s.as_str()), Some("serv") | Some("repl")) {
        let rest: Vec<String> = raw_args[2..].to_vec();
        let is_json = raw_args.get(1).map(|s| s.as_str()) == Some("serv")
            || rest.iter().any(|a| a == "-j" || a == "--json");
        if is_json {
            let mut serv_args = vec!["-j".to_string()];
            serv_args.extend(rest.iter().filter(|a| *a != "-j" && *a != "--json").cloned());
            serv_cmd(&serv_args);
        } else {
            repl_cmd();
        }
        std::process::exit(0);
    }

    let (mode, explicit_json, no_hints, args) = detect_output_mode(raw_args);

    if args.len() < 2 {
        eprintln!("Usage: ilo <file-or-code> [args... | --run func args... | --bench func args... | --emit python]");
        eprintln!("       ilo repl                                  Interactive REPL");
        eprintln!("       ilo serv [--mcp <path>] [--tools <path>]  Stdio agent loop");
        eprintln!("       ilo help | -h     Show usage and examples");
        eprintln!("       ilo help lang     Show language specification");
        eprintln!("       ilo help ai | -ai Compact spec for LLM consumption");
        std::process::exit(1);
    }

    if args[1] == "--version" || args[1] == "-V" {
        println!("ilo {}", env!("CARGO_PKG_VERSION"));
        std::process::exit(0);
    }

    if args[1] == "--explain" {
        match args.get(2) {
            Some(code) => match diagnostic::registry::lookup(code) {
                Some(entry) => {
                    print!("{}", entry.long);
                    std::process::exit(0);
                }
                None => {
                    eprintln!("unknown error code: {code}");
                    eprintln!("Error codes have the form ILO-L001, ILO-P001, ILO-T001, ILO-R001.");
                    std::process::exit(1);
                }
            },
            None => {
                eprintln!("Usage: ilo --explain <code>  (e.g. ilo --explain ILO-T005)");
                std::process::exit(1);
            }
        }
    }

    if args[1] == "-ai" {
        print!("{}", compact_spec());
        std::process::exit(0);
    }

    if args[1] == "help" || args[1] == "--help" || args[1] == "-h" {
        if args.len() > 2 && args[2] == "lang" {
            print!("{}", include_str!("../SPEC.md"));
        } else if args.len() > 2 && args[2] == "ai" {
            print!("{}", compact_spec());
        } else {
            println!("ilo — a programming language for AI agents\n");
            println!("Usage:");
            println!("  ilo <code> [args...]              Run (Cranelift JIT, falls back to interpreter)");
            println!("  ilo <file.ilo> [args...]          Run from file");
            println!("  ilo <code> func [args...]         Run a specific function");
            println!("  ilo <code> --emit python          Transpile to Python");
            println!("  ilo <code> --explain / -x            Annotate each statement with its role");
            println!("  ilo <code> --dense / -d             Reformat (dense wire format)");
            println!("  ilo <code> --expanded / -e          Reformat (expanded human format)");
            println!("  ilo <code>                        Print AST as JSON (no args)");
            println!("  ilo <code> --bench func [args...] Benchmark a function");
            println!("  ilo repl                          Interactive REPL");
            println!("  ilo help lang                     Show language specification");
            println!("  ilo help ai | ilo -ai             Compact spec for LLM consumption");
            println!("  ilo --explain ILO-T005            Explain an error code\n");
            println!("Output format (errors):");
            println!("  --ansi / -a   Force ANSI colour output (default when stderr is a TTY)");
            println!("  --text / -t   Force plain text output (no colour)");
            println!("  --json / -j   Force JSON output (default when stderr is not a TTY)");
            println!("  --no-hints / -nh  Suppress idiomatic hints after execution");
            println!("  NO_COLOR=1    Disable colour (same as --text)\n");
            println!("Tool providers (requires --features tools build):");
            println!("  --tools <path>   HTTP tool provider config (JSON)");
            println!("  --mcp <path>     MCP server config (Claude Desktop format JSON)\n");
            println!("Tool discovery:");
            println!("  ilo tool -m <path>              List tools from MCP server");
            println!("  ilo tool -t <path>              List tools from HTTP config");
            println!("  ilo tool ... --full             Show full signatures");
            println!("  ilo tool ... --ilo              Output as valid ilo tool declarations");
            println!("  ilo tool ... --json             Output as JSON array\n");
            println!("Agent serve loop:");
            println!("  ilo serv [-m <path>] [-t <path>]");
            println!("  Request:  {{\"program\": \"<ilo>\", \"args\": [...], \"func\": \"name\"}}");
            println!("  Response: {{\"ok\": <value>, \"ms\": n}} | {{\"error\": {{\"phase\": \"...\", ...}}}}\n");
            println!("Backends:");
            println!("  (default)        Cranelift JIT → interpreter fallback");
            println!("  --run-interp     Tree-walking interpreter");
            println!("  --run-vm         Register VM");
            println!("  --run-cranelift  Cranelift JIT");
            println!("  --run-jit        Custom ARM64 JIT (macOS Apple Silicon only)");
            println!("  --run-llvm       LLVM JIT (requires --features llvm build)\n");
            println!("Examples:");
            println!("  ilo 'f x:n>n;*x 2' 5             Define and call f(5) → 10");
            println!("  ilo 'f xs:L n>n;len xs' 1,2,3     Pass a list → 3");
            println!("  ilo program.ilo 10 20             Run file with arguments");
            println!("  ilo 'f x:n>n;*x 2' --emit python Transpile to Python");
        }
        std::process::exit(0);
    }

    // If args[1] is a file that exists, read it. Otherwise treat it as inline code.
    let (source, mode_args_start) = if std::path::Path::new(&args[1]).is_file() {
        let s = match std::fs::read_to_string(&args[1]) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Error reading {}: {}", args[1], e);
                std::process::exit(1);
            }
        };
        (s, 2)
    } else if args[1] == "-e" {
        // Legacy -e flag: skip it, use args[2] as code
        if args.len() < 3 || args[2].is_empty() {
            eprintln!("Usage: ilo <file-or-code> [args... | --run func args... | --emit python]");
            std::process::exit(1);
        }
        (args[2].clone(), 3)
    } else {
        let code = &args[1];
        if code.is_empty() {
            eprintln!("Error: empty code string");
            std::process::exit(1);
        }
        (code.clone(), 2)
    };

    // Scan for --tools <path> and --mcp <path>.
    // Remove both flags+values from args so downstream dispatch doesn't see them.
    let (tools_config_path, mcp_config_path, args) = {
        let mut tools_path: Option<String> = None;
        let mut mcp_path: Option<String> = None;
        let mut filtered: Vec<String> = Vec::with_capacity(args.len());
        let mut i = 0;
        while i < args.len() {
            if args[i] == "--tools" {
                if i + 1 < args.len() {
                    tools_path = Some(args[i + 1].clone());
                    i += 2;
                } else {
                    eprintln!("error: --tools requires a path argument");
                    std::process::exit(1);
                }
            } else if args[i] == "--mcp" {
                if i + 1 < args.len() {
                    mcp_path = Some(args[i + 1].clone());
                    i += 2;
                } else {
                    eprintln!("error: --mcp requires a path argument");
                    std::process::exit(1);
                }
            } else {
                filtered.push(args[i].clone());
                i += 1;
            }
        }
        if tools_path.is_some() && mcp_path.is_some() {
            eprintln!("error: --tools and --mcp are mutually exclusive");
            std::process::exit(1);
        }
        (tools_path, mcp_path, filtered)
    };

    warn_cross_language_syntax(&source, mode);

    let tokens = match lexer::lex(&source) {
        Ok(t) => t,
        Err(e) => {
            report_diagnostic(&Diagnostic::from(&e).with_source(source.clone()), mode);
            std::process::exit(1);
        }
    };

    let token_spans: Vec<(lexer::Token, ast::Span)> = tokens
        .into_iter()
        .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
        .collect();

    let (mut program, parse_errors) = parser::parse(token_spans);
    program.source = Some(source.clone());

    // If --mcp was provided, connect to the MCP servers and inject synthesized
    // Decl::Tool nodes into the program before the verifier runs.
    // This requires the `tools` feature (tokio process + async runtime).
    #[cfg(not(feature = "tools"))]
    if mcp_config_path.is_some() {
        eprintln!("error: --mcp requires the 'tools' feature (build with: cargo build --features tools)");
        std::process::exit(1);
    }

    #[cfg(feature = "tools")]
    let mut mcp_rt: Option<tokio::runtime::Runtime> = None;
    #[cfg(feature = "tools")]
    let mut mcp_provider_holder: Option<tools::mcp_provider::McpProvider> = None;

    #[cfg(feature = "tools")]
    if let Some(ref path) = mcp_config_path {
        let config = tools::mcp_provider::McpConfig::from_file(path)
            .unwrap_or_else(|e| { eprintln!("{}", e); std::process::exit(1); });
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("tokio runtime");
        let provider = rt
            .block_on(tools::mcp_provider::McpProvider::connect(&config))
            .unwrap_or_else(|e| { eprintln!("MCP error: {}", e); std::process::exit(1); });
        // Prepend synthesized Decl::Tool nodes so the verifier sees them
        let mut decls = provider.tool_decls();
        decls.append(&mut program.declarations);
        program.declarations = decls;
        mcp_rt = Some(rt);
        mcp_provider_holder = Some(provider);
    }

    let mut had_errors = false;

    // Resolve `use "..."` imports — must happen before verification.
    // base_dir is the directory of the source file (None for inline code).
    {
        let base_dir: Option<std::path::PathBuf> = if std::path::Path::new(&args[1]).is_file() {
            std::path::Path::new(&args[1])
                .canonicalize()
                .ok()
                .and_then(|p| p.parent().map(|d| d.to_path_buf()))
        } else {
            None
        };
        let mut import_diagnostics: Vec<Diagnostic> = Vec::new();
        let mut visited = std::collections::HashSet::new();
        // Mark the main file as visited to catch direct self-imports
        if let Ok(canonical_file) = std::path::Path::new(&args[1]).canonicalize() {
            visited.insert(canonical_file);
        }
        program.declarations = resolve_imports(
            program.declarations,
            base_dir.as_deref(),
            &mut visited,
            &mut import_diagnostics,
        );
        for d in import_diagnostics {
            report_diagnostic(&d, mode);
            had_errors = true;
        }
    }

    for e in &parse_errors {
        report_diagnostic(&Diagnostic::from(e).with_source(source.clone()), mode);
        had_errors = true;
    }

    // Always run the verifier — it skips Decl::Error poison nodes and reports
    // problems in any functions that did parse successfully.
    let verify_result = verify::verify(&program);
    for w in &verify_result.warnings {
        report_diagnostic(&Diagnostic::from(w).with_source(source.clone()), mode);
    }
    if !verify_result.errors.is_empty() {
        for e in &verify_result.errors {
            report_diagnostic(&Diagnostic::from(e).with_source(source.clone()), mode);
        }
        had_errors = true;
    }

    if had_errors {
        std::process::exit(1);
    }

    // Determine mode from args
    let m = mode_args_start;
    if args.len() > m && args[m] == "--bench" {
        // --bench [func] [args...]
        let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
        let run_args: Vec<interpreter::Value> = if args.len() > m + 2 {
            args[m + 2..].iter().map(|a| parse_cli_arg(a)).collect()
        } else {
            vec![]
        };
        run_bench(&program, func_name, &run_args);
    } else if args.len() > m && matches!(args[m].as_str(), "--explain" | "-x") {
        let filename = if std::path::Path::new(&args[1]).is_file() { Some(args[1].as_str()) } else { None };
        print!("{}", codegen::explain::explain(&program, filename));
    } else if args.len() > m && args[m] == "--emit" {
        if args.len() > m + 1 && args[m + 1] == "python" {
            println!("{}", codegen::python::emit(&program));
        } else {
            eprintln!("Unknown emit target. Supported: python");
            std::process::exit(1);
        }
    } else if args.len() > m && matches!(args[m].as_str(), "--dense" | "-d" | "--fmt") {
        println!("{}", codegen::fmt::format(&program, codegen::fmt::FmtMode::Dense));
    } else if args.len() > m && matches!(args[m].as_str(), "--expanded" | "-e" | "--fmt-expanded") {
        print!("{}", codegen::fmt::format(&program, codegen::fmt::FmtMode::Expanded));
    } else if args.len() > m && args[m] == "--run-jit" {
        // --run-jit [func] [args...] — ARM64 JIT (aarch64 only)
        #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
        {
            let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
            let run_args: Vec<f64> = if args.len() > m + 2 {
                args[m + 2..].iter().map(|a| a.parse::<f64>().expect("JIT args must be numbers")).collect()
            } else {
                vec![]
            };

            let compiled = vm::compile(&program).unwrap_or_else(|e| { eprintln!("Compile error: {}", e); std::process::exit(1); });
            let target = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
            let func_idx = compiled.func_names.iter().position(|n| n == target)
                .unwrap_or_else(|| { eprintln!("undefined function: {}", target); std::process::exit(1); });
            let chunk = &compiled.chunks[func_idx];
            let nan_consts = &compiled.nan_constants[func_idx];

            match vm::jit_arm64::compile_and_call(chunk, nan_consts, &run_args) {
                Some(result) => {
                    if result == (result as i64) as f64 {
                        println!("{}", result as i64);
                    } else {
                        println!("{}", result);
                    }
                }
                None => {
                    eprintln!("JIT: function not eligible for compilation (numeric-only required)");
                    std::process::exit(1);
                }
            }
        }
        #[cfg(not(all(target_arch = "aarch64", target_os = "macos")))]
        {
            eprintln!("Custom JIT (arm64) is only available on aarch64 macOS");
            std::process::exit(1);
        }
    } else if args.len() > m && args[m] == "--run-cranelift" {
        // --run-cranelift [func] [args...]
        #[cfg(feature = "cranelift")]
        {
            let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
            let run_args: Vec<interpreter::Value> = if args.len() > m + 2 {
                args[m + 2..].iter().map(|a| parse_cli_arg(a)).collect()
            } else {
                vec![]
            };

            let compiled = vm::compile(&program).unwrap_or_else(|e| { eprintln!("Compile error: {}", e); std::process::exit(1); });
            let target = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
            let func_idx = compiled.func_names.iter().position(|n| n == target)
                .unwrap_or_else(|| { eprintln!("undefined function: {}", target); std::process::exit(1); });
            let chunk = &compiled.chunks[func_idx];
            let nan_consts = &compiled.nan_constants[func_idx];
            let nan_args: Vec<u64> = run_args.iter().map(|v| vm::NanVal::from_value(v).0).collect();

            match vm::jit_cranelift::compile_and_call(chunk, nan_consts, &nan_args, &compiled) {
                Some(result_bits) => {
                    let result = vm::NanVal(result_bits).to_value();
                    println!("{}", result);
                }
                None => {
                    eprintln!("Cranelift JIT: compilation failed");
                    std::process::exit(1);
                }
            }
        }
        #[cfg(not(feature = "cranelift"))]
        {
            eprintln!("Cranelift JIT not enabled. Build with: cargo build --features cranelift");
            std::process::exit(1);
        }
    } else if args.len() > m && args[m] == "--run-llvm" {
        // --run-llvm [func] [args...]
        #[cfg(feature = "llvm")]
        {
            let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
            let run_args: Vec<f64> = if args.len() > m + 2 {
                args[m + 2..].iter().map(|a| a.parse::<f64>().expect("JIT args must be numbers")).collect()
            } else {
                vec![]
            };

            let compiled = vm::compile(&program).unwrap_or_else(|e| { eprintln!("Compile error: {}", e); std::process::exit(1); });
            let target = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
            let func_idx = compiled.func_names.iter().position(|n| n == target)
                .unwrap_or_else(|| { eprintln!("undefined function: {}", target); std::process::exit(1); });
            let chunk = &compiled.chunks[func_idx];
            let nan_consts = &compiled.nan_constants[func_idx];

            match vm::jit_llvm::compile_and_call(chunk, nan_consts, &run_args) {
                Some(result) => {
                    if result == (result as i64) as f64 {
                        println!("{}", result as i64);
                    } else {
                        println!("{}", result);
                    }
                }
                None => {
                    eprintln!("LLVM JIT: function not eligible for compilation");
                    std::process::exit(1);
                }
            }
        }
        #[cfg(not(feature = "llvm"))]
        {
            eprintln!("LLVM JIT not enabled. Build with: cargo build --features llvm");
            std::process::exit(1);
        }
    } else if args.len() > m && args[m] == "--run-vm" {
        // --run-vm [func] [args...]
        let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
        let run_args: Vec<interpreter::Value> = if args.len() > m + 2 {
            args[m + 2..].iter().map(|a| parse_cli_arg(a)).collect()
        } else {
            vec![]
        };

        let compiled = vm::compile(&program).unwrap_or_else(|e| { eprintln!("Compile error: {}", e); std::process::exit(1); });
        run_vm_with_provider(
            &compiled,
            func_name,
            run_args,
            tools_config_path.as_deref(),
            #[cfg(feature = "tools")]
            mcp_provider_holder.as_ref(),
            #[cfg(feature = "tools")]
            mcp_rt.as_ref(),
            &source,
            mode,
            explicit_json,
        );
    } else if args.len() > m && (args[m] == "--run" || args[m] == "--run-interp") {
        // --run / --run-interp [func] [args...]
        let func_name = if args.len() > m + 1 { Some(args[m + 1].as_str()) } else { None };
        let run_args: Vec<interpreter::Value> = if args.len() > m + 2 {
            args[m + 2..].iter().map(|a| parse_cli_arg(a)).collect()
        } else {
            vec![]
        };

        run_interp_with_provider(
            &program,
            func_name,
            run_args,
            tools_config_path.as_deref(),
            #[cfg(feature = "tools")]
            mcp_provider_holder,
            #[cfg(feature = "tools")]
            mcp_rt,
            &source,
            mode,
            explicit_json,
        );
    } else if args.len() > m {
        // Bare args: default = Cranelift JIT, fall back to interpreter
        let func_names: Vec<&str> = program.declarations.iter().filter_map(|d| match d {
            ast::Decl::Function { name, .. } => Some(name.as_str()),
            _ => None,
        }).collect();

        let (func_name, run_args_start) = if func_names.contains(&args[m].as_str()) {
            (Some(args[m].as_str()), m + 1)
        } else {
            (None, m)
        };

        let run_args: Vec<interpreter::Value> = args[run_args_start..].iter().map(|a| parse_cli_arg(a)).collect();
        run_default(&program, func_name, run_args, &source, mode, explicit_json);
    } else {
        // No args: AST JSON
        match serde_json::to_string_pretty(&program) {
            Ok(json) => println!("{}", json),
            Err(e) => {
                eprintln!("Serialization error: {}", e);
                std::process::exit(1);
            }
        }
    }

    // Emit idiomatic hints after successful execution
    if !no_hints {
        let hints = collect_hints(&source);
        emit_hints(&hints, mode);
    }
}

/// Dispatch --run-vm, routing to MCP / HTTP / plain run based on available providers.
#[allow(clippy::too_many_arguments)]
fn run_vm_with_provider(
    compiled: &vm::CompiledProgram,
    func_name: Option<&str>,
    args: Vec<interpreter::Value>,
    tools_config_path: Option<&str>,
    #[cfg(feature = "tools")] mcp_provider: Option<&tools::mcp_provider::McpProvider>,
    #[cfg(feature = "tools")] mcp_rt: Option<&tokio::runtime::Runtime>,
    source: &str,
    mode: OutputMode,
    explicit_json: bool,
) {
    #[cfg(feature = "tools")]
    if let Some(provider) = mcp_provider {
        let rt = mcp_rt.expect("runtime present with mcp_provider");
        match vm::run_with_tools(compiled, func_name, args, provider, rt) {
            Ok(val) => { print_value(&val, explicit_json); return; }
            Err(e) => {
                report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
                std::process::exit(1);
            }
        }
    }

    if let Some(tools_path) = tools_config_path {
        let config = tools::http_provider::ToolsConfig::from_file(tools_path)
            .unwrap_or_else(|e| { eprintln!("{}", e); std::process::exit(1); });
        let provider = tools::http_provider::HttpProvider::new(config);
        #[cfg(feature = "tools")]
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("tokio runtime");
        match vm::run_with_tools(
            compiled,
            func_name,
            args,
            &provider,
            #[cfg(feature = "tools")]
            &runtime,
        ) {
            Ok(val) => print_value(&val, explicit_json),
            Err(e) => {
                report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
                std::process::exit(1);
            }
        }
        return;
    }

    match vm::run(compiled, func_name, args) {
        Ok(val) => print_value(&val, explicit_json),
        Err(e) => {
            report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
            std::process::exit(1);
        }
    }
}

/// Dispatch --run-interp, routing to MCP / HTTP / plain run based on available providers.
#[allow(clippy::too_many_arguments)]
fn run_interp_with_provider(
    program: &ast::Program,
    func_name: Option<&str>,
    args: Vec<interpreter::Value>,
    tools_config_path: Option<&str>,
    #[cfg(feature = "tools")] mcp_provider: Option<tools::mcp_provider::McpProvider>,
    #[cfg(feature = "tools")] mcp_rt: Option<tokio::runtime::Runtime>,
    source: &str,
    mode: OutputMode,
    explicit_json: bool,
) {
    #[cfg(feature = "tools")]
    if let Some(provider) = mcp_provider {
        let rt = std::sync::Arc::new(mcp_rt.expect("runtime present with mcp_provider"));
        match interpreter::run_with_tools(program, func_name, args, std::sync::Arc::new(provider), rt) {
            Ok(val) => { print_value(&val, explicit_json); return; }
            Err(e) => {
                report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
                std::process::exit(1);
            }
        }
    }

    if let Some(tools_path) = tools_config_path {
        let config = tools::http_provider::ToolsConfig::from_file(tools_path)
            .unwrap_or_else(|e| { eprintln!("{}", e); std::process::exit(1); });
        let provider = std::sync::Arc::new(tools::http_provider::HttpProvider::new(config));
        #[cfg(feature = "tools")]
        let runtime = std::sync::Arc::new(tokio::runtime::Builder::new_current_thread().enable_all().build().expect("tokio runtime"));
        match interpreter::run_with_tools(
            program,
            func_name,
            args,
            provider,
            #[cfg(feature = "tools")]
            runtime,
        ) {
            Ok(val) => print_value(&val, explicit_json),
            Err(e) => {
                report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
                std::process::exit(1);
            }
        }
        return;
    }

    match interpreter::run(program, func_name, args) {
        Ok(val) => print_value(&val, explicit_json),
        Err(e) => {
            report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
            std::process::exit(1);
        }
    }
}

fn run_default(program: &ast::Program, func_name: Option<&str>, args: Vec<interpreter::Value>, source: &str, mode: OutputMode, explicit_json: bool) {
    // Try Cranelift JIT first — all functions are now eligible
    #[cfg(feature = "cranelift")]
    {
        if let Ok(compiled) = vm::compile(program) {
            let target = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
            if let Some(func_idx) = compiled.func_names.iter().position(|n| n == target) {
                let chunk = &compiled.chunks[func_idx];
                let nan_consts = &compiled.nan_constants[func_idx];
                let nan_args: Vec<u64> = args.iter().map(|v| vm::NanVal::from_value(v).0).collect();
                if let Some(result_bits) = vm::jit_cranelift::compile_and_call(chunk, nan_consts, &nan_args, &compiled) {
                    let result = vm::NanVal(result_bits).to_value();
                    print_value(&result, explicit_json);
                    return;
                }
            }
        }
    }

    // Fall back to interpreter
    match interpreter::run(program, func_name, args) {
        Ok(val) => print_value(&val, explicit_json),
        Err(e) => {
            report_diagnostic(&Diagnostic::from(&e).with_source(source.to_string()), mode);
            std::process::exit(1);
        }
    }
}

/// Print a program result value. When `as_json` is true (explicit -j/--json), wraps it as
/// `{"ok": ...}` or `{"error": ...}`. Auto-detected JSON mode does not affect result format.
fn print_value(val: &interpreter::Value, as_json: bool) {
    if !as_json {
        println!("{}", val);
        return;
    }
    let json = match val {
        interpreter::Value::Ok(inner) => {
            let v = inner.to_json().unwrap_or(serde_json::Value::Null);
            serde_json::json!({"ok": v})
        }
        interpreter::Value::Err(inner) => {
            let v = inner
                .to_json()
                .unwrap_or_else(|_| serde_json::Value::String(inner.to_string()));
            serde_json::json!({"error": {"phase": "program", "value": v}})
        }
        other => {
            let v = other
                .to_json()
                .unwrap_or_else(|_| serde_json::Value::String(other.to_string()));
            serde_json::json!({"ok": v})
        }
    };
    println!("{}", json);
}

fn run_bench(program: &ast::Program, func_name: Option<&str>, args: &[interpreter::Value]) {
    use std::time::Instant;
    use std::io::Write;
    use std::process::Command;

    let iterations: u32 = 10_000;

    // -- Rust interpreter benchmark --
    // Warmup
    for _ in 0..100 {
        let _ = interpreter::run(program, func_name, args.to_vec());
    }

    let start = Instant::now();
    let mut result = interpreter::Value::Nil;
    for _ in 0..iterations {
        result = interpreter::run(program, func_name, args.to_vec()).expect("interpreter error during benchmark");
    }
    let interp_dur = start.elapsed();
    let interp_ns = interp_dur.as_nanos() / iterations as u128;

    println!("Rust interpreter");
    println!("  result:     {}", result);
    println!("  iterations: {}", iterations);
    println!("  total:      {:.2}ms", interp_dur.as_nanos() as f64 / 1e6);
    println!("  per call:   {}ns", interp_ns);
    println!();

    // -- Register VM benchmark --
    let compiled = vm::compile(program).expect("compile error in benchmark");
    // Warmup
    for _ in 0..100 {
        let _ = vm::run(&compiled, func_name, args.to_vec());
    }

    let start = Instant::now();
    let mut vm_result = interpreter::Value::Nil;
    for _ in 0..iterations {
        vm_result = vm::run(&compiled, func_name, args.to_vec()).expect("VM error during benchmark");
    }
    let vm_dur = start.elapsed();
    let vm_ns = vm_dur.as_nanos() / iterations as u128;

    println!("Register VM");
    println!("  result:     {}", vm_result);
    println!("  iterations: {}", iterations);
    println!("  total:      {:.2}ms", vm_dur.as_nanos() as f64 / 1e6);
    println!("  per call:   {}ns", vm_ns);
    println!();

    // -- Register VM (reusable) benchmark --
    let call_name = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
    let mut vm_state = vm::VmState::new(&compiled);
    for _ in 0..100 {
        let _ = vm_state.call(call_name, args.to_vec());
    }

    let start = Instant::now();
    for _ in 0..iterations {
        vm_result = vm_state.call(call_name, args.to_vec()).expect("VM reusable error during benchmark");
    }
    let vm_reuse_dur = start.elapsed();
    let vm_reuse_ns = vm_reuse_dur.as_nanos() / iterations as u128;

    println!("Register VM (reusable)");
    println!("  result:     {}", vm_result);
    println!("  iterations: {}", iterations);
    println!("  total:      {:.2}ms", vm_reuse_dur.as_nanos() as f64 / 1e6);
    println!("  per call:   {}ns", vm_reuse_ns);
    println!();

    // -- JIT benchmarks --
    // Extract function info for JIT
    let call_name_jit = func_name.unwrap_or(compiled.func_names.first().map(|s| s.as_str()).unwrap_or("main"));
    let func_idx_jit = compiled.func_names.iter().position(|n| n == call_name_jit);
    let jit_args: Vec<f64> = args.iter().filter_map(|a| match a {
        interpreter::Value::Number(n) => Some(*n),
        _ => None,
    }).collect();
    let all_numeric = jit_args.len() == args.len();

    let mut jit_arm64_ns: Option<u128> = None;
    #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
    if let Some(fi) = func_idx_jit
        && all_numeric {
            let chunk = &compiled.chunks[fi];
            let nan_consts = &compiled.nan_constants[fi];
            if let Some(jit_func) = vm::jit_arm64::compile(chunk, nan_consts) {
                // Warmup
                for _ in 0..100 {
                    let _ = vm::jit_arm64::call(&jit_func, &jit_args);
                }

                let start = Instant::now();
                let mut jit_result = 0.0f64;
                for _ in 0..iterations {
                    jit_result = vm::jit_arm64::call(&jit_func, &jit_args).expect("arm64 JIT error during benchmark");
                }
                let jit_dur = start.elapsed();
                let ns = jit_dur.as_nanos() / iterations as u128;
                jit_arm64_ns = Some(ns);

                println!("Custom JIT (arm64)");
                if jit_result == (jit_result as i64) as f64 {
                    println!("  result:     {}", jit_result as i64);
                } else {
                    println!("  result:     {}", jit_result);
                }
                println!("  iterations: {}", iterations);
                println!("  total:      {:.2}ms", jit_dur.as_nanos() as f64 / 1e6);
                println!("  per call:   {}ns", ns);
                println!();
            }
        }

    let mut jit_cranelift_ns: Option<u128> = None;
    #[cfg(feature = "cranelift")]
    if let Some(fi) = func_idx_jit {
        let chunk = &compiled.chunks[fi];
        let nan_consts = &compiled.nan_constants[fi];
        let nan_args: Vec<u64> = args.iter().map(|v| vm::NanVal::from_value(v).0).collect();
        // SAFETY: `compiled` outlives the entire bench loop below.
        unsafe { vm::set_active_registry(&compiled); }
        if let Some(jit_func) = vm::jit_cranelift::compile(chunk, nan_consts, &compiled) {
            for _ in 0..100 {
                let _ = vm::jit_cranelift::call(&jit_func, &nan_args);
            }

            let start = Instant::now();
            let mut jit_result_bits = 0u64;
            for _ in 0..iterations {
                jit_result_bits = vm::jit_cranelift::call(&jit_func, &nan_args).expect("Cranelift JIT error during benchmark");
            }
            let jit_dur = start.elapsed();
            let ns = jit_dur.as_nanos() / iterations as u128;
            jit_cranelift_ns = Some(ns);

            let jit_result = vm::NanVal(jit_result_bits).to_value();
            println!("Cranelift JIT");
            println!("  result:     {}", jit_result);
            println!("  iterations: {}", iterations);
            println!("  total:      {:.2}ms", jit_dur.as_nanos() as f64 / 1e6);
            println!("  per call:   {}ns", ns);
            println!();
        }
    }

    #[allow(unused_variables)]
    let jit_llvm_ns: Option<u128> = None;
    #[cfg(feature = "llvm")]
    if let Some(fi) = func_idx_jit {
        if all_numeric {
            let chunk = &compiled.chunks[fi];
            let nan_consts = &compiled.nan_constants[fi];
            if let Some(jit_func) = vm::jit_llvm::compile(chunk, nan_consts) {
                for _ in 0..100 {
                    let _ = vm::jit_llvm::call(&jit_func, &jit_args);
                }

                let start = Instant::now();
                let mut jit_result = 0.0f64;
                for _ in 0..iterations {
                    jit_result = vm::jit_llvm::call(&jit_func, &jit_args).expect("LLVM JIT error during benchmark");
                }
                let jit_dur = start.elapsed();
                let ns = jit_dur.as_nanos() / iterations as u128;
                jit_llvm_ns = Some(ns);

                println!("LLVM JIT");
                if jit_result == (jit_result as i64) as f64 {
                    println!("  result:     {}", jit_result as i64);
                } else {
                    println!("  result:     {}", jit_result);
                }
                println!("  iterations: {}", iterations);
                println!("  total:      {:.2}ms", jit_dur.as_nanos() as f64 / 1e6);
                println!("  per call:   {}ns", ns);
                println!();
            }
        }
    }

    // -- Python transpiler benchmark (single invocation) --
    let py_code = codegen::python::emit(program);
    let call_func = func_name.unwrap_or("main").replace('-', "_");
    let call_args: Vec<String> = args.iter().map(|a| match a {
        interpreter::Value::Number(n) => {
            if *n == (*n as i64) as f64 { format!("{}", *n as i64) } else { format!("{}", n) }
        }
        interpreter::Value::Text(s) => format!("\"{}\"", s),
        interpreter::Value::Bool(b) => if *b { "True".to_string() } else { "False".to_string() },
        _ => "None".to_string(),
    }).collect();

    // Python script: prints human-readable lines then a final __NS__=<value> for parsing
    let py_script = format!(
        r#"import time
{code}
_n = {n}
for _ in range(100):
    {func}({args})
_start = time.perf_counter_ns()
for _ in range(_n):
    _r = {func}({args})
_elapsed = time.perf_counter_ns() - _start
_per = _elapsed // _n
print(f"result:     {{_r}}")
print(f"iterations: {{_n}}")
print(f"total:      {{_elapsed / 1e6:.2f}}ms")
print(f"per call:   {{_per}}ns")
print(f"__NS__={{_per}}")
"#,
        code = py_code,
        n = iterations,
        func = call_func,
        args = call_args.join(", ")
    );

    println!("Python transpiled");
    let output = Command::new("python3")
        .arg("-c")
        .arg(&py_script)
        .output();

    let mut py_ns: Option<u128> = None;
    match output {
        Ok(out) => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            for line in stdout.lines() {
                if let Some(val) = line.strip_prefix("__NS__=") {
                    py_ns = val.parse().ok();
                } else {
                    println!("  {}", line);
                }
            }
            std::io::stderr().write_all(&out.stderr).expect("write to stderr");
        }
        Err(e) => eprintln!("  failed to run python3: {}", e),
    }

    println!();

    // -- Summary --
    println!("Summary");
    if vm_ns > 0 && interp_ns > 0 {
        if vm_ns < interp_ns {
            println!("  Register VM is {:.1}x faster than interpreter", interp_ns as f64 / vm_ns as f64);
        } else {
            println!("  Interpreter is {:.1}x faster than bytecode VM", vm_ns as f64 / interp_ns as f64);
        }
    }
    if let Some(jit_ns) = jit_arm64_ns
        && jit_ns > 0 && vm_reuse_ns > 0 {
            println!("  Custom JIT (arm64) is {:.1}x faster than VM (reusable)", vm_reuse_ns as f64 / jit_ns as f64);
        }
    if let Some(jit_ns) = jit_cranelift_ns
        && jit_ns > 0 && vm_reuse_ns > 0 {
            println!("  Cranelift JIT is {:.1}x faster than VM (reusable)", vm_reuse_ns as f64 / jit_ns as f64);
        }
    if let Some(jit_ns) = jit_llvm_ns
        && jit_ns > 0 && vm_reuse_ns > 0 {
            println!("  LLVM JIT is {:.1}x faster than VM (reusable)", vm_reuse_ns as f64 / jit_ns as f64);
        }
    if let Some(py) = py_ns {
        if interp_ns > 0 && py > 0 {
            if interp_ns < py {
                println!("  Rust interpreter is {:.1}x faster than Python", py as f64 / interp_ns as f64);
            } else {
                println!("  Python is {:.1}x faster than Rust interpreter", interp_ns as f64 / py as f64);
            }
        }
        if vm_ns > 0 && py > 0 {
            if vm_ns < py {
                println!("  Register VM is {:.1}x faster than Python", py as f64 / vm_ns as f64);
            } else {
                println!("  Python is {:.1}x faster than Register VM", vm_ns as f64 / py as f64);
            }
        }
        if vm_reuse_ns > 0 && py > 0 {
            if vm_reuse_ns < py {
                println!("  VM (reusable) is {:.1}x faster than Python", py as f64 / vm_reuse_ns as f64);
            } else {
                println!("  Python is {:.1}x faster than VM (reusable)", vm_reuse_ns as f64 / py as f64);
            }
        }
        if let Some(jit_ns) = jit_arm64_ns
            && jit_ns > 0 && py > 0 {
                println!("  Custom JIT (arm64) is {:.1}x faster than Python", py as f64 / jit_ns as f64);
            }
        if let Some(jit_ns) = jit_cranelift_ns
            && jit_ns > 0 && py > 0 {
                println!("  Cranelift JIT is {:.1}x faster than Python", py as f64 / jit_ns as f64);
            }
        if let Some(jit_ns) = jit_llvm_ns
            && jit_ns > 0 && py > 0 {
                println!("  LLVM JIT is {:.1}x faster than Python", py as f64 / jit_ns as f64);
            }
    }
}

fn parse_cli_arg(s: &str) -> interpreter::Value {
    // Bracketed list: [1,2,3] or []
    if s.starts_with('[') && s.ends_with(']') {
        let inner = s[1..s.len()-1].trim();
        if inner.is_empty() {
            return interpreter::Value::List(vec![]);
        }
        let items = inner.split(',').map(|part| parse_cli_arg(part.trim())).collect();
        return interpreter::Value::List(items);
    }
    // Bare comma list: 1,2,3
    if s.contains(',') {
        let items = s.split(',').map(|part| parse_cli_arg(part.trim())).collect();
        return interpreter::Value::List(items);
    }
    if let Ok(n) = s.parse::<f64>()
        && n.is_finite() {
            return interpreter::Value::Number(n);
        }
    if s == "true" {
        interpreter::Value::Bool(true)
    } else if s == "false" {
        interpreter::Value::Bool(false)
    } else {
        interpreter::Value::Text(s.to_string())
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

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

    // ── test helpers ──────────────────────────────────────────────────────────

    fn make_compiled(src: &str) -> vm::CompiledProgram {
        let tokens = lexer::lex(src).unwrap();
        let token_spans: Vec<_> = tokens
            .into_iter()
            .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
            .collect();
        let (program, _) = parser::parse(token_spans);
        vm::compile(&program).unwrap()
    }

    fn make_program(src: &str) -> ast::Program {
        let tokens = lexer::lex(src).unwrap();
        let token_spans: Vec<_> = tokens
            .into_iter()
            .map(|(t, r)| (t, ast::Span { start: r.start, end: r.end }))
            .collect();
        let (mut program, _) = parser::parse(token_spans);
        program.source = Some(src.to_string());
        program
    }

    // Helper: call process_serv_request portably across feature configs.
    fn run_serv(line: &str) -> serde_json::Value {
        #[cfg(not(feature = "tools"))]
        return process_serv_request(line, &[], None);

        #[cfg(feature = "tools")]
        {
            let rt = std::sync::Arc::new(
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap(),
            );
            process_serv_request(line, &[], None, None, rt)
        }
    }

    // ── parse_cli_arg ─────────────────────────────────────────────────────────

    #[test]
    fn cli_arg_integer() {
        assert_eq!(parse_cli_arg("42"), interpreter::Value::Number(42.0));
    }

    #[test]
    fn cli_arg_float() {
        assert_eq!(parse_cli_arg("3.14"), interpreter::Value::Number(3.14));
    }

    #[test]
    fn cli_arg_bool_true() {
        assert_eq!(parse_cli_arg("true"), interpreter::Value::Bool(true));
    }

    #[test]
    fn cli_arg_bool_false() {
        assert_eq!(parse_cli_arg("false"), interpreter::Value::Bool(false));
    }

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

    #[test]
    fn cli_arg_bracketed_list() {
        assert_eq!(
            parse_cli_arg("[1,2,3]"),
            interpreter::Value::List(vec![
                interpreter::Value::Number(1.0),
                interpreter::Value::Number(2.0),
                interpreter::Value::Number(3.0),
            ])
        );
    }

    #[test]
    fn cli_arg_empty_bracketed_list() {
        assert_eq!(parse_cli_arg("[]"), interpreter::Value::List(vec![]));
    }

    #[test]
    fn cli_arg_comma_list() {
        assert_eq!(
            parse_cli_arg("1,2,3"),
            interpreter::Value::List(vec![
                interpreter::Value::Number(1.0),
                interpreter::Value::Number(2.0),
                interpreter::Value::Number(3.0),
            ])
        );
    }

    #[test]
    fn cli_arg_mixed_comma_list() {
        assert_eq!(
            parse_cli_arg("1,hello,true"),
            interpreter::Value::List(vec![
                interpreter::Value::Number(1.0),
                interpreter::Value::Text("hello".into()),
                interpreter::Value::Bool(true),
            ])
        );
    }

    #[test]
    fn cli_arg_infinity_is_text() {
        // inf is not finite so it should fall through to text
        assert_eq!(parse_cli_arg("inf"), interpreter::Value::Text("inf".into()));
    }

    // ── detect_output_mode ────────────────────────────────────────────────────

    #[test]
    fn detect_mode_json_long_flag() {
        let (mode, explicit, _, remaining) =
            detect_output_mode(vec!["--json".into(), "foo".into()]);
        assert!(matches!(mode, OutputMode::Json));
        assert!(explicit);
        assert_eq!(remaining, vec!["foo".to_string()]);
    }

    #[test]
    fn detect_mode_json_short_flag() {
        let (mode, explicit, _, _) = detect_output_mode(vec!["-j".into()]);
        assert!(matches!(mode, OutputMode::Json));
        assert!(explicit);
    }

    #[test]
    fn detect_mode_text_long_flag() {
        let (mode, explicit, _, _) = detect_output_mode(vec!["--text".into()]);
        assert!(matches!(mode, OutputMode::Text));
        assert!(!explicit);
    }

    #[test]
    fn detect_mode_text_short_flag() {
        let (mode, _, _, _) = detect_output_mode(vec!["-t".into()]);
        assert!(matches!(mode, OutputMode::Text));
    }

    #[test]
    fn detect_mode_ansi_long_flag() {
        let (mode, explicit, _, _) = detect_output_mode(vec!["--ansi".into()]);
        assert!(matches!(mode, OutputMode::Ansi));
        assert!(!explicit);
    }

    #[test]
    fn detect_mode_ansi_short_flag() {
        let (mode, _, _, _) = detect_output_mode(vec!["-a".into()]);
        assert!(matches!(mode, OutputMode::Ansi));
    }

    #[test]
    fn detect_mode_non_flag_args_pass_through() {
        let (_, _, _, remaining) =
            detect_output_mode(vec!["ilo".into(), "f>n;1".into(), "42".into()]);
        assert_eq!(remaining, vec!["ilo", "f>n;1", "42"]);
    }

    #[test]
    fn detect_mode_format_flag_stripped_from_remaining() {
        let (_, _, _, remaining) =
            detect_output_mode(vec!["--json".into(), "code".into(), "arg".into()]);
        assert_eq!(remaining, vec!["code", "arg"]);
    }

    #[test]
    fn detect_mode_no_hints_flag() {
        let (_, _, no_hints, _) = detect_output_mode(vec!["--no-hints".into(), "code".into()]);
        assert!(no_hints);
    }

    #[test]
    fn detect_mode_no_hints_short_flag() {
        let (_, _, no_hints, _) = detect_output_mode(vec!["-nh".into(), "code".into()]);
        assert!(no_hints);
    }

    #[test]
    fn detect_mode_no_hints_not_stripped() {
        let (_, _, no_hints, remaining) =
            detect_output_mode(vec!["--no-hints".into(), "code".into()]);
        assert!(no_hints);
        assert_eq!(remaining, vec!["code"]);
    }

    // ── collect_hints ─────────────────────────────────────────────────────────

    #[test]
    fn collect_hints_double_equals() {
        let hints = collect_hints("f x:n y:n>b;==x y");
        assert_eq!(hints.len(), 1);
        assert!(hints[0].contains("=="));
    }

    #[test]
    fn collect_hints_single_equals_no_hint() {
        let hints = collect_hints("f x:n y:n>b;=x y");
        assert!(hints.is_empty());
    }

    #[test]
    fn collect_hints_double_equals_inside_string_no_hint() {
        let hints = collect_hints(r#"f x:s>s;"hello==world""#);
        assert!(hints.is_empty());
    }

    #[test]
    fn collect_hints_no_source_no_hint() {
        let hints = collect_hints("f x:n>n;+x 1");
        assert!(hints.is_empty());
    }

    // ── process_serv_request ─────────────────────────────────────────────────

    #[test]
    fn serv_invalid_json_returns_request_phase() {
        let resp = run_serv("not valid json");
        assert_eq!(resp["error"]["phase"], "request");
    }

    #[test]
    fn serv_parse_error_returns_parse_phase() {
        let resp = run_serv(r#"{"program": "f>n;??invalid"}"#);
        assert_eq!(resp["error"]["phase"], "parse");
    }

    #[test]
    fn serv_verify_error_returns_verify_phase() {
        // x:n>t — returns a number where text is expected → ILO-T005
        let resp = run_serv(r#"{"program": "f x:n>t;x"}"#);
        assert_eq!(resp["error"]["phase"], "verify");
    }

    #[test]
    fn serv_success_simple_number() {
        let resp = run_serv(r#"{"program": "f>n;99"}"#);
        assert!(resp.get("ok").is_some(), "expected ok, got: {resp}");
        assert_eq!(resp["ok"].as_f64(), Some(99.0));
        assert!(resp["ms"].is_number());
    }

    #[test]
    fn serv_success_with_args() {
        let resp = run_serv(r#"{"program": "f x:n>n;*x 2", "args": ["5"], "func": "f"}"#);
        assert!(resp.get("ok").is_some(), "expected ok, got: {resp}");
        assert_eq!(resp["ok"].as_f64(), Some(10.0));
    }

    #[test]
    fn serv_result_err_value_returns_program_phase() {
        // Function returns Err value (not a runtime crash — interpreter returns Ok(Value::Err))
        let resp = run_serv(r#"{"program": "f>R n t;^\"oops\""}"#);
        assert_eq!(resp["error"]["phase"], "program",
            "expected program phase for Err value, got: {resp}");
    }

    #[test]
    fn serv_result_ok_value_unwrapped() {
        let resp = run_serv(r#"{"program": "f>R n t;~42"}"#);
        assert!(resp.get("ok").is_some(), "expected ok, got: {resp}");
        assert_eq!(resp["ok"].as_f64(), Some(42.0));
    }

    #[test]
    fn serv_text_result() {
        let resp = run_serv(r#"{"program": "f>t;\"hello\""}"#);
        assert_eq!(resp["ok"].as_str(), Some("hello"));
    }

    #[test]
    fn serv_with_func_field_selects_function() {
        // Two functions; func field picks second one
        let prog = "{\"program\": \"a>n;1\\nb>n;2\", \"func\": \"b\"}";
        let resp = run_serv(prog);
        assert_eq!(resp["ok"].as_f64(), Some(2.0));
    }

    #[test]
    fn serv_mcp_decls_prepended() {
        // mcp_tool_decls are prepended before verify; an empty slice should still work
        let resp = run_serv(r#"{"program": "f>n;1"}"#);
        assert_eq!(resp["ok"].as_f64(), Some(1.0));
    }

    // ── tool_ok_type ──────────────────────────────────────────────────────────

    #[test]
    fn tool_ok_type_extracts_ok_branch() {
        let ty = ast::Type::Result(
            Box::new(ast::Type::Number),
            Box::new(ast::Type::Text),
        );
        assert!(matches!(tool_ok_type(&ty), ast::Type::Number));
    }

    #[test]
    fn tool_ok_type_passthrough_non_result() {
        assert!(matches!(tool_ok_type(&ast::Type::Text), ast::Type::Text));
        assert!(matches!(tool_ok_type(&ast::Type::Number), ast::Type::Number));
        assert!(matches!(tool_ok_type(&ast::Type::Bool), ast::Type::Bool));
    }

    // ── types_pipe_compatible ─────────────────────────────────────────────────

    #[test]
    fn pipe_compat_same_primitives() {
        assert!(types_pipe_compatible(&ast::Type::Number, &ast::Type::Number));
        assert!(types_pipe_compatible(&ast::Type::Text, &ast::Type::Text));
        assert!(types_pipe_compatible(&ast::Type::Bool, &ast::Type::Bool));
        assert!(types_pipe_compatible(&ast::Type::Nil, &ast::Type::Nil));
    }

    #[test]
    fn pipe_compat_different_primitives_incompatible() {
        assert!(!types_pipe_compatible(&ast::Type::Number, &ast::Type::Text));
        assert!(!types_pipe_compatible(&ast::Type::Bool, &ast::Type::Number));
    }

    #[test]
    fn pipe_compat_named_type_is_wildcard() {
        assert!(types_pipe_compatible(&ast::Type::Named("foo".into()), &ast::Type::Text));
        assert!(types_pipe_compatible(&ast::Type::Text, &ast::Type::Named("bar".into())));
    }

    #[test]
    fn pipe_compat_optional_param_accepts_inner_type() {
        let opt = ast::Type::Optional(Box::new(ast::Type::Number));
        assert!(types_pipe_compatible(&ast::Type::Number, &opt));
    }

    #[test]
    fn pipe_compat_list_checks_element_type() {
        let list_n = ast::Type::List(Box::new(ast::Type::Number));
        let list_t = ast::Type::List(Box::new(ast::Type::Text));
        assert!(types_pipe_compatible(&list_n, &list_n.clone()));
        assert!(!types_pipe_compatible(&list_n, &list_t));
    }

    #[test]
    fn pipe_compat_sum_is_text_compatible() {
        let sum = ast::Type::Sum(vec!["a".into(), "b".into()]);
        assert!(types_pipe_compatible(&sum, &ast::Type::Text));
        assert!(types_pipe_compatible(&ast::Type::Text, &sum));
        assert!(types_pipe_compatible(&sum, &sum.clone()));
    }

    #[test]
    fn pipe_compat_map_checks_key_and_value() {
        let map_nn = ast::Type::Map(Box::new(ast::Type::Text), Box::new(ast::Type::Number));
        let map_nt = ast::Type::Map(Box::new(ast::Type::Text), Box::new(ast::Type::Text));
        assert!(types_pipe_compatible(&map_nn, &map_nn.clone()));
        assert!(!types_pipe_compatible(&map_nn, &map_nt));
    }

    // ── tool_sig_str ──────────────────────────────────────────────────────────

    #[test]
    fn tool_sig_str_no_params() {
        assert_eq!(tool_sig_str(&[], &ast::Type::Number), "> n");
    }

    #[test]
    fn tool_sig_str_one_param() {
        let params = vec![ast::Param { name: "x".into(), ty: ast::Type::Number }];
        assert_eq!(tool_sig_str(&params, &ast::Type::Text), "x:n > t");
    }

    #[test]
    fn tool_sig_str_two_params() {
        let params = vec![
            ast::Param { name: "a".into(), ty: ast::Type::Number },
            ast::Param { name: "b".into(), ty: ast::Type::Text },
        ];
        assert_eq!(tool_sig_str(&params, &ast::Type::Bool), "a:n b:t > b");
    }

    // ── load_env_file ─────────────────────────────────────────────────────────

    #[test]
    fn load_env_file_sets_new_var() {
        use std::io::Write;
        let path = "/tmp/ilo_test_env_load_A7B3.env";
        let key = "ILO_TEST_LOAD_VAR_A7B3";
        // SAFETY: test-only, no concurrent env access
        unsafe { std::env::remove_var(key) };
        std::fs::remove_file(path).ok();

        let mut f = std::fs::File::create(path).unwrap();
        writeln!(f, "# comment line").unwrap();
        writeln!(f).unwrap(); // blank line
        writeln!(f, "{key}=hello_world").unwrap();
        writeln!(f, "  KEY_WITH_SPACES = trimmed  ").unwrap();
        drop(f);

        load_env_file(path);
        assert_eq!(std::env::var(key).unwrap(), "hello_world");

        // SAFETY: test-only, no concurrent env access
        unsafe { std::env::remove_var(key) };
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn load_env_file_does_not_overwrite_existing_var() {
        use std::io::Write;
        let path = "/tmp/ilo_test_env_no_overwrite_C5D1.env";
        let key = "ILO_TEST_NO_OVERWRITE_C5D1";
        // SAFETY: test-only, no concurrent env access
        unsafe { std::env::remove_var(key) };
        unsafe { std::env::set_var(key, "original") };

        let mut f = std::fs::File::create(path).unwrap();
        writeln!(f, "{key}=new_value").unwrap();
        drop(f);

        load_env_file(path);
        assert_eq!(std::env::var(key).unwrap(), "original");

        // SAFETY: test-only, no concurrent env access
        unsafe { std::env::remove_var(key) };
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn load_env_file_missing_file_is_noop() {
        // Should not panic when file doesn't exist
        load_env_file("/tmp/ilo_nonexistent_env_file_X9Z2.env");
    }

    // ── warn_cross_language_syntax ────────────────────────────────────────────

    #[test]
    fn warn_cross_lang_clean_source_no_panic() {
        warn_cross_language_syntax("f x:n>n;*x 2", OutputMode::Text);
    }

    #[test]
    fn warn_cross_lang_detects_double_ampersand() {
        // Should not panic; warning goes to stderr
        warn_cross_language_syntax("f a:b>b;&& a true", OutputMode::Text);
    }

    #[test]
    fn warn_cross_lang_detects_double_pipe() {
        warn_cross_language_syntax("f a:b>b;|| a false", OutputMode::Text);
    }

    #[test]
    fn warn_cross_lang_detects_arrow() {
        warn_cross_language_syntax("f x:n->n;x", OutputMode::Text);
    }

    #[test]
    fn warn_cross_lang_equality_no_longer_warns() {
        // == is now sugar for =, so no cross-language warning
        warn_cross_language_syntax("f x:n>b;== x 1", OutputMode::Text);
        // This should not produce any warning — just a no-op call.
        // (Previously this warned about ==.)
    }

    // ── decl_name ─────────────────────────────────────────────────────────────

    #[test]
    fn decl_name_function_returns_name() {
        let d = ast::Decl::Function {
            name: "myfunc".into(),
            params: vec![],
            return_type: ast::Type::Number,
            body: vec![],
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), Some("myfunc"));
    }

    #[test]
    fn decl_name_use_returns_none() {
        let d = ast::Decl::Use {
            path: "lib.ilo".into(),
            only: None,
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), None);
    }

    #[test]
    fn decl_name_alias_returns_name() {
        let d = ast::Decl::Alias {
            name: "mytype".into(),
            target: ast::Type::Number,
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), Some("mytype"));
    }

    #[test]
    fn decl_name_error_returns_none() {
        let d = ast::Decl::Error {
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), None);
    }

    // ── resolve_imports: `only` filter path ───────────────────────────────────

    #[test]
    fn resolve_imports_only_filter_keeps_named_decl() {
        use std::io::Write;
        let lib_path = "/tmp/ilo_test_resolve_only_F2G7.ilo";
        let mut f = std::fs::File::create(lib_path).unwrap();
        writeln!(f, "dbl n:n>n;*n 2").unwrap();
        writeln!(f, "half n:n>n;/n 2").unwrap();
        drop(f);

        let use_decl = ast::Decl::Use {
            path: "ilo_test_resolve_only_F2G7.ilo".into(),
            only: Some(vec!["dbl".into()]),
            span: ast::Span { start: 0, end: 0 },
        };
        let mut diags = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let result = resolve_imports(
            vec![use_decl],
            Some(std::path::Path::new("/tmp")),
            &mut visited,
            &mut diags,
        );

        let names: Vec<&str> = result.iter().filter_map(|d| decl_name(d)).collect();
        assert!(names.contains(&"dbl"), "expected dbl: {names:?}");
        assert!(!names.contains(&"half"), "half should be filtered: {names:?}");
        assert!(diags.is_empty(), "no errors expected: {diags:?}");

        std::fs::remove_file(lib_path).ok();
    }

    #[test]
    fn resolve_imports_only_filter_warns_missing_name() {
        use std::io::Write;
        let lib_path = "/tmp/ilo_test_resolve_missing_H4K9.ilo";
        let mut f = std::fs::File::create(lib_path).unwrap();
        writeln!(f, "dbl n:n>n;*n 2").unwrap();
        drop(f);

        let use_decl = ast::Decl::Use {
            path: "ilo_test_resolve_missing_H4K9.ilo".into(),
            only: Some(vec!["dbl".into(), "nonexistent".into()]),
            span: ast::Span { start: 0, end: 0 },
        };
        let mut diags = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let _ = resolve_imports(
            vec![use_decl],
            Some(std::path::Path::new("/tmp")),
            &mut visited,
            &mut diags,
        );

        assert!(
            diags.iter().any(|d| d.code.as_deref() == Some("ILO-P019")),
            "expected ILO-P019 for missing name, got: {diags:?}"
        );

        std::fs::remove_file(lib_path).ok();
    }

    // ── diag_to_json ──────────────────────────────────────────────────────────

    #[test]
    fn diag_to_json_simple_error() {
        let d = Diagnostic::error("something went wrong").with_code("ILO-T001");
        let val = diag_to_json(&d);
        assert!(val.is_object());
        let obj = val.as_object().unwrap();
        assert_eq!(obj["code"], "ILO-T001");
        assert!(obj["message"].as_str().unwrap().contains("something went wrong"));
    }

    #[test]
    fn diag_to_json_with_span_and_source() {
        let d = Diagnostic::error("bad token")
            .with_code("ILO-L001")
            .with_span(ast::Span { start: 0, end: 3 }, "here")
            .with_source("abc".to_string());
        let val = diag_to_json(&d);
        assert!(val.is_object());
        assert_eq!(val["severity"], "error");
    }

    // ── types_pipe_compatible: Result and Map branches ────────────────────────

    #[test]
    fn pipe_compat_result_matching() {
        use ast::Type::*;
        let r1 = Result(Box::new(Number), Box::new(Text));
        let r2 = Result(Box::new(Number), Box::new(Text));
        assert!(types_pipe_compatible(&r1, &r2));
    }

    #[test]
    fn pipe_compat_result_mismatched_ok() {
        use ast::Type::*;
        assert!(!types_pipe_compatible(
            &Result(Box::new(Number), Box::new(Text)),
            &Result(Box::new(Text), Box::new(Text)),
        ));
    }

    #[test]
    fn pipe_compat_result_mismatched_err() {
        use ast::Type::*;
        assert!(!types_pipe_compatible(
            &Result(Box::new(Number), Box::new(Text)),
            &Result(Box::new(Number), Box::new(Number)),
        ));
    }

    #[test]
    fn pipe_compat_map_matching() {
        use ast::Type::*;
        let m = Map(Box::new(Text), Box::new(Number));
        assert!(types_pipe_compatible(&m, &m.clone()));
    }

    #[test]
    fn pipe_compat_map_key_mismatch() {
        use ast::Type::*;
        assert!(!types_pipe_compatible(
            &Map(Box::new(Text), Box::new(Number)),
            &Map(Box::new(Number), Box::new(Number)),
        ));
    }

    #[test]
    fn pipe_compat_map_value_mismatch() {
        use ast::Type::*;
        assert!(!types_pipe_compatible(
            &Map(Box::new(Text), Box::new(Number)),
            &Map(Box::new(Text), Box::new(Text)),
        ));
    }

    #[test]
    fn pipe_compat_result_named_wildcard() {
        use ast::Type::*;
        // Named types inside Result act as wildcards
        assert!(types_pipe_compatible(
            &Result(Box::new(Named("T".into())), Box::new(Text)),
            &Result(Box::new(Number), Box::new(Text)),
        ));
    }

    #[test]
    fn pipe_compat_map_named_wildcard() {
        use ast::Type::*;
        assert!(types_pipe_compatible(
            &Map(Box::new(Text), Box::new(Named("V".into()))),
            &Map(Box::new(Text), Box::new(Number)),
        ));
    }

    // ── run_vm_with_provider: success path ────────────────────────────────────

    #[test]
    fn run_vm_with_provider_success_no_tools() {
        let compiled = make_compiled("f x:n>n;*x 2");
        run_vm_with_provider(
            &compiled,
            Some("f"),
            vec![interpreter::Value::Number(5.0)],
            None,
            #[cfg(feature = "tools")] None,
            #[cfg(feature = "tools")] None,
            "f x:n>n;*x 2",
            OutputMode::Text,
            false,
        );
    }

    #[test]
    fn run_vm_with_provider_explicit_json_wraps_ok() {
        let compiled = make_compiled("f x:n>n;*x 3");
        run_vm_with_provider(
            &compiled,
            Some("f"),
            vec![interpreter::Value::Number(4.0)],
            None,
            #[cfg(feature = "tools")] None,
            #[cfg(feature = "tools")] None,
            "f x:n>n;*x 3",
            OutputMode::Json,
            true,
        );
    }

    // ── run_interp_with_provider: success path ────────────────────────────────

    #[test]
    fn run_interp_with_provider_success_no_tools() {
        let program = make_program("f x:n>n;*x 2");
        run_interp_with_provider(
            &program,
            Some("f"),
            vec![interpreter::Value::Number(7.0)],
            None,
            #[cfg(feature = "tools")] None,
            #[cfg(feature = "tools")] None,
            "f x:n>n;*x 2",
            OutputMode::Text,
            false,
        );
    }

    #[test]
    fn run_interp_with_provider_explicit_json() {
        let program = make_program("f x:n>n;+x 1");
        run_interp_with_provider(
            &program,
            Some("f"),
            vec![interpreter::Value::Number(10.0)],
            None,
            #[cfg(feature = "tools")] None,
            #[cfg(feature = "tools")] None,
            "f x:n>n;+x 1",
            OutputMode::Json,
            true,
        );
    }

    // ── run_default: cranelift-then-interpreter dispatch ──────────────────────

    #[test]
    fn run_default_simple_numeric() {
        let program = make_program("f x:n>n;*x 2");
        run_default(&program, Some("f"), vec![interpreter::Value::Number(3.0)],
            "f x:n>n;*x 2", OutputMode::Text, false);
    }

    #[test]
    fn run_default_text_result() {
        let program = make_program("greet name:t>t;cat \"hi \" name");
        run_default(&program, Some("greet"),
            vec![interpreter::Value::Text("world".into())],
            "greet name:t>t;cat \"hi \" name", OutputMode::Text, false);
    }

    #[test]
    fn run_default_none_func_name_uses_first() {
        let program = make_program("double x:n>n;*x 2");
        run_default(&program, None, vec![interpreter::Value::Number(4.0)],
            "double x:n>n;*x 2", OutputMode::Text, false);
    }

    // ── resolve_imports: additional paths ─────────────────────────────────────

    #[test]
    fn resolve_imports_inline_code_emits_p017() {
        let use_decl = ast::Decl::Use {
            path: "something.ilo".into(),
            only: None,
            span: ast::Span { start: 0, end: 20 },
        };
        let mut visited = std::collections::HashSet::new();
        let mut diags = Vec::new();
        let result = resolve_imports(vec![use_decl], None, &mut visited, &mut diags);
        assert!(result.is_empty());
        assert!(diags.iter().any(|d| d.code.as_deref() == Some("ILO-P017")));
        assert!(diags[0].message.contains("inline code"));
    }

    #[test]
    fn resolve_imports_file_not_found_emits_p017() {
        let use_decl = ast::Decl::Use {
            path: "nonexistent_xyz_99999.ilo".into(),
            only: None,
            span: ast::Span { start: 0, end: 30 },
        };
        let mut visited = std::collections::HashSet::new();
        let mut diags = Vec::new();
        let result = resolve_imports(
            vec![use_decl], Some(std::path::Path::new("/tmp")), &mut visited, &mut diags,
        );
        assert!(result.is_empty());
        assert!(diags.iter().any(|d| d.code.as_deref() == Some("ILO-P017")
            && d.message.contains("file not found")));
    }

    #[test]
    fn resolve_imports_non_use_decl_passes_through() {
        let func_decl = ast::Decl::Function {
            name: "f".into(),
            params: vec![],
            return_type: ast::Type::Number,
            body: vec![],
            span: ast::Span { start: 0, end: 0 },
        };
        let mut visited = std::collections::HashSet::new();
        let mut diags = Vec::new();
        let result = resolve_imports(vec![func_decl], None, &mut visited, &mut diags);
        assert_eq!(result.len(), 1);
        assert!(diags.is_empty());
    }

    // ── print_value ───────────────────────────────────────────────────────────

    #[test]
    fn print_value_plain_number_no_json() {
        print_value(&interpreter::Value::Number(42.0), false);
    }

    #[test]
    fn print_value_ok_as_json() {
        let val = interpreter::Value::Ok(Box::new(interpreter::Value::Number(42.0)));
        print_value(&val, true);
    }

    #[test]
    fn print_value_err_as_json() {
        let val = interpreter::Value::Err(Box::new(interpreter::Value::Text("oops".into())));
        print_value(&val, true);
    }

    #[test]
    fn print_value_err_no_json() {
        let val = interpreter::Value::Err(Box::new(interpreter::Value::Text("fail".into())));
        print_value(&val, false);
    }

    #[test]
    fn print_value_text_as_json() {
        print_value(&interpreter::Value::Text("hello".into()), true);
    }

    #[test]
    fn print_value_bool_as_json() {
        print_value(&interpreter::Value::Bool(true), true);
    }

    #[test]
    fn print_value_nil_as_json() {
        print_value(&interpreter::Value::Nil, true);
    }

    #[test]
    fn print_value_list_as_json() {
        let val = interpreter::Value::List(vec![
            interpreter::Value::Number(1.0),
            interpreter::Value::Number(2.0),
        ]);
        print_value(&val, true);
    }

    // ── warn_cross_language_syntax: Json mode ─────────────────────────────────

    #[test]
    fn warn_cross_lang_json_mode() {
        warn_cross_language_syntax("f x:b y:b>b;&& x y", OutputMode::Json);
    }

    #[test]
    fn warn_cross_lang_multiple_patterns_json_mode() {
        // == no longer warns, but -> and // still do
        warn_cross_language_syntax("f x:n->n;== x 1 // check", OutputMode::Json);
    }

    // ── resolve_imports: parse error propagation ──────────────────────────────

    #[test]
    fn resolve_imports_parse_error_in_imported_file() {
        let bad_path = "/tmp/ilo_unit_bad_parse_imports.ilo";
        std::fs::write(bad_path, "f x:>n;x").expect("write bad file");

        let decls = vec![ast::Decl::Use {
            path: "ilo_unit_bad_parse_imports.ilo".into(),
            only: None,
            span: ast::Span { start: 0, end: 0 },
        }];
        let mut visited = std::collections::HashSet::new();
        let mut diags = Vec::new();
        let _ = resolve_imports(decls, Some(std::path::Path::new("/tmp")), &mut visited, &mut diags);

        assert!(!diags.is_empty(), "expected parse error diagnostic from imported file");
        std::fs::remove_file(bad_path).ok();
    }

    // ── resolve_imports: transitive imports ───────────────────────────────────

    #[test]
    fn resolve_imports_transitive() {
        let file_b = "/tmp/ilo_unit_trans_b_Q3R8.ilo";
        let file_a = "/tmp/ilo_unit_trans_a_Q3R8.ilo";

        std::fs::write(file_b, "triple x:n>n;*x 3").expect("write B");
        std::fs::write(file_a, "use \"ilo_unit_trans_b_Q3R8.ilo\"\nsextuple x:n>n;t=triple x;*t 2")
            .expect("write A");

        let decls = vec![ast::Decl::Use {
            path: "ilo_unit_trans_a_Q3R8.ilo".into(),
            only: None,
            span: ast::Span { start: 0, end: 0 },
        }];
        let mut visited = std::collections::HashSet::new();
        let mut diags = Vec::new();
        let result = resolve_imports(decls, Some(std::path::Path::new("/tmp")), &mut visited, &mut diags);

        assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
        let names: Vec<_> = result.iter().filter_map(|d| decl_name(d)).collect();
        assert!(names.contains(&"triple"), "expected triple: {names:?}");
        assert!(names.contains(&"sextuple"), "expected sextuple: {names:?}");

        std::fs::remove_file(file_b).ok();
        std::fs::remove_file(file_a).ok();
    }

    // ── report_diagnostic: all three output modes ─────────────────────────────

    #[test]
    fn report_diagnostic_text_mode_no_panic() {
        let d = Diagnostic::error("test error").with_code("ILO-T001");
        report_diagnostic(&d, OutputMode::Text);
    }

    #[test]
    fn report_diagnostic_ansi_mode_no_panic() {
        let d = Diagnostic::error("ansi error").with_code("ILO-T002");
        report_diagnostic(&d, OutputMode::Ansi);
    }

    #[test]
    fn report_diagnostic_json_mode_no_panic() {
        let d = Diagnostic::error("json error").with_code("ILO-T003");
        report_diagnostic(&d, OutputMode::Json);
    }

    #[test]
    fn report_diagnostic_warning_all_modes_no_panic() {
        let d = Diagnostic::warning("test warning");
        report_diagnostic(&d, OutputMode::Text);
        report_diagnostic(&d, OutputMode::Ansi);
        report_diagnostic(&d, OutputMode::Json);
    }

    // ── decl_name: Tool and TypeDef variants ─────────────────────────────────

    #[test]
    fn decl_name_tool_returns_name() {
        let d = ast::Decl::Tool {
            name: "my_tool".into(),
            description: "does things".into(),
            params: vec![],
            return_type: ast::Type::Text,
            timeout: None,
            retry: None,
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), Some("my_tool"));
    }

    #[test]
    fn decl_name_typedef_returns_name() {
        let d = ast::Decl::TypeDef {
            name: "Point".into(),
            fields: vec![],
            span: ast::Span { start: 0, end: 0 },
        };
        assert_eq!(decl_name(&d), Some("Point"));
    }

    // ── warn_cross_language_syntax: // comment pattern ────────────────────────

    #[test]
    fn warn_cross_lang_detects_double_slash_comment() {
        // '//' outside strings is a foreign-syntax comment; ilo uses '--'
        warn_cross_language_syntax("f x:n>n;// this is a comment", OutputMode::Text);
    }

    #[test]
    fn warn_cross_lang_ignores_slash_in_strings() {
        // '//' inside string literals should NOT trigger the warning
        // (common case: URLs like "https://example.com")
        warn_cross_language_syntax(r#"f>t;"https://example.com""#, OutputMode::Text);
        // No warning emitted — this just verifies no panic and no false positive.
    }

    #[test]
    fn strip_string_contents_preserves_outside() {
        let result = strip_string_contents(r#"abc "hello" def"#);
        assert_eq!(result, r#"abc "     " def"#);
    }

    #[test]
    fn strip_string_contents_handles_escapes() {
        let result = strip_string_contents(r#""a\"b""#);
        assert_eq!(result, r#""    ""#);
    }

    #[test]
    fn strip_string_contents_url() {
        let result = strip_string_contents(r#"get "https://api.com/users""#);
        assert!(!result.contains("//"));
    }

    #[test]
    fn warn_cross_lang_ansi_mode_no_panic() {
        warn_cross_language_syntax("f x:n>n;&& x true", OutputMode::Ansi);
    }

    // ── parse_cli_arg: edge cases ─────────────────────────────────────────────

    #[test]
    fn cli_arg_nan_is_text() {
        // NaN is not finite, so it should fall through to text
        assert_eq!(parse_cli_arg("NaN"), interpreter::Value::Text("NaN".into()));
    }

    #[test]
    fn cli_arg_negative_number() {
        assert_eq!(parse_cli_arg("-5"), interpreter::Value::Number(-5.0));
    }

    // ── load_dotenv: priority ordering ───────────────────────────────────────

    #[test]
    fn load_dotenv_env_local_takes_priority_over_env() {
        // Write two env files in a temp dir, change cwd, call load_dotenv(),
        // verify that .env.local value wins (loaded first; .env cannot overwrite).
        use std::io::Write;

        let dir = "/tmp/ilo_test_load_dotenv_prio_M8N2";
        std::fs::create_dir_all(dir).unwrap();
        let local_path = format!("{dir}/.env.local");
        let env_path = format!("{dir}/.env");
        let key = "ILO_TEST_DOTENV_PRIO_M8N2";

        // SAFETY: test-only, single-threaded env manipulation
        unsafe { std::env::remove_var(key) };

        let mut f = std::fs::File::create(&local_path).unwrap();
        writeln!(f, "{key}=from_local").unwrap();
        drop(f);

        let mut f = std::fs::File::create(&env_path).unwrap();
        writeln!(f, "{key}=from_env").unwrap();
        drop(f);

        // Load both files manually in the same order load_dotenv() would
        load_env_file(&local_path);
        load_env_file(&env_path);

        assert_eq!(
            std::env::var(key).unwrap(),
            "from_local",
            ".env.local should take priority over .env"
        );

        unsafe { std::env::remove_var(key) };
        std::fs::remove_file(&local_path).ok();
        std::fs::remove_file(&env_path).ok();
        std::fs::remove_dir(dir).ok();
    }

    // ── process_serv_request: lex error phase ─────────────────────────────────

    #[test]
    fn serv_lex_error_returns_lex_phase() {
        // A string with an unterminated string literal causes a lex error
        let resp = run_serv(r#"{"program": "f>t;\""}"#);
        // Either lex or parse phase is acceptable depending on how the lexer reports it
        let phase = resp["error"]["phase"].as_str().unwrap_or("");
        assert!(
            phase == "lex" || phase == "parse",
            "expected lex or parse phase for unterminated string, got: {resp}"
        );
    }

    // ── process_serv_request: runtime error phase ────────────────────────────

    #[test]
    fn serv_runtime_error_returns_runtime_phase() {
        // Division by zero passes lex/parse/verify but fails at runtime
        let resp = run_serv(r#"{"program": "f>n;/1 0", "func": "f"}"#);
        assert_eq!(
            resp["error"]["phase"], "runtime",
            "expected runtime phase for division by zero, got: {resp}"
        );
    }

    // ── process_serv_request: mcp_tool_decls prepended ───────────────────────

    #[test]
    fn serv_with_non_empty_mcp_tool_decls_succeed() {
        // Build a synthetic Tool decl that represents an external tool.
        // process_serv_request prepends mcp_tool_decls before verify, so a
        // program that calls the tool should verify and run cleanly IF the
        // stub returns Ok(Nil).  Here we just pass a decl and call a simple
        // function that doesn't use the tool — verifies the prepend path is
        // exercised without a tool call error.
        let tool_decl = ast::Decl::Tool {
            name: "echo_tool".into(),
            description: "echoes input".into(),
            params: vec![ast::Param { name: "msg".into(), ty: ast::Type::Text }],
            return_type: ast::Type::Result(
                Box::new(ast::Type::Text),
                Box::new(ast::Type::Text),
            ),
            timeout: None,
            retry: None,
            span: ast::Span { start: 0, end: 0 },
        };

        let line = r#"{"program": "f>n;42", "func": "f"}"#;

        #[cfg(not(feature = "tools"))]
        let resp = process_serv_request(line, &[tool_decl], None);

        #[cfg(feature = "tools")]
        let resp = {
            let rt = std::sync::Arc::new(
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap(),
            );
            process_serv_request(line, &[tool_decl], None, None, rt)
        };

        assert!(resp.get("ok").is_some(), "expected ok response, got: {resp}");
        assert_eq!(resp["ok"].as_f64(), Some(42.0));
    }

    // ── diag_to_json: warning severity ───────────────────────────────────────

    #[test]
    fn diag_to_json_warning_severity() {
        let d = Diagnostic::warning("suspicious pattern");
        let val = diag_to_json(&d);
        assert!(val.is_object());
        assert_eq!(val["severity"], "warning");
    }

    // ── print_value: remaining branches ──────────────────────────────────────

    #[test]
    fn print_value_list_plain_not_json() {
        let val = interpreter::Value::List(vec![
            interpreter::Value::Number(1.0),
            interpreter::Value::Text("x".into()),
        ]);
        print_value(&val, false);
    }

    #[test]
    fn print_value_map_as_json() {
        let mut m = std::collections::HashMap::new();
        m.insert("k".to_string(), interpreter::Value::Number(7.0));
        let val = interpreter::Value::Map(m);
        print_value(&val, true);
    }

    #[test]
    fn print_value_map_plain_not_json() {
        let mut m = std::collections::HashMap::new();
        m.insert("key".to_string(), interpreter::Value::Bool(true));
        let val = interpreter::Value::Map(m);
        print_value(&val, false);
    }

    // ── subprocess helpers ────────────────────────────────────────────────────

    /// Locate the `ilo` binary that corresponds to the current test profile.
    ///
    /// Unit tests run as `target/<profile>/deps/ilo-<hash>`.  The actual
    /// binary is one directory up, at `target/<profile>/ilo`.
    fn ilo_bin() -> std::path::PathBuf {
        // current_exe() → e.g. /…/target/debug/deps/ilo-abc123
        let exe = std::env::current_exe().expect("current_exe");
        // Go up from deps/ to the profile dir (debug or release)
        let profile_dir = exe
            .parent()          // deps/
            .and_then(|p| p.parent()) // debug/ or release/
            .expect("could not locate profile dir");
        let bin = profile_dir.join("ilo");
        assert!(
            bin.exists(),
            "ilo binary not found at {}; run `cargo build` first",
            bin.display()
        );
        bin
    }

    // ── subprocess: --version ─────────────────────────────────────────────────

    #[test]
    fn cli_version_flag_prints_version() {
        let out = std::process::Command::new(ilo_bin())
            .arg("--version")
            .output()
            .expect("failed to run ilo --version");
        assert!(out.status.success(), "exit status: {}", out.status);
        let stdout = String::from_utf8_lossy(&out.stdout);
        // Should contain a semver-ish version like "0.7.0"
        assert!(
            stdout.contains('.'),
            "expected version number in stdout, got: {stdout}"
        );
        // Should contain the binary name or version token
        assert!(
            stdout.to_lowercase().contains("ilo") || stdout.trim().chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false),
            "expected ilo version string, got: {stdout}"
        );
    }

    // ── subprocess: --explain ─────────────────────────────────────────────────

    #[test]
    fn cli_explain_valid_code_exits_zero_with_text() {
        let out = std::process::Command::new(ilo_bin())
            .args(["--explain", "ILO-T001"])
            .output()
            .expect("failed to run ilo --explain ILO-T001");
        assert!(
            out.status.success(),
            "expected exit 0, got: {}; stderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            !stdout.trim().is_empty(),
            "expected explanation text on stdout, got empty"
        );
    }

    #[test]
    fn cli_explain_unknown_code_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .args(["--explain", "INVALID-CODE"])
            .output()
            .expect("failed to run ilo --explain INVALID-CODE");
        assert!(
            !out.status.success(),
            "expected non-zero exit for unknown code"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("unknown") || stderr.contains("not found"),
            "expected 'unknown' or 'not found' in stderr, got: {stderr}"
        );
    }

    // ── subprocess: help ─────────────────────────────────────────────────────

    #[test]
    fn cli_help_default_exits_zero_with_usage() {
        let out = std::process::Command::new(ilo_bin())
            .arg("help")
            .output()
            .expect("failed to run ilo help");
        assert!(
            out.status.success(),
            "expected exit 0, got: {}; stderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("Usage") || stdout.contains("usage") || stdout.contains("ilo"),
            "expected usage info in stdout, got: {stdout}"
        );
    }

    #[test]
    fn cli_help_lang_exits_zero_with_spec_content() {
        let out = std::process::Command::new(ilo_bin())
            .args(["help", "lang"])
            .output()
            .expect("failed to run ilo help lang");
        assert!(
            out.status.success(),
            "expected exit 0, got: {}; stderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8_lossy(&out.stdout);
        // SPEC.md has ilo language content
        assert!(
            !stdout.trim().is_empty(),
            "expected spec content on stdout, got empty"
        );
    }

    #[test]
    fn cli_help_ai_exits_zero_with_compact_spec() {
        let out = std::process::Command::new(ilo_bin())
            .args(["help", "ai"])
            .output()
            .expect("failed to run ilo help ai");
        assert!(
            out.status.success(),
            "expected exit 0, got: {}; stderr: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            !stdout.trim().is_empty(),
            "expected compact spec on stdout, got empty"
        );
    }

    // ── subprocess: empty code ────────────────────────────────────────────────

    #[test]
    fn cli_empty_code_string_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .arg("")
            .output()
            .expect("failed to run ilo with empty arg");
        // An empty string is not a valid file path and not valid ilo code;
        // the process must exit non-zero.
        assert!(
            !out.status.success(),
            "expected non-zero exit for empty code string"
        );
        // Error should appear on stderr
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !stderr.trim().is_empty(),
            "expected some error on stderr, got empty"
        );
    }

    // ── subprocess: --emit unknown target ─────────────────────────────────────

    #[test]
    fn cli_emit_unknown_target_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .args(["f>n;1", "--emit", "rust"])
            .output()
            .expect("failed to run ilo --emit rust");
        assert!(
            !out.status.success(),
            "expected non-zero exit for unknown emit target"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("Unknown emit") || stderr.contains("Supported") || stderr.contains("python"),
            "expected unknown-emit error in stderr, got: {stderr}"
        );
    }

    // ── subprocess: --tools and --mcp mutually exclusive ─────────────────────

    #[test]
    fn cli_tools_and_mcp_mutually_exclusive() {
        let out = std::process::Command::new(ilo_bin())
            .args(["f>n;1", "--tools", "/tmp/x.json", "--mcp", "/tmp/y.json"])
            .output()
            .expect("failed to run ilo with --tools and --mcp");
        assert!(
            !out.status.success(),
            "expected non-zero exit when both --tools and --mcp are provided"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("mutually exclusive") || stderr.contains("exclusive"),
            "expected 'mutually exclusive' in stderr, got: {stderr}"
        );
    }

    // ── subprocess: tools subcommand ─────────────────────────────────────────

    #[test]
    fn cli_tools_cmd_no_flags_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .arg("tools")
            .output()
            .expect("failed to run ilo tools");
        assert!(
            !out.status.success(),
            "expected non-zero exit for `ilo tools` with no flags"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("--mcp") || stderr.contains("--tools") || stderr.contains("requires"),
            "expected usage hint in stderr, got: {stderr}"
        );
    }

    #[test]
    fn cli_tools_cmd_mcp_no_path_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--mcp"])
            .output()
            .expect("failed to run ilo tools --mcp");
        assert!(
            !out.status.success(),
            "expected non-zero exit for `ilo tools --mcp` with no path"
        );
    }

    // ── subprocess: serv subcommand unknown flag ──────────────────────────────

    #[test]
    fn cli_serv_unknown_flag_exits_nonzero() {
        let out = std::process::Command::new(ilo_bin())
            .args(["serv", "--invalid-flag"])
            .output()
            .expect("failed to run ilo serv --invalid-flag");
        assert!(
            !out.status.success(),
            "expected non-zero exit for unknown flag to `ilo serv`"
        );
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !stderr.trim().is_empty(),
            "expected error on stderr, got empty"
        );
    }

    // ── subprocess: tools subcommand with --tools http config file ───────────

    fn write_temp_tools_config(name: &str, tools_json: &str) -> String {
        let path = format!("/tmp/ilo_test_{name}.json");
        std::fs::write(&path, tools_json).expect("write tools config");
        path
    }

    #[test]
    fn cli_tools_cmd_with_http_config_human_output() {
        // tools --tools <path> → human-readable list of tool names
        let config = r#"{"tools":{"greet":{"url":"http://localhost:9"},"ping":{"url":"http://localhost:9"}}}"#;
        let path = write_temp_tools_config("human_A1", config);
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools", &path])
            .output()
            .expect("failed to run ilo tools --tools");
        // May exit non-zero (no MCP), but should not crash
        let stdout = String::from_utf8_lossy(&out.stdout);
        // greet and ping should appear in output
        assert!(
            stdout.contains("greet") || stdout.contains("ping"),
            "expected tool names in stdout, got: {stdout}"
        );
    }

    #[test]
    fn cli_tools_cmd_with_http_config_ilo_output() {
        // --ilo flag: emit valid ilo tool decls
        let config = r#"{"tools":{"calc":{"url":"http://localhost:9"}}}"#;
        let path = write_temp_tools_config("ilo_B2", config);
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools", &path, "--ilo"])
            .output()
            .expect("failed to run ilo tools --tools --ilo");
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("tool") || stdout.contains("calc"),
            "expected ilo tool decl in stdout, got: {stdout}"
        );
    }

    #[test]
    fn cli_tools_cmd_with_http_config_json_output() {
        // --json flag: emit JSON array
        let config = r#"{"tools":{"lookup":{"url":"http://localhost:9"}}}"#;
        let path = write_temp_tools_config("json_C3", config);
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools", &path, "--json"])
            .output()
            .expect("failed to run ilo tools --tools --json");
        let stdout = String::from_utf8_lossy(&out.stdout);
        // Should be a JSON array
        assert!(
            stdout.trim().starts_with('['),
            "expected JSON array in stdout, got: {stdout}"
        );
        assert!(
            stdout.contains("lookup"),
            "expected 'lookup' in JSON output, got: {stdout}"
        );
    }

    #[test]
    fn cli_tools_cmd_with_http_config_full_flag() {
        // --full flag: human output with type info
        let config = r#"{"tools":{"do_thing":{"url":"http://localhost:9"}}}"#;
        let path = write_temp_tools_config("full_D4", config);
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools", &path, "--full"])
            .output()
            .expect("failed to run ilo tools --tools --full");
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("do_thing"),
            "expected 'do_thing' in output, got: {stdout}"
        );
    }

    #[test]
    fn cli_tools_cmd_unknown_flag_exits_nonzero() {
        // Unknown flag in tools subcommand → exit nonzero
        let config = r#"{"tools":{}}"#;
        let path = write_temp_tools_config("ukflag_E5", config);
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools", &path, "--unknown-flag"])
            .output()
            .expect("failed to run ilo tools with unknown flag");
        assert!(
            !out.status.success(),
            "expected non-zero exit for unknown flag"
        );
    }

    #[test]
    fn cli_tools_cmd_tools_no_path_exits_nonzero() {
        // --tools with no path arg → exit nonzero
        let out = std::process::Command::new(ilo_bin())
            .args(["tools", "--tools"])
            .output()
            .expect("failed to run ilo tools --tools");
        assert!(
            !out.status.success(),
            "expected non-zero exit for --tools with no path"
        );
    }

    // ── unit: print_tool_graph (no typed tools = empty message) ──────────────

    #[test]
    fn print_tool_graph_no_tools_prints_no_typed_tools() {
        // With no Decl::Tool entries, graph prints "(no typed tools...)"
        // We can't easily capture stdout in unit tests, but calling the function
        // with an empty slice exercises the early return path.
        // This test just ensures no panic.
        print_tool_graph(&[]);
    }

    #[test]
    fn print_tool_graph_with_typed_tools_no_panic() {
        use ast::{Decl, Param, Type};
        let decls = vec![
            Decl::Tool {
                name: "alpha".into(),
                description: "first tool".into(),
                params: vec![Param { name: "x".into(), ty: Type::Number }],
                return_type: Type::Result(Box::new(Type::Text), Box::new(Type::Text)),
                timeout: None,
                retry: None,
                span: ast::Span::UNKNOWN,
            },
            Decl::Tool {
                name: "beta".into(),
                description: "second tool".into(),
                params: vec![Param { name: "s".into(), ty: Type::Text }],
                return_type: Type::Text,
                timeout: None,
                retry: None,
                span: ast::Span::UNKNOWN,
            },
        ];
        // Should not panic — exercises the graph table printing code
        print_tool_graph(&decls);
    }

    // ── unit: tool_sig_str edge cases ─────────────────────────────────────────

    #[test]
    fn tool_sig_str_no_params_result_type() {
        use ast::{Param, Type};
        let params: Vec<Param> = vec![];
        let ret = Type::Result(Box::new(Type::Number), Box::new(Type::Text));
        let sig = tool_sig_str(&params, &ret);
        assert!(sig.starts_with('>'), "expected '>' prefix for no-param sig, got: {sig}");
        assert!(sig.contains("R"), "expected result type in sig, got: {sig}");
    }

    // ── unit: resolve_imports verify-warning path ─────────────────────────────

    #[test]
    fn verify_warnings_emitted_via_subprocess() {
        // A program that triggers a verify warning (unused variable or similar).
        // Run via subprocess so the warn path (L1107) is exercised.
        // Use a program with a dead let binding to trigger warnings.
        let out = std::process::Command::new(ilo_bin())
            .args(["f>n;x=1;2"])
            .output()
            .expect("failed to run ilo");
        // May succeed or fail depending on verify behavior, just ensure it runs
        let _ = out;
    }

    // ── unit: resolve_imports error paths ─────────────────────────────────────

    fn make_use_decl(path: &str) -> ast::Decl {
        ast::Decl::Use {
            path: path.to_string(),
            only: None,
            span: ast::Span::UNKNOWN,
        }
    }

    #[test]
    fn resolve_imports_no_base_dir_emits_error() {
        // `use` without a file context → ILO-P017 error (lines 699-703)
        let decls = vec![make_use_decl("math.ilo")];
        let mut visited = std::collections::HashSet::new();
        let mut diagnostics = Vec::new();
        let result = resolve_imports(decls, None, &mut visited, &mut diagnostics);
        assert!(result.is_empty(), "should return no decls");
        assert!(!diagnostics.is_empty(), "should emit error");
        assert!(diagnostics[0].message.contains("file path context"));
    }

    #[test]
    fn resolve_imports_file_not_found_emits_error() {
        // Import a non-existent file → ILO-P017 (lines 711-716)
        let decls = vec![make_use_decl("nonexistent_file_xyz.ilo")];
        let mut visited = std::collections::HashSet::new();
        let mut diagnostics = Vec::new();
        let dir = std::path::Path::new("/tmp");
        let result = resolve_imports(decls, Some(dir), &mut visited, &mut diagnostics);
        assert!(result.is_empty());
        assert!(!diagnostics.is_empty());
        assert!(diagnostics[0].message.contains("nonexistent_file_xyz.ilo"));
    }

    #[test]
    fn resolve_imports_circular_emits_error() {
        // Pre-populate visited with a file that we then try to import → ILO-P018 (lines 721-726)
        let path = "/tmp/ilo_circ_test.ilo";
        std::fs::write(path, "f>n;1").unwrap();
        let canonical = std::fs::canonicalize(path).unwrap();

        let decls = vec![make_use_decl("ilo_circ_test.ilo")];
        let mut visited = std::collections::HashSet::new();
        visited.insert(canonical);
        let mut diagnostics = Vec::new();
        let dir = std::path::Path::new("/tmp");
        let result = resolve_imports(decls, Some(dir), &mut visited, &mut diagnostics);
        assert!(result.is_empty());
        assert!(!diagnostics.is_empty());
        assert!(diagnostics[0].message.contains("circular"));
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn resolve_imports_lex_error_in_imported_file() {
        // Import a file with invalid syntax → lex error pushed to diagnostics (lines 743-745)
        let path = "/tmp/ilo_lex_err_test.ilo";
        std::fs::write(path, "MyFunc invalid_UpperCase").unwrap();
        let decls = vec![make_use_decl("ilo_lex_err_test.ilo")];
        let mut visited = std::collections::HashSet::new();
        let mut diagnostics = Vec::new();
        let dir = std::path::Path::new("/tmp");
        let _result = resolve_imports(decls, Some(dir), &mut visited, &mut diagnostics);
        assert!(!diagnostics.is_empty(), "should emit lex error diagnostic");
        std::fs::remove_file(path).ok();
    }

    #[test]
    fn resolve_imports_read_error_after_canonicalize() {
        // Create a real file, canonicalize it, then delete it — when resolve_imports
        // tries to read_to_string after canonicalize, it gets Err → lines 731-737.
        let path = "/tmp/ilo_read_err_test.ilo";
        std::fs::write(path, "f>n;1").unwrap();
        // Create a symlink-like path that canonicalizes to /tmp/ilo_read_err_test_gone.ilo
        // Instead: just test file-not-found by giving a path whose parent exists but file doesn't.
        // Use a path that doesn't exist at all — canonicalize will Err → covers lines 711-716 again.
        // To hit the read_to_string Err path (731-737), we'd need canonicalize to succeed but
        // read to fail — which requires platform tricks. Skip that specific sub-path.
        std::fs::remove_file(path).ok();
        // Simple verification: non-existent path hits the canonical error (711-716)
        let decls = vec![make_use_decl("ilo_read_err_test.ilo")];
        let mut visited = std::collections::HashSet::new();
        let mut diagnostics = Vec::new();
        let dir = std::path::Path::new("/tmp");
        resolve_imports(decls, Some(dir), &mut visited, &mut diagnostics);
        assert!(!diagnostics.is_empty());
    }

    // ── unit: warn_cross_language_syntax ─────────────────────────────────────

    #[test]
    fn warn_cross_language_syntax_detects_and_or() {
        // && and || in source → warn_cross_language_syntax emits a diagnostic
        // Capture is not possible directly; test that no panic occurs and the
        // function is callable with Text mode.
        warn_cross_language_syntax("f>b;x&&y", OutputMode::Text);
        warn_cross_language_syntax("f>b;x||y", OutputMode::Text);
        // No return value — just ensure it completes without panic.
    }

    #[test]
    fn warn_cross_language_syntax_no_match_is_silent() {
        // Clean source → no warning emitted (early return at line 658)
        warn_cross_language_syntax("f x:n>n;+x 1", OutputMode::Text);
    }

    // ── unit: report_diagnostic modes ────────────────────────────────────────

    #[test]
    fn report_diagnostic_ansi_mode() {
        let d = Diagnostic::error("test error".to_string());
        // Just verify it doesn't panic with ANSI mode
        report_diagnostic(&d, OutputMode::Ansi);
    }

    #[test]
    fn report_diagnostic_text_mode() {
        let d = Diagnostic::error("test error".to_string());
        report_diagnostic(&d, OutputMode::Text);
    }

    #[test]
    fn report_diagnostic_json_mode() {
        let d = Diagnostic::error("test error".to_string());
        report_diagnostic(&d, OutputMode::Json);
    }

    // ── unit: tools_cmd rendering paths ──────────────────────────────────────

    fn write_tools_config_unit(name: &str) -> String {
        let path = format!("/tmp/ilo_unit_tools_{name}.json");
        std::fs::write(&path,
            r#"{"tools":{"search":{"url":"http://localhost:9"},"fetch":{"url":"http://localhost:9"}}}"#
        ).unwrap();
        path
    }

    #[test]
    fn tools_cmd_human_flag_renders_no_panic() {
        // Covers: --human flag (lines 57-58), Human rendering without --full (lines 122, 126)
        let path = write_tools_config_unit("human_unit");
        tools_cmd(&[
            "--tools".to_string(), path.clone(),
            "--human".to_string(),
        ]);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn tools_cmd_ilo_flag_renders_no_panic() {
        // Covers: --ilo flag (lines 60-61), full=true (line 99-100), Ilo rendering (lines 140-147)
        let path = write_tools_config_unit("ilo_unit");
        tools_cmd(&[
            "--tools".to_string(), path.clone(),
            "--ilo".to_string(),
        ]);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn tools_cmd_json_flag_renders_no_panic() {
        // Covers: --json flag (lines 64-65), Json rendering (lines 149-181)
        let path = write_tools_config_unit("json_unit");
        tools_cmd(&[
            "--tools".to_string(), path.clone(),
            "--json".to_string(),
        ]);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn tools_cmd_full_flag_human_shows_http_label() {
        // Covers: --full flag (lines 68-70), Human+full path (lines 122, 124)
        let path = write_tools_config_unit("full_unit");
        tools_cmd(&[
            "--tools".to_string(), path.clone(),
            "--full".to_string(),
        ]);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn tools_cmd_graph_flag_no_panic() {
        // Covers: --graph flag (lines 72-74), graph flag path (lines 190-192)
        let path = write_tools_config_unit("graph_unit");
        tools_cmd(&[
            "--tools".to_string(), path.clone(),
            "--graph".to_string(),
        ]);
        std::fs::remove_file(&path).ok();
    }

    // ── unit: print_tool_graph with non-Tool decl → filter_map None ──────────

    #[test]
    fn print_tool_graph_with_function_decl_skipped() {
        // Covers line 205: the None arm of filter_map when decl is not a Tool.
        use ast::{Decl, Param, Type, Span};
        let decls = vec![
            Decl::Function {
                name: "helper".into(),
                params: vec![Param { name: "x".into(), ty: Type::Number }],
                return_type: Type::Number,
                body: vec![],
                span: Span::UNKNOWN,
            },
            Decl::Tool {
                name: "alpha".into(),
                description: "a tool".into(),
                params: vec![Param { name: "x".into(), ty: Type::Text }],
                return_type: Type::Result(Box::new(Type::Text), Box::new(Type::Text)),
                timeout: None,
                retry: None,
                span: Span::UNKNOWN,
            },
        ];
        // Function decl → None in filter_map (line 205); Tool → Some
        print_tool_graph(&decls);
    }

    // ── unit: tool_sig_str with params ───────────────────────────────────────

    #[test]
    fn tool_sig_str_with_params() {
        let params = vec![
            ast::Param { name: "url".into(), ty: ast::Type::Text },
            ast::Param { name: "limit".into(), ty: ast::Type::Number },
        ];
        let ret = ast::Type::Result(Box::new(ast::Type::Text), Box::new(ast::Type::Text));
        let sig = tool_sig_str(&params, &ret);
        assert!(sig.contains("url"), "expected url param in sig: {sig}");
        assert!(sig.contains("limit"), "expected limit param in sig: {sig}");
    }

    // ── unit: print_tool_graph with long sig triggers truncation ─────────────

    #[test]
    fn print_tool_graph_long_sig_truncates_no_panic() {
        // sig_w is 36; create a tool with enough params that the sig exceeds 36 chars.
        // e.g. "url:t query:t page:n limit:n size:n>R t t" is ~43 chars.
        use ast::{Decl, Param, Type};
        let decls = vec![Decl::Tool {
            name: "search".into(),
            description: "search tool".into(),
            params: vec![
                Param { name: "url".into(),   ty: Type::Text },
                Param { name: "query".into(), ty: Type::Text },
                Param { name: "page".into(),  ty: Type::Number },
                Param { name: "limit".into(), ty: Type::Number },
                Param { name: "size".into(),  ty: Type::Number },
            ],
            return_type: Type::Result(Box::new(Type::Text), Box::new(Type::Text)),
            timeout: None,
            retry: None,
            span: ast::Span::UNKNOWN,
        }];
        // sig = "url:t query:t page:n limit:n size:n>R t t" (42 chars) > 36 → truncation path
        print_tool_graph(&decls);
    }

    // ── unit: resolve_imports — directory path triggers read_to_string error ──

    #[test]
    fn resolve_imports_directory_triggers_read_error() {
        // Importing a path that resolves to a directory: canonicalize succeeds,
        // but read_to_string fails ("Is a directory") → covers lines 731-737.
        let dir_name = "ilo_test_dir_import_Z9.ilo";
        let dir_path = format!("/tmp/{dir_name}");
        std::fs::create_dir_all(&dir_path).unwrap();

        let decls = vec![make_use_decl(dir_name)];
        let mut visited = std::collections::HashSet::new();
        let mut diagnostics = Vec::new();
        let result = resolve_imports(decls, Some(std::path::Path::new("/tmp")), &mut visited, &mut diagnostics);

        assert!(result.is_empty());
        assert!(!diagnostics.is_empty(), "should emit error for directory import");

        std::fs::remove_dir(&dir_path).ok();
    }

    // ── unit: load_env_file — line without '=' is skipped silently ───────────

    #[test]
    fn load_env_file_line_without_equals_skipped() {
        // Line without '=' hits the else branch of split_once (line 826 coverage).
        use std::io::Write;
        let path = "/tmp/ilo_test_env_noeq_X7.env";
        let key = "ILO_TEST_ENV_NOEQ_X7";
        unsafe { std::env::remove_var(key) };

        let mut f = std::fs::File::create(path).unwrap();
        writeln!(f, "# comment").unwrap();          // skipped (comment)
        writeln!(f, "no_equals_here").unwrap();      // split_once returns None → line 826
        writeln!(f, "{key}=set_value").unwrap();     // normal assignment
        drop(f);

        load_env_file(path);
        assert_eq!(std::env::var(key).unwrap(), "set_value");

        unsafe { std::env::remove_var(key) };
        std::fs::remove_file(path).ok();
    }
}