kaish-kernel 0.7.0

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

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use anyhow::{Context, Result};
use tokio::sync::RwLock;

/// Monotonic counter assigned to each Kernel at construction time, exposed
/// via `$$` / `${$}`. Starts at 1; each new Kernel gets the next value.
/// `Kernel::fork()` inherits the parent's value (matching bash's "subshell
/// keeps parent's $$" semantics) because forks clone the parent's Scope
/// rather than calling `set_pid` again.
///
/// Deliberately *not* the OS PID — kaish runs as a long-lived MCP server
/// or embedded inside other binaries (kaijutsu), where the host PID is
/// meaningless to the script. See
/// `~/.claude/projects/-home-atobey-src-kaish/memory/lang_dollar_dollar_identifier.md`
/// for the design rationale.
static KERNEL_COUNTER: AtomicU64 = AtomicU64::new(1);

use async_trait::async_trait;

use crate::ast::{Arg, Command, Expr, FileTestOp, Stmt, StringPart, TestExpr, ToolDef, Value, BinaryOp};
pub use kaish_types::ExecuteOptions;
use crate::backend::{BackendError, KernelBackend};
use kaish_glob::glob_match;
use crate::dispatch::{CommandDispatcher, PipelinePosition};
use crate::interpreter::{apply_output_format, eval_expr, expand_tilde, json_to_value, value_to_bool, value_to_string, ControlFlow, ExecResult, Scope};
use crate::parser::parse;
use crate::scheduler::{is_bool_type, schema_param_lookup, stderr_stream, BoundedStream, JobManager, PipelineRunner, StderrReceiver};
#[cfg(feature = "native")]
use crate::scheduler::{drain_to_stream, DEFAULT_STREAM_MAX_SIZE};
use crate::tools::{extract_output_format, register_builtins, ExecContext, ToolArgs, ToolRegistry};
#[cfg(feature = "native")]
use crate::tools::resolve_in_path;
use crate::validator::{Severity, Validator};
#[cfg(feature = "native")]
use crate::vfs::LocalFs;
use crate::vfs::{BuiltinFs, JobFs, MemoryFs, VfsRouter};

/// VFS mount mode determines how the local filesystem is exposed.
///
/// Different modes trade off convenience vs. security:
/// - `Passthrough` gives native path access (best for human REPL use)
/// - `Sandboxed` restricts access to a subtree (safer for agents)
/// - `NoLocal` provides complete isolation (tests, pure memory mode)
#[derive(Debug, Clone)]
pub enum VfsMountMode {
    /// LocalFs at "/" — native paths work directly.
    ///
    /// Full filesystem access. Use for human-operated REPL sessions where
    /// native paths like `/home/user/project` should just work.
    ///
    /// Mounts:
    /// - `/` → LocalFs("/")
    /// - `/v` → MemoryFs (blob storage)
    #[cfg(feature = "native")]
    Passthrough,

    /// Transparent sandbox — paths look native but access is restricted.
    ///
    /// The local filesystem is mounted at its real path (e.g., `/home/user`),
    /// so `/home/user/src/project` just works. But paths outside the sandbox
    /// root are not accessible.
    ///
    /// **Note:** This only restricts VFS (builtin) operations. External commands
    /// bypass the sandbox entirely — see [`KernelConfig::allow_external_commands`].
    ///
    /// Mounts:
    /// - `/` → MemoryFs (catches paths outside sandbox)
    /// - `{root}` → LocalFs(root)  (e.g., `/home/user` → LocalFs)
    /// - `/tmp` → LocalFs("/tmp")
    /// - `/v` → MemoryFs (blob storage)
    #[cfg(feature = "native")]
    Sandboxed {
        /// Root path for local filesystem. Defaults to `$HOME`.
        /// Can be restricted further, e.g., `~/src`.
        root: Option<PathBuf>,
    },

    /// No local filesystem. Memory only.
    ///
    /// Complete isolation — no access to the host filesystem.
    /// Useful for tests or pure sandboxed execution.
    ///
    /// Mounts:
    /// - `/` → MemoryFs
    /// - `/tmp` → MemoryFs
    /// - `/v` → MemoryFs
    NoLocal,
}

#[allow(clippy::derivable_impls)] // native has multiple variants; not derivable cross-feature
impl Default for VfsMountMode {
    fn default() -> Self {
        #[cfg(feature = "native")]
        { VfsMountMode::Sandboxed { root: None } }
        #[cfg(not(feature = "native"))]
        { VfsMountMode::NoLocal }
    }
}

/// Configuration for kernel initialization.
#[derive(Debug, Clone)]
pub struct KernelConfig {
    /// Name of this kernel (for identification).
    pub name: String,

    /// VFS mount mode — controls how local filesystem is exposed.
    pub vfs_mode: VfsMountMode,

    /// Initial working directory (VFS path).
    pub cwd: PathBuf,

    /// Whether to skip pre-execution validation.
    ///
    /// When false (default), scripts are validated before execution to catch
    /// errors early. Set to true to skip validation for performance or to
    /// allow dynamic/external commands.
    pub skip_validation: bool,

    /// When true, standalone external commands inherit stdio for real-time output.
    ///
    /// Set by script runner and REPL for human-visible output.
    /// Not set by MCP server (output must be captured for structured responses).
    pub interactive: bool,

    /// Ignore file configuration for file-walking tools.
    pub ignore_config: crate::ignore_config::IgnoreConfig,

    /// Output size limit configuration for agent safety.
    pub output_limit: crate::output_limit::OutputLimitConfig,

    /// Whether external command execution (PATH lookup, `exec`, `spawn`) is allowed.
    ///
    /// When `true` (default), commands not found as builtins are resolved via PATH
    /// and executed as child processes. When `false`, only kaish builtins and
    /// backend-registered tools are available.
    ///
    /// **Security:** External commands bypass the VFS sandbox entirely — they see
    /// the real filesystem, network, and environment. Set to `false` when running
    /// untrusted input.
    pub allow_external_commands: bool,

    /// Enable confirmation latch for dangerous operations (set -o latch).
    ///
    /// When enabled, destructive operations like `rm` require nonce confirmation.
    /// Can also be enabled at runtime with `set -o latch` or via `KAISH_LATCH=1`.
    pub latch_enabled: bool,

    /// Enable trash-on-delete for rm (set -o trash).
    ///
    /// When enabled, small files are moved to freedesktop.org Trash instead of
    /// being permanently deleted. Can also be enabled at runtime with `set -o trash`
    /// or via `KAISH_TRASH=1`.
    pub trash_enabled: bool,

    /// Shared nonce store for cross-request confirmation latch.
    ///
    /// When `Some`, the kernel uses this store instead of creating a fresh one.
    /// This allows nonces issued in one MCP `execute()` call to be validated
    /// in a subsequent call. When `None` (default), a fresh store is created.
    pub nonce_store: Option<crate::nonce::NonceStore>,

    /// Variables to populate the root scope with at construction, all marked
    /// for export to child processes.
    ///
    /// The kernel itself is hermetic — it never reads `std::env::vars()` —
    /// so frontends that want OS-env passthrough (REPL, MCP) populate this
    /// from `std::env::vars()`. Embedders that want isolation pass nothing
    /// (or only the keys they curate).
    pub initial_vars: HashMap<String, Value>,

    /// Default per-request timeout. When `Some`, every `execute_with_options`
    /// call without an explicit `ExecuteOptions::timeout` uses this duration.
    /// When elapsed, the kernel cancels the request, kills any external
    /// children with the configured grace, and returns exit code 124.
    ///
    /// `None` means no default timeout — only explicit per-call timeouts apply.
    pub request_timeout: Option<Duration>,

    /// Grace period between SIGTERM and SIGKILL when killing an external
    /// child on cancellation or timeout.
    ///
    /// Defaults to 2 seconds. Set to `Duration::ZERO` to escalate immediately
    /// to SIGKILL. Long-shutdown processes (databases, etc.) may need more.
    pub kill_grace: Duration,
}

/// Get the default sandbox root ($HOME).
#[cfg(feature = "native")]
fn default_sandbox_root() -> PathBuf {
    std::env::var("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/"))
}

impl Default for KernelConfig {
    fn default() -> Self {
        #[cfg(feature = "native")]
        {
            let home = default_sandbox_root();
            Self {
                name: "default".to_string(),
                vfs_mode: VfsMountMode::Sandboxed { root: None },
                cwd: home,
                skip_validation: false,
                interactive: false,
                ignore_config: crate::ignore_config::IgnoreConfig::none(),
                output_limit: crate::output_limit::OutputLimitConfig::none(),
                allow_external_commands: true,
                latch_enabled: std::env::var("KAISH_LATCH").is_ok_and(|v| v == "1"),
                trash_enabled: std::env::var("KAISH_TRASH").is_ok_and(|v| v == "1"),
                nonce_store: None,
                initial_vars: HashMap::new(),
                request_timeout: None,
                kill_grace: Duration::from_secs(2),
            }
        }
        #[cfg(not(feature = "native"))]
        {
            Self {
                name: "default".to_string(),
                vfs_mode: VfsMountMode::NoLocal,
                cwd: PathBuf::from("/"),
                skip_validation: false,
                interactive: false,
                ignore_config: crate::ignore_config::IgnoreConfig::none(),
                output_limit: crate::output_limit::OutputLimitConfig::none(),
                allow_external_commands: false,
                latch_enabled: false,
                trash_enabled: false,
                nonce_store: None,
                initial_vars: HashMap::new(),
                request_timeout: None,
                kill_grace: Duration::from_secs(2),
            }
        }
    }
}

impl KernelConfig {
    /// Create a transient kernel config (sandboxed, for temporary use).
    #[cfg(feature = "native")]
    pub fn transient() -> Self {
        let home = default_sandbox_root();
        Self {
            name: "transient".to_string(),
            vfs_mode: VfsMountMode::Sandboxed { root: None },
            cwd: home,
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::none(),
            output_limit: crate::output_limit::OutputLimitConfig::none(),
            allow_external_commands: true,
            latch_enabled: false,
            trash_enabled: false,
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Create a transient kernel config (isolated, no-default-features).
    #[cfg(not(feature = "native"))]
    pub fn transient() -> Self {
        Self::isolated()
    }

    /// Create a kernel config with the given name (sandboxed by default).
    #[cfg(feature = "native")]
    pub fn named(name: &str) -> Self {
        let home = default_sandbox_root();
        Self {
            name: name.to_string(),
            vfs_mode: VfsMountMode::Sandboxed { root: None },
            cwd: home,
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::none(),
            output_limit: crate::output_limit::OutputLimitConfig::none(),
            allow_external_commands: true,
            latch_enabled: false,
            trash_enabled: false,
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Create a kernel config with the given name (isolated, no-default-features).
    #[cfg(not(feature = "native"))]
    pub fn named(name: &str) -> Self {
        Self {
            name: name.to_string(),
            ..Self::isolated()
        }
    }

    /// Create a REPL config with passthrough filesystem access.
    ///
    /// Native paths like `/home/user/project` work directly.
    /// The cwd is set to the actual current working directory.
    #[cfg(feature = "native")]
    pub fn repl() -> Self {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
        Self {
            name: "repl".to_string(),
            vfs_mode: VfsMountMode::Passthrough,
            cwd,
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::none(),
            output_limit: crate::output_limit::OutputLimitConfig::none(),
            allow_external_commands: true,
            latch_enabled: std::env::var("KAISH_LATCH").is_ok_and(|v| v == "1"),
            trash_enabled: std::env::var("KAISH_TRASH").is_ok_and(|v| v == "1"),
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Create an MCP server config with sandboxed filesystem access.
    ///
    /// Local filesystem is accessible at its real path (e.g., `/home/user`),
    /// but sandboxed to `$HOME`. Paths outside the sandbox are not accessible
    /// through builtins. External commands still access the real filesystem —
    /// use `.with_allow_external_commands(false)` to block them.
    #[cfg(feature = "native")]
    pub fn mcp() -> Self {
        let home = default_sandbox_root();
        Self {
            name: "mcp".to_string(),
            vfs_mode: VfsMountMode::Sandboxed { root: None },
            cwd: home,
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::mcp(),
            output_limit: crate::output_limit::OutputLimitConfig::mcp(),
            allow_external_commands: true,
            latch_enabled: std::env::var("KAISH_LATCH").is_ok_and(|v| v == "1"),
            trash_enabled: std::env::var("KAISH_TRASH").is_ok_and(|v| v == "1"),
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Create an MCP server config with a custom sandbox root.
    ///
    /// Use this to restrict access to a subdirectory like `~/src`.
    #[cfg(feature = "native")]
    pub fn mcp_with_root(root: PathBuf) -> Self {
        Self {
            name: "mcp".to_string(),
            vfs_mode: VfsMountMode::Sandboxed { root: Some(root.clone()) },
            cwd: root,
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::mcp(),
            output_limit: crate::output_limit::OutputLimitConfig::mcp(),
            allow_external_commands: true,
            latch_enabled: std::env::var("KAISH_LATCH").is_ok_and(|v| v == "1"),
            trash_enabled: std::env::var("KAISH_TRASH").is_ok_and(|v| v == "1"),
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Create a config with no local filesystem (memory only).
    ///
    /// Complete isolation: no local filesystem and external commands are disabled.
    /// Useful for tests or pure sandboxed execution.
    pub fn isolated() -> Self {
        Self {
            name: "isolated".to_string(),
            vfs_mode: VfsMountMode::NoLocal,
            cwd: PathBuf::from("/"),
            skip_validation: false,
            interactive: false,
            ignore_config: crate::ignore_config::IgnoreConfig::none(),
            output_limit: crate::output_limit::OutputLimitConfig::none(),
            allow_external_commands: false,
            latch_enabled: false,
            trash_enabled: false,
            nonce_store: None,
            initial_vars: HashMap::new(),
            request_timeout: None,
            kill_grace: Duration::from_secs(2),
        }
    }

    /// Set the VFS mount mode.
    pub fn with_vfs_mode(mut self, mode: VfsMountMode) -> Self {
        self.vfs_mode = mode;
        self
    }

    /// Set the initial working directory.
    pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
        self.cwd = cwd;
        self
    }

    /// Skip pre-execution validation.
    pub fn with_skip_validation(mut self, skip: bool) -> Self {
        self.skip_validation = skip;
        self
    }

    /// Enable interactive mode (external commands inherit stdio).
    pub fn with_interactive(mut self, interactive: bool) -> Self {
        self.interactive = interactive;
        self
    }

    /// Set the ignore file configuration.
    pub fn with_ignore_config(mut self, config: crate::ignore_config::IgnoreConfig) -> Self {
        self.ignore_config = config;
        self
    }

    /// Set the output limit configuration.
    pub fn with_output_limit(mut self, config: crate::output_limit::OutputLimitConfig) -> Self {
        self.output_limit = config;
        self
    }

    /// Set whether external command execution is allowed.
    ///
    /// When `false`, commands not found as builtins produce "command not found"
    /// instead of searching PATH. The `exec` and `spawn` builtins also return
    /// errors. Use this to prevent VFS sandbox bypass via external binaries.
    pub fn with_allow_external_commands(mut self, allow: bool) -> Self {
        self.allow_external_commands = allow;
        self
    }

    /// Enable or disable confirmation latch at startup.
    pub fn with_latch(mut self, enabled: bool) -> Self {
        self.latch_enabled = enabled;
        self
    }

    /// Enable or disable trash-on-delete at startup.
    pub fn with_trash(mut self, enabled: bool) -> Self {
        self.trash_enabled = enabled;
        self
    }

    /// Use a shared nonce store for cross-request confirmation latch.
    ///
    /// Pass a `NonceStore` that outlives individual kernel instances so nonces
    /// issued in one MCP `execute()` call can be validated in subsequent calls.
    pub fn with_nonce_store(mut self, store: crate::nonce::NonceStore) -> Self {
        self.nonce_store = Some(store);
        self
    }

    /// Add a single initial variable; marked exported when the kernel boots.
    ///
    /// Repeated calls add (last write wins on key collision).
    pub fn with_var(mut self, name: impl Into<String>, value: Value) -> Self {
        self.initial_vars.insert(name.into(), value);
        self
    }

    /// Replace the entire initial-vars map. All entries are marked exported.
    pub fn with_initial_vars(mut self, vars: HashMap<String, Value>) -> Self {
        self.initial_vars = vars;
        self
    }

    /// Extend the initial-vars map with the given entries (last write wins).
    pub fn with_vars(mut self, vars: HashMap<String, Value>) -> Self {
        self.initial_vars.extend(vars);
        self
    }

    /// Set the default per-request timeout (kernel-wide).
    ///
    /// Each `execute_with_options` call without an explicit timeout uses
    /// this. On elapsed, the kernel cancels and returns exit code 124.
    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Set the SIGTERM-to-SIGKILL grace period for child kills.
    pub fn with_kill_grace(mut self, grace: Duration) -> Self {
        self.kill_grace = grace;
        self
    }
}

/// The Kernel (核) — executes kaish code.
///
/// This is the primary interface for running kaish commands. It owns all
/// the runtime state: variables, tools, VFS, jobs, and persistence.
pub struct Kernel {
    /// Kernel name.
    name: String,
    /// Variable scope.
    scope: RwLock<Scope>,
    /// Tool registry.
    tools: Arc<ToolRegistry>,
    /// User-defined tools (from `tool name { body }` statements).
    user_tools: RwLock<HashMap<String, ToolDef>>,
    /// Virtual filesystem router.
    vfs: Arc<VfsRouter>,
    /// Background job manager.
    jobs: Arc<JobManager>,
    /// Pipeline runner.
    runner: PipelineRunner,
    /// Execution context (cwd, stdin, etc.).
    exec_ctx: RwLock<ExecContext>,
    /// Whether to skip pre-execution validation.
    skip_validation: bool,
    /// When true, standalone external commands inherit stdio for real-time output.
    interactive: bool,
    /// Whether external command execution is allowed.
    allow_external_commands: bool,
    /// Default per-request timeout (None = no default).
    request_timeout: Option<Duration>,
    /// SIGTERM-to-SIGKILL grace period for child kills.
    kill_grace: Duration,
    /// Receiver for the kernel stderr stream.
    ///
    /// Pipeline stages write to the corresponding `StderrStream` (set on ExecContext).
    /// The kernel drains this after each statement in `execute_streaming`.
    stderr_receiver: tokio::sync::Mutex<StderrReceiver>,
    /// Cancellation token for interrupting execution (Ctrl-C).
    ///
    /// Protected by `std::sync::Mutex` (not tokio) because the SIGINT handler
    /// needs sync access. Each `execute()` call gets a fresh child token;
    /// `cancel()` cancels the current token and replaces it.
    cancel_token: std::sync::Mutex<tokio_util::sync::CancellationToken>,
    /// Terminal state for job control (interactive mode only, Unix only).
    #[cfg(all(unix, feature = "native"))]
    terminal_state: Option<Arc<crate::terminal::TerminalState>>,
    /// Weak self-reference for handing out `Arc<dyn CommandDispatcher>`.
    ///
    /// Set by `into_arc()`. Allows builtins to re-dispatch inner commands
    /// through the full Kernel resolution chain.
    self_weak: std::sync::OnceLock<std::sync::Weak<Self>>,
    /// Serializes concurrent `execute()` / `execute_streaming()` callers on
    /// this Kernel instance. Tokio's Mutex is fair (FIFO) and acts as the
    /// queue. Background jobs, scatter workers, and concurrent pipeline
    /// stages do NOT take this lock — they run against a *forked* Kernel
    /// (see [`Kernel::fork`]) so they never contend with the foreground.
    execute_lock: tokio::sync::Mutex<()>,
}

impl Kernel {
    /// Create a new kernel with the given configuration.
    pub fn new(config: KernelConfig) -> Result<Self> {
        let mut vfs = Self::setup_vfs(&config);
        let jobs = Arc::new(JobManager::new());

        // Mount JobFs for job observability at /v/jobs
        vfs.mount("/v/jobs", JobFs::new(jobs.clone()));

        Self::assemble(config, vfs, jobs, |_| {}, |vfs_ref, tools| {
            ExecContext::with_vfs_and_tools(vfs_ref.clone(), tools.clone())
        })
    }

    /// Set up VFS based on mount mode.
    fn setup_vfs(config: &KernelConfig) -> VfsRouter {
        let mut vfs = VfsRouter::new();

        match &config.vfs_mode {
            #[cfg(feature = "native")]
            VfsMountMode::Passthrough => {
                // LocalFs at "/" — native paths work directly
                vfs.mount("/", LocalFs::new(PathBuf::from("/")));
                // Memory for blobs
                vfs.mount("/v", MemoryFs::new());
            }
            #[cfg(feature = "native")]
            VfsMountMode::Sandboxed { root } => {
                // Memory at root for safety (catches paths outside sandbox)
                vfs.mount("/", MemoryFs::new());
                vfs.mount("/v", MemoryFs::new());

                // Real /tmp for interop with other processes
                vfs.mount("/tmp", LocalFs::new(PathBuf::from("/tmp")));

                // Mount XDG runtime dir for spill files and socket access
                let runtime = crate::paths::xdg_runtime_dir();
                if runtime.exists() {
                    let runtime_str = runtime.to_string_lossy().to_string();
                    vfs.mount(&runtime_str, LocalFs::new(runtime));
                }

                // Resolve the sandbox root (defaults to $HOME)
                let local_root = root.clone().unwrap_or_else(|| {
                    std::env::var("HOME")
                        .map(PathBuf::from)
                        .unwrap_or_else(|_| PathBuf::from("/"))
                });

                // Mount at the real path for transparent access
                // e.g., /home/atobey → LocalFs("/home/atobey")
                // so /home/atobey/src/kaish just works
                let mount_point = local_root.to_string_lossy().to_string();
                vfs.mount(&mount_point, LocalFs::new(local_root));
            }
            VfsMountMode::NoLocal => {
                // Pure memory mode — no local filesystem
                vfs.mount("/", MemoryFs::new());
                vfs.mount("/tmp", MemoryFs::new());
                vfs.mount("/v", MemoryFs::new());
            }
        }

        vfs
    }

    /// Create a transient kernel (no persistence).
    pub fn transient() -> Result<Self> {
        Self::new(KernelConfig::transient())
    }

    /// Create a kernel with a custom backend and `/v/*` virtual path support.
    ///
    /// This is the constructor for embedding kaish in other systems that provide
    /// their own storage backend (e.g., CRDT-backed storage in kaijutsu).
    ///
    /// A `VirtualOverlayBackend` routes paths automatically:
    /// - `/v/*` → Internal VFS (JobFs at `/v/jobs`, MemoryFs at `/v/blobs`)
    /// - Everything else → Your custom backend
    ///
    /// The optional `configure_vfs` closure lets you add additional virtual mounts
    /// (e.g., `/v/docs` for CRDT blocks) after the built-in mounts are set up.
    ///
    /// **Note:** The config's `vfs_mode` is ignored — all non-`/v/*` path routing
    /// is handled by your custom backend. The config is only used for `name`, `cwd`,
    /// `skip_validation`, and `interactive`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Simple: default /v/* mounts only
    /// let kernel = Kernel::with_backend(backend, config, |_| {}, |_| {})?;
    ///
    /// // With custom mounts
    /// let kernel = Kernel::with_backend(backend, config, |vfs| {
    ///     vfs.mount_arc("/v/docs", docs_fs);
    ///     vfs.mount_arc("/v/g", git_fs);
    /// }, |_| {})?;
    ///
    /// // With custom tools
    /// let kernel = Kernel::with_backend(backend, config, |_| {}, |tools| {
    ///     tools.register(MyCustomTool::new());
    /// })?;
    /// ```
    pub fn with_backend(
        backend: Arc<dyn KernelBackend>,
        config: KernelConfig,
        configure_vfs: impl FnOnce(&mut VfsRouter),
        configure_tools: impl FnOnce(&mut ToolRegistry),
    ) -> Result<Self> {
        use crate::backend::VirtualOverlayBackend;

        let mut vfs = VfsRouter::new();
        let jobs = Arc::new(JobManager::new());

        vfs.mount("/v/jobs", JobFs::new(jobs.clone()));
        vfs.mount("/v/blobs", MemoryFs::new());

        // Let caller add custom mounts (e.g., /v/docs, /v/g)
        configure_vfs(&mut vfs);

        Self::assemble(config, vfs, jobs, configure_tools, |vfs_arc: &Arc<VfsRouter>, _: &Arc<ToolRegistry>| {
            let overlay: Arc<dyn KernelBackend> =
                Arc::new(VirtualOverlayBackend::new(backend, vfs_arc.clone()));
            ExecContext::with_backend(overlay)
        })
    }

    /// Shared assembly: wires up tools, runner, scope, and ExecContext.
    ///
    /// The `make_ctx` closure receives the VFS and tools so backends that need
    /// them (like `LocalBackend::with_tools`) can capture them. Custom backends
    /// that already have their own storage can ignore these parameters.
    fn assemble(
        config: KernelConfig,
        mut vfs: VfsRouter,
        jobs: Arc<JobManager>,
        configure_tools: impl FnOnce(&mut ToolRegistry),
        make_ctx: impl FnOnce(&Arc<VfsRouter>, &Arc<ToolRegistry>) -> ExecContext,
    ) -> Result<Self> {
        let KernelConfig { name, cwd, skip_validation, interactive, ignore_config, output_limit, allow_external_commands, latch_enabled, trash_enabled, nonce_store, initial_vars, request_timeout, kill_grace, .. } = config;

        let mut tools = ToolRegistry::new();
        register_builtins(&mut tools);
        configure_tools(&mut tools);
        let tools = Arc::new(tools);

        // Mount BuiltinFs so `ls /v/bin` lists builtins
        vfs.mount("/v/bin", BuiltinFs::new(tools.clone()));

        let vfs = Arc::new(vfs);

        let runner = PipelineRunner::new(tools.clone());

        let (stderr_writer, stderr_receiver) = stderr_stream();

        let mut exec_ctx = make_ctx(&vfs, &tools);
        exec_ctx.set_cwd(cwd);
        exec_ctx.set_job_manager(jobs.clone());
        exec_ctx.set_tool_schemas(tools.schemas());
        exec_ctx.set_tools(tools.clone());
        #[cfg(feature = "native")]
        exec_ctx.set_trash_backend(Arc::new(crate::trash_system::SystemTrash));
        exec_ctx.stderr = Some(stderr_writer);
        exec_ctx.ignore_config = ignore_config;
        exec_ctx.output_limit = output_limit;
        exec_ctx.allow_external_commands = allow_external_commands;
        if let Some(store) = nonce_store {
            exec_ctx.nonce_store = store;
        }

        Ok(Self {
            name,
            scope: RwLock::new({
                let mut scope = Scope::new();
                scope.set_pid(KERNEL_COUNTER.fetch_add(1, Ordering::Relaxed));
                if let Ok(home) = std::env::var("HOME") {
                    scope.set("HOME", Value::String(home));
                }
                // Apply caller-supplied initial variables, all marked exported.
                // Frontends (REPL, MCP) populate this from std::env::vars()
                // for shell-like UX; embedders that want hermetic behavior
                // simply leave it empty.
                for (name, value) in initial_vars {
                    scope.set_exported(name, value);
                }
                scope.set_latch_enabled(latch_enabled);
                scope.set_trash_enabled(trash_enabled);
                scope
            }),
            tools,
            user_tools: RwLock::new(HashMap::new()),
            vfs,
            jobs,
            runner,
            exec_ctx: RwLock::new(exec_ctx),
            skip_validation,
            interactive,
            allow_external_commands,
            request_timeout,
            kill_grace,
            stderr_receiver: tokio::sync::Mutex::new(stderr_receiver),
            cancel_token: std::sync::Mutex::new(tokio_util::sync::CancellationToken::new()),
            #[cfg(all(unix, feature = "native"))]
            terminal_state: None,
            self_weak: std::sync::OnceLock::new(),
            execute_lock: tokio::sync::Mutex::new(()),
        })
    }

    /// Get the kernel name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Wrap this Kernel in an Arc and initialize its self-reference.
    ///
    /// This enables the Kernel to hand out `Arc<dyn CommandDispatcher>` references
    /// to child contexts, allowing builtins like `timeout` to dispatch inner
    /// commands through the full resolution chain (user tools → builtins →
    /// .kai scripts → external commands).
    pub fn into_arc(self) -> Arc<Self> {
        let arc = Arc::new(self);
        let _ = arc.self_weak.set(Arc::downgrade(&arc));
        arc
    }

    /// Fork a subsidiary kernel for concurrent execution.
    ///
    /// The fork is a fully-functional `Kernel` that:
    /// - **Snapshots** per-session state from the parent: scope (COW — cheap),
    ///   user-defined tools, cwd, aliases, ignore config, etc. Mutations on
    ///   the fork do NOT propagate back to the parent — matching bash
    ///   subshell / background-job semantics.
    /// - **Shares** read-mostly resources with the parent via `Arc`: the tool
    ///   registry, the VFS router, and the job manager. A job registered by
    ///   the fork is visible to the parent's `jobs` builtin, and the fork
    ///   sees the same VFS mounts.
    /// - **Owns** its own `stderr_receiver`, `cancel_token`, and
    ///   `execute_lock`. It is never the TTY owner, so `interactive` is
    ///   `false` and `terminal_state` is `None`.
    ///
    /// The returned Arc has its `self_weak` populated (via `into_arc`), so
    /// nested dispatch through `ctx.dispatcher` (e.g. the `timeout` builtin)
    /// routes through the fork itself, not the parent — which is essential
    /// for concurrency safety.
    ///
    /// Use this for **detached** background concurrency where the fork should
    /// survive parent cancellation: the `&` background-job operator and any
    /// other "fire and forget" worker. The fork gets a fresh, independent
    /// cancellation token.
    ///
    /// For foreground concurrency (scatter workers, concurrent pipeline
    /// stages, `$(...)` cmdsubs) where parent timeout/cancel must cascade
    /// into the fork's external children, use [`Self::fork_attached`].
    pub async fn fork(&self) -> Arc<Self> {
        self.fork_inner(tokio_util::sync::CancellationToken::new()).await
    }

    /// Fork attached to the parent's cancellation.
    ///
    /// Same as [`Self::fork`] but the fork's `cancel_token` is a child of
    /// the parent's. When the parent cancels (request timeout, embedder
    /// `Kernel::cancel`, etc.), the fork's token also cancels, which in
    /// turn kills any external children spawned in the fork via the
    /// `wait_or_kill` / SIGTERM-grace-SIGKILL path.
    pub async fn fork_attached(&self) -> Arc<Self> {
        let child_token = {
            #[allow(clippy::expect_used)]
            let parent = self.cancel_token.lock().expect("cancel_token poisoned");
            parent.child_token()
        };
        self.fork_inner(child_token).await
    }

    /// Shared fork implementation. Caller decides the cancellation token.
    async fn fork_inner(&self, cancel: tokio_util::sync::CancellationToken) -> Arc<Self> {
        let scope_snapshot = self.scope.read().await.clone();
        let user_tools_snapshot = self.user_tools.read().await.clone();

        // Snapshot exec_ctx by cloning the cloneable fields, then override
        // the ones that should not carry over (stderr channel, dispatcher,
        // interactive flag, terminal state, cancel — set from `cancel` arg).
        let mut fork_ctx = {
            let parent_ctx = self.exec_ctx.read().await;
            parent_ctx.child_for_pipeline()
        };
        let (stderr_writer, stderr_receiver) = stderr_stream();
        fork_ctx.stderr = Some(stderr_writer);
        // Clear dispatcher; dispatch_command will repopulate it to point at
        // the fork on the first dispatch call.
        fork_ctx.dispatcher = None;
        fork_ctx.interactive = false;
        fork_ctx.cancel = cancel.clone();
        #[cfg(all(unix, feature = "native"))]
        {
            fork_ctx.terminal_state = None;
        }

        let fork = Self {
            name: format!("{}:fork", self.name),
            scope: RwLock::new(scope_snapshot),
            tools: Arc::clone(&self.tools),
            user_tools: RwLock::new(user_tools_snapshot),
            vfs: Arc::clone(&self.vfs),
            jobs: Arc::clone(&self.jobs),
            runner: self.runner.clone(),
            exec_ctx: RwLock::new(fork_ctx),
            skip_validation: self.skip_validation,
            // Forks are never the TTY owner — they run in the background.
            interactive: false,
            allow_external_commands: self.allow_external_commands,
            request_timeout: self.request_timeout,
            kill_grace: self.kill_grace,
            stderr_receiver: tokio::sync::Mutex::new(stderr_receiver),
            cancel_token: std::sync::Mutex::new(cancel),
            #[cfg(all(unix, feature = "native"))]
            terminal_state: None,
            self_weak: std::sync::OnceLock::new(),
            execute_lock: tokio::sync::Mutex::new(()),
        };

        fork.into_arc()
    }

    /// Get an `Arc<dyn CommandDispatcher>` to this Kernel, if wrapped via `into_arc()`.
    ///
    /// Returns `None` if the Kernel was not wrapped, or if all strong references
    /// have been dropped (the `Weak` can no longer upgrade).
    pub fn dispatcher(&self) -> Option<Arc<dyn CommandDispatcher>> {
        self.self_weak
            .get()
            .and_then(|weak| weak.upgrade())
            .map(|arc| arc as Arc<dyn CommandDispatcher>)
    }

    /// Initialize terminal state for interactive job control.
    ///
    /// Call this after kernel creation when running as an interactive REPL
    /// and stdin is a TTY. Sets up process groups and signal handling.
    #[cfg(all(unix, feature = "native"))]
    pub fn init_terminal(&mut self) {
        if !self.interactive {
            return;
        }
        match crate::terminal::TerminalState::init() {
            Ok(state) => {
                let state = Arc::new(state);
                self.terminal_state = Some(state.clone());
                // Set on exec_ctx so builtins (fg, bg, kill) can access it
                self.exec_ctx.get_mut().terminal_state = Some(state);
                tracing::debug!("terminal job control initialized");
            }
            Err(e) => {
                tracing::warn!("failed to initialize terminal job control: {}", e);
            }
        }
    }

    /// Cancel the current execution.
    ///
    /// This cancels the current cancellation token, causing any execution
    /// loop to exit at the next checkpoint with exit code 130 (SIGINT).
    /// A fresh token is installed for the next `execute()` call.
    pub fn cancel(&self) {
        #[allow(clippy::expect_used)]
        let token = self.cancel_token.lock().expect("cancel_token poisoned");
        token.cancel();
    }

    /// Check if the current execution has been cancelled.
    pub fn is_cancelled(&self) -> bool {
        #[allow(clippy::expect_used)]
        let token = self.cancel_token.lock().expect("cancel_token poisoned");
        token.is_cancelled()
    }

    /// Reset the cancellation token (called at the start of each execute).
    fn reset_cancel(&self) -> tokio_util::sync::CancellationToken {
        #[allow(clippy::expect_used)]
        let mut token = self.cancel_token.lock().expect("cancel_token poisoned");
        if token.is_cancelled() {
            *token = tokio_util::sync::CancellationToken::new();
        }
        token.clone()
    }

    /// Acquire the per-Kernel execute lock, warning on contention.
    ///
    /// Tokio's Mutex is fair (FIFO) so callers queue in arrival order. When
    /// the lock is already held, emit a warning so the silent serialization
    /// is observable in logs — if you need real parallelism, fork the kernel.
    async fn acquire_execute_lock(&self) -> tokio::sync::MutexGuard<'_, ()> {
        match self.execute_lock.try_lock() {
            Ok(guard) => guard,
            Err(_) => {
                tracing::warn!(
                    target: "kaish::kernel::concurrency",
                    kernel = %self.name,
                    "execute() contended — serializing concurrent caller; \
                     use Kernel::fork() for parallelism instead of sharing"
                );
                self.execute_lock.lock().await
            }
        }
    }

    /// Execute kaish source code with default options.
    ///
    /// Equivalent to `execute_with_options(input, ExecuteOptions::default())`.
    /// Returns the result of the last statement executed.
    pub async fn execute(&self, input: &str) -> Result<ExecResult> {
        self.execute_with_options_inner(input, ExecuteOptions::default(), None).await
    }

    /// Execute with per-call options. The primary entry point for embedders
    /// that don't need per-statement output streaming.
    ///
    /// `opts` carries timeout, transient vars overlay, optional cwd override,
    /// and optional embedder-owned cancellation token. See [`ExecuteOptions`]
    /// for semantics. For streaming, use [`Self::execute_with_options_streaming`].
    ///
    /// **Cancellation:** if `opts.cancel_token` is `Some`, it is *raced*
    /// against the kernel's internal token. Either firing cancels and kills
    /// external children. The embedder's token is read-only — kernel
    /// timeouts do NOT propagate into it. Distinguish via the returned
    /// `code`: 124 = timeout, 130 = cancellation.
    ///
    /// **Timeout:** `opts.timeout` overrides `KernelConfig::request_timeout`.
    /// `Some(Duration::ZERO)` returns 124 immediately without spawning.
    ///
    /// Concurrent callers on the same Kernel serialize on the kernel-wide
    /// execute lock. For true parallelism, call [`Kernel::fork`] (detached)
    /// or [`Kernel::fork_attached`] (cancellation cascades from this kernel).
    pub async fn execute_with_options(
        &self,
        input: &str,
        opts: ExecuteOptions,
    ) -> Result<ExecResult> {
        self.execute_with_options_inner(input, opts, None).await
    }

    /// Same as [`Self::execute_with_options`] but with a per-statement output
    /// callback. The callback fires after each top-level statement so the
    /// embedder (REPL, MCP streaming) can flush output incrementally.
    pub async fn execute_with_options_streaming(
        &self,
        input: &str,
        opts: ExecuteOptions,
        on_output: &mut (dyn FnMut(&ExecResult) + Send),
    ) -> Result<ExecResult> {
        self.execute_with_options_inner(input, opts, Some(on_output)).await
    }

    /// Execute kaish source code with a transient overlay of exported variables.
    ///
    /// Deprecated thin wrapper over [`Self::execute_with_options`]. New code
    /// should use that method directly:
    /// `execute_with_options(input, ExecuteOptions::new().with_vars(vars))`.
    #[deprecated(note = "use Kernel::execute_with_options with ExecuteOptions::with_vars")]
    pub async fn execute_with_vars(
        &self,
        input: &str,
        vars: HashMap<String, Value>,
    ) -> Result<ExecResult> {
        self.execute_with_options_inner(input, ExecuteOptions::new().with_vars(vars), None).await
    }

    /// Execute kaish source code with a per-statement callback.
    ///
    /// Deprecated thin wrapper. New code should use
    /// [`Self::execute_with_options_streaming`].
    #[deprecated(note = "use Kernel::execute_with_options_streaming")]
    pub async fn execute_streaming(
        &self,
        input: &str,
        on_output: &mut (dyn FnMut(&ExecResult) + Send),
    ) -> Result<ExecResult> {
        self.execute_with_options_inner(input, ExecuteOptions::default(), Some(on_output)).await
    }

    /// Shared body for `execute`, `execute_with_options(_streaming)`, and
    /// the deprecated wrappers. Owns the per-call cancel token, vars overlay,
    /// cwd override, and timeout race.
    #[tracing::instrument(level = "info", skip(self, opts, on_output), fields(input_len = input.len()))]
    async fn execute_with_options_inner(
        &self,
        input: &str,
        opts: ExecuteOptions,
        on_output: Option<&mut (dyn FnMut(&ExecResult) + Send)>,
    ) -> Result<ExecResult> {
        let _guard = self.acquire_execute_lock().await;

        // Always reset to a fresh internal token; this is the kernel's own
        // cancel surface for embedders calling `Kernel::cancel()`. The
        // embedder-supplied `opts.cancel_token` is a *read-only input* — it
        // is NOT written into `self.cancel_token`, because doing so would
        // (a) leak the embedder's token past this call's lifetime,
        // (b) re-route a later `Kernel::cancel()` into the embedder's token,
        // (c) extend the token's lifetime via the kernel's strong clone.
        let internal = self.reset_cancel();
        // Race the embedder token against the kernel's internal token via a
        // tracked watcher task. We hold the JoinHandle so we can abort the
        // task at function exit — otherwise it would wait forever for either
        // token to fire and leak per call.
        let (effective_cancel, watcher_handle): (
            tokio_util::sync::CancellationToken,
            Option<tokio::task::JoinHandle<()>>,
        ) = if let Some(ext) = opts.cancel_token {
            let combined = tokio_util::sync::CancellationToken::new();
            let combined_writer = combined.clone();
            let i = internal.clone();
            let handle = tokio::spawn(async move {
                tokio::select! {
                    _ = i.cancelled() => combined_writer.cancel(),
                    _ = ext.cancelled() => combined_writer.cancel(),
                }
            });
            (combined, Some(handle))
        } else {
            (internal, None)
        };

        // Effective timeout: per-call wins over kernel-config default.
        let timeout = opts.timeout.or(self.request_timeout);

        // ZERO timeout: return 124 immediately without spawning anything.
        if timeout == Some(Duration::ZERO) {
            if let Some(h) = watcher_handle {
                h.abort();
            }
            return Ok(ExecResult::failure(124, "timeout: timed out after 0s".to_string()));
        }

        // Apply per-call vars overlay (push frame + set_exported), wrapped in
        // an RAII guard so a panic inside `execute_streaming_inner` still
        // pops the frame and unexports the temporarily-exported names.
        struct VarsFrameGuard<'a> {
            kernel: &'a Kernel,
            newly_exported: Vec<String>,
        }
        impl Drop for VarsFrameGuard<'_> {
            fn drop(&mut self) {
                // Best-effort cleanup using try_write. The execute_lock held
                // throughout execute_with_options means there is no concurrent
                // foreground caller; forks have their own scope and won't
                // block this. blocking_write would deadlock the runtime when
                // called from a tokio worker thread, so we explicitly do NOT
                // fall back to it — if try_write fails (which we've never
                // seen in practice), log loudly and accept the leak rather
                // than deadlock the entire kernel.
                let Ok(mut scope) = self.kernel.scope.try_write() else {
                    tracing::error!(
                        "vars frame guard: scope lock unexpectedly busy; \
                         skipping pop_frame to avoid runtime deadlock — \
                         transient vars may leak"
                    );
                    return;
                };
                scope.pop_frame();
                for name in self.newly_exported.drain(..) {
                    scope.unexport(&name);
                }
            }
        }

        // Per-call cwd override: save current cwd, set the new one, restore
        // on Drop so the kernel's persistent cwd doesn't leak between calls.
        // Same RAII pattern as VarsFrameGuard, same blocking_write trade-off.
        struct CwdGuard<'a> {
            kernel: &'a Kernel,
            saved: PathBuf,
        }
        impl Drop for CwdGuard<'_> {
            fn drop(&mut self) {
                let Ok(mut ec) = self.kernel.exec_ctx.try_write() else {
                    tracing::error!(
                        "cwd guard: exec_ctx lock unexpectedly busy; \
                         skipping cwd restore — kernel cwd may be wrong for next call"
                    );
                    return;
                };
                ec.cwd = std::mem::take(&mut self.saved);
            }
        }
        let _cwd_guard: Option<CwdGuard<'_>> = if let Some(new_cwd) = opts.cwd {
            let mut ec = self.exec_ctx.write().await;
            let saved = std::mem::replace(&mut ec.cwd, new_cwd);
            drop(ec);
            Some(CwdGuard { kernel: self, saved })
        } else {
            None
        };

        let _vars_guard: Option<VarsFrameGuard<'_>> = if !opts.vars.is_empty() {
            let mut scope = self.scope.write().await;
            scope.push_frame();
            let mut newly = Vec::with_capacity(opts.vars.len());
            for (name, value) in opts.vars {
                if !scope.is_exported(&name) {
                    newly.push(name.clone());
                }
                scope.set_exported(name, value);
            }
            drop(scope);
            Some(VarsFrameGuard { kernel: self, newly_exported: newly })
        } else {
            None
        };

        // Sync the effective cancel into self.exec_ctx so try_execute_external
        // (which reads via self.cancel_token) sees cancellation. We also need
        // builtins to see it via ctx.cancel — handled in execute_command.
        // For simplicity here we mirror effective_cancel into self.cancel_token
        // for the duration of this call, then restore the internal token at
        // the end (so a later Kernel::cancel still hits our internal surface).
        {
            #[allow(clippy::expect_used)]
            let mut cur = self.cancel_token.lock().expect("cancel_token poisoned");
            *cur = effective_cancel.clone();
        }

        // Run inner with optional timeout. The timer task cancels our token
        // on elapsed; the cascade fires SIGTERM/SIGKILL on any external
        // children via the wait_or_kill discipline in try_execute_external.
        let mut noop_cb: Box<dyn FnMut(&ExecResult) + Send> = Box::new(|_| {});
        let cb_ref: &mut (dyn FnMut(&ExecResult) + Send) = match on_output {
            Some(cb) => cb,
            None => &mut *noop_cb,
        };

        let result = if let Some(d) = timeout {
            let elapsed = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let elapsed_writer = elapsed.clone();
            let timer_token = effective_cancel.clone();
            let timer = tokio::spawn(async move {
                tokio::time::sleep(d).await;
                elapsed_writer.store(true, std::sync::atomic::Ordering::SeqCst);
                timer_token.cancel();
            });
            let r = self.execute_streaming_inner(input, cb_ref).await;
            timer.abort();
            match r {
                Ok(mut res) => {
                    if elapsed.load(std::sync::atomic::Ordering::SeqCst) {
                        res.code = 124;
                        if res.err.is_empty() {
                            res.err = format!("timeout: timed out after {:?}", d);
                        }
                    }
                    Ok(res)
                }
                Err(e) => Err(e),
            }
        } else {
            self.execute_streaming_inner(input, cb_ref).await
        };

        // Restore self.cancel_token to a fresh, uncancelled token so the
        // embedder's view of `Kernel::cancel()` stays predictable on the
        // next call (it cancels the kernel's own token, not whatever was
        // left over from this call's combined token).
        {
            #[allow(clippy::expect_used)]
            let mut cur = self.cancel_token.lock().expect("cancel_token poisoned");
            *cur = tokio_util::sync::CancellationToken::new();
        }

        // Tear down the embedder-token race watcher (if any). Leaving it
        // alive would idle forever waiting for tokens that may never fire.
        if let Some(h) = watcher_handle {
            h.abort();
        }

        // VarsFrameGuard drops here on the success path and on early-return
        // paths above (error path included). Panic safety preserved.
        result
    }

    /// The actual body of `execute_streaming`, run while holding the execute lock.
    ///
    /// Split out so internal kernel paths that are already under the lock can
    /// call this without deadlocking on re-entry. External callers must go
    /// through [`Self::execute_streaming`] so they acquire the lock.
    async fn execute_streaming_inner(
        &self,
        input: &str,
        on_output: &mut (dyn FnMut(&ExecResult) + Send),
    ) -> Result<ExecResult> {
        let program = parse(input).map_err(|errors| {
            let msg = errors
                .iter()
                .map(|e| e.format(input))
                .collect::<Vec<_>>()
                .join("\n");
            anyhow::anyhow!("parse error:\n{}", msg)
        })?;

        // AST display mode: show AST instead of executing
        {
            let scope = self.scope.read().await;
            if scope.show_ast() {
                let output = format!("{:#?}\n", program);
                return Ok(ExecResult::with_output(crate::interpreter::OutputData::text(output)));
            }
        }

        // Pre-execution validation
        if !self.skip_validation {
            let user_tools = self.user_tools.read().await;
            let validator = Validator::new(&self.tools, &user_tools);
            let issues = validator.validate(&program);

            // Collect errors (warnings are logged but don't prevent execution)
            let errors: Vec<_> = issues
                .iter()
                .filter(|i| i.severity == Severity::Error)
                .collect();

            if !errors.is_empty() {
                let error_msg = errors
                    .iter()
                    .map(|e| e.format(input))
                    .collect::<Vec<_>>()
                    .join("\n");
                return Err(anyhow::anyhow!("validation failed:\n{}", error_msg));
            }

            // Log warnings via tracing (trace level to avoid noise)
            for warning in issues.iter().filter(|i| i.severity == Severity::Warning) {
                tracing::trace!("validation: {}", warning.format(input));
            }
        }

        let mut result = ExecResult::success("");

        // Reset cancellation token for this execution.
        let cancel = self.reset_cancel();

        for stmt in program.statements {
            if matches!(stmt, Stmt::Empty) {
                continue;
            }

            // Cancellation checkpoint
            if cancel.is_cancelled() {
                result.code = 130;
                return Ok(result);
            }

            let flow = self.execute_stmt_flow(&stmt).await?;

            // Drain any stderr written by pipeline stages during this statement.
            // This captures stderr from intermediate pipeline stages that would
            // otherwise be lost (only the last stage's result is returned).
            let drained_stderr = {
                let mut receiver = self.stderr_receiver.lock().await;
                receiver.drain_lossy()
            };

            match flow {
                ControlFlow::Normal(mut r) => {
                    if !drained_stderr.is_empty() {
                        if !r.err.is_empty() && !r.err.ends_with('\n') {
                            r.err.push('\n');
                        }
                        // Prepend pipeline stderr before the last stage's stderr
                        let combined = format!("{}{}", drained_stderr, r.err);
                        r.err = combined;
                    }
                    on_output(&r);
                    // Carry the last statement's structured output for MCP TOON encoding.
                    // Must be done here (not in accumulate_result) because accumulate_result
                    // is also used in loops where per-iteration output would be wrong.
                    let last_output = r.output().cloned();
                    accumulate_result(&mut result, &r);
                    result.set_output(last_output);
                }
                ControlFlow::Exit { code } => {
                    if !drained_stderr.is_empty() {
                        result.err.push_str(&drained_stderr);
                    }
                    result.code = code;
                    return Ok(result);
                }
                ControlFlow::Return { mut value } => {
                    if !drained_stderr.is_empty() {
                        value.err = format!("{}{}", drained_stderr, value.err);
                    }
                    on_output(&value);
                    result = value;
                }
                ControlFlow::Break { result: mut r, .. } | ControlFlow::Continue { result: mut r, .. } => {
                    if !drained_stderr.is_empty() {
                        r.err = format!("{}{}", drained_stderr, r.err);
                    }
                    on_output(&r);
                    result = r;
                }
            }
        }

        Ok(result)
    }

    /// Execute a single statement, returning control flow information.
    fn execute_stmt_flow<'a>(
        &'a self,
        stmt: &'a Stmt,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ControlFlow>> + Send + 'a>> {
        use tracing::Instrument;
        let span = tracing::debug_span!("execute_stmt_flow", stmt_type = %stmt.kind_name());
        Box::pin(async move {
        match stmt {
            Stmt::Assignment(assign) => {
                // Use async evaluator to support command substitution
                let value = self.eval_expr_async(&assign.value).await
                    .context("failed to evaluate assignment")?;
                let mut scope = self.scope.write().await;
                if assign.local {
                    // local: set in innermost (current function) frame
                    scope.set(&assign.name, value.clone());
                } else {
                    // non-local: update existing or create in root frame
                    scope.set_global(&assign.name, value.clone());
                }
                drop(scope);

                // Assignments don't produce output (like sh)
                Ok(ControlFlow::ok(ExecResult::success("")))
            }
            Stmt::Command(cmd) => {
                // Route single commands through execute_pipeline for a unified path.
                // This ensures all commands go through the dispatcher chain.
                let pipeline = crate::ast::Pipeline {
                    commands: vec![cmd.clone()],
                    background: false,
                };
                let result = self.execute_pipeline(&pipeline).await?;
                self.update_last_result(&result).await;

                // Check for error exit mode (set -e)
                if !result.ok() {
                    let scope = self.scope.read().await;
                    if scope.error_exit_enabled() {
                        return Ok(ControlFlow::exit_code(result.code));
                    }
                }

                Ok(ControlFlow::ok(result))
            }
            Stmt::Pipeline(pipeline) => {
                let result = self.execute_pipeline(pipeline).await?;
                self.update_last_result(&result).await;

                // Check for error exit mode (set -e)
                if !result.ok() {
                    let scope = self.scope.read().await;
                    if scope.error_exit_enabled() {
                        return Ok(ControlFlow::exit_code(result.code));
                    }
                }

                Ok(ControlFlow::ok(result))
            }
            Stmt::If(if_stmt) => {
                // Use async evaluator to support command substitution in conditions
                let cond_value = self.eval_expr_async(&if_stmt.condition).await?;

                let branch = if is_truthy(&cond_value) {
                    &if_stmt.then_branch
                } else {
                    if_stmt.else_branch.as_deref().unwrap_or(&[])
                };

                let mut result = ExecResult::success("");
                for stmt in branch {
                    let flow = self.execute_stmt_flow(stmt).await?;
                    match flow {
                        ControlFlow::Normal(r) => {
                            accumulate_result(&mut result, &r);
                            self.drain_stderr_into(&mut result).await;
                        }
                        other => {
                            self.drain_stderr_into(&mut result).await;
                            return Ok(other);
                        }
                    }
                }
                Ok(ControlFlow::ok(result))
            }
            Stmt::For(for_loop) => {
                // Evaluate all items and collect values for iteration
                // Use async evaluator to support command substitution like $(seq 1 5)
                let mut items: Vec<Value> = Vec::new();
                for item_expr in &for_loop.items {
                    // Glob expansion in for-loop items: `for f in *.txt`
                    if let Expr::GlobPattern(pattern) = item_expr {
                        let glob_enabled = {
                            let scope = self.scope.read().await;
                            scope.glob_enabled()
                        };
                        if glob_enabled {
                            let (paths, cwd) = {
                                let ctx = self.exec_ctx.read().await;
                                let paths = ctx.expand_glob(pattern).await
                                    .map_err(|e| anyhow::anyhow!("glob: {}", e))?;
                                let cwd = ctx.resolve_path(".");
                                (paths, cwd)
                            };
                            if paths.is_empty() {
                                return Err(anyhow::anyhow!("no matches: {}", pattern));
                            }
                            for path in paths {
                                let display = if !pattern.starts_with('/') {
                                    path.strip_prefix(&cwd)
                                        .unwrap_or(&path)
                                        .to_string_lossy().into_owned()
                                } else {
                                    path.to_string_lossy().into_owned()
                                };
                                items.push(Value::String(display));
                            }
                            continue;
                        }
                    }
                    // Track whether this item came from $(cmd); that's the
                    // only position where multi-line stdout auto-splits per
                    // line. Arrays still spread element-by-element; bare
                    // $VAR is rejected upstream by validator E012. See
                    // docs/plan-for-loop-newline-split.md.
                    let from_command_subst = matches!(item_expr, Expr::CommandSubst(_));
                    let item = self.eval_expr_async(item_expr).await?;
                    match item {
                        // JSON arrays iterate over elements (preferred path
                        // when builtins emit .data — seq, jq, cut, find, …)
                        Value::Json(serde_json::Value::Array(arr)) => {
                            for elem in arr {
                                items.push(json_to_value(elem));
                            }
                        }
                        // Strings from $(cmd): empty → 0 iterations,
                        // multi-line → split per line (trimming trailing
                        // newlines and per-line trailing \r), single-line
                        // → one iteration. Whitespace within a line is
                        // NOT split — the "$VAR with spaces just works"
                        // promise is preserved because this only fires
                        // in CommandSubst position.
                        Value::String(s) if from_command_subst => {
                            let trimmed = s.trim_end_matches(['\n', '\r']);
                            if trimmed.is_empty() {
                                continue;
                            }
                            if trimmed.contains('\n') {
                                for line in trimmed.split('\n') {
                                    let line = line.trim_end_matches('\r');
                                    items.push(Value::String(line.to_string()));
                                }
                            } else {
                                items.push(Value::String(trimmed.to_string()));
                            }
                        }
                        // Strings not from $(cmd) stay as one value.
                        other => items.push(other),
                    }
                }

                let mut result = ExecResult::success("");
                {
                    let mut scope = self.scope.write().await;
                    scope.push_frame();
                }

                'outer: for item in items {
                    // Cancellation checkpoint per iteration
                    if self.is_cancelled() {
                        let mut scope = self.scope.write().await;
                        scope.pop_frame();
                        result.code = 130;
                        return Ok(ControlFlow::ok(result));
                    }
                    {
                        let mut scope = self.scope.write().await;
                        scope.set(&for_loop.variable, item);
                    }
                    for stmt in &for_loop.body {
                        let mut flow = match self.execute_stmt_flow(stmt).await {
                            Ok(f) => f,
                            Err(e) => {
                                let mut scope = self.scope.write().await;
                                scope.pop_frame();
                                return Err(e);
                            }
                        };
                        self.drain_stderr_into(&mut result).await;
                        match &mut flow {
                            ControlFlow::Normal(r) => {
                                accumulate_result(&mut result, r);
                                if !r.ok() {
                                    let scope = self.scope.read().await;
                                    if scope.error_exit_enabled() {
                                        drop(scope);
                                        let mut scope = self.scope.write().await;
                                        scope.pop_frame();
                                        return Ok(ControlFlow::exit_code(r.code));
                                    }
                                }
                            }
                            ControlFlow::Break { .. } => {
                                if flow.decrement_level() {
                                    break 'outer;
                                }
                                let mut scope = self.scope.write().await;
                                scope.pop_frame();
                                return Ok(flow);
                            }
                            ControlFlow::Continue { .. } => {
                                if flow.decrement_level() {
                                    continue 'outer;
                                }
                                let mut scope = self.scope.write().await;
                                scope.pop_frame();
                                return Ok(flow);
                            }
                            ControlFlow::Return { .. } | ControlFlow::Exit { .. } => {
                                let mut scope = self.scope.write().await;
                                scope.pop_frame();
                                return Ok(flow);
                            }
                        }
                    }
                }

                {
                    let mut scope = self.scope.write().await;
                    scope.pop_frame();
                }
                Ok(ControlFlow::ok(result))
            }
            Stmt::While(while_loop) => {
                let mut result = ExecResult::success("");

                'outer: loop {
                    // Evaluate condition - use async to support command substitution
                    // Cancellation checkpoint per iteration
                    if self.is_cancelled() {
                        result.code = 130;
                        return Ok(ControlFlow::ok(result));
                    }

                    let cond_value = self.eval_expr_async(&while_loop.condition).await?;

                    if !is_truthy(&cond_value) {
                        break;
                    }

                    // Execute body
                    for stmt in &while_loop.body {
                        let mut flow = self.execute_stmt_flow(stmt).await?;
                        self.drain_stderr_into(&mut result).await;
                        match &mut flow {
                            ControlFlow::Normal(r) => {
                                accumulate_result(&mut result, r);
                                if !r.ok() {
                                    let scope = self.scope.read().await;
                                    if scope.error_exit_enabled() {
                                        return Ok(ControlFlow::exit_code(r.code));
                                    }
                                }
                            }
                            ControlFlow::Break { .. } => {
                                if flow.decrement_level() {
                                    break 'outer;
                                }
                                return Ok(flow);
                            }
                            ControlFlow::Continue { .. } => {
                                if flow.decrement_level() {
                                    continue 'outer;
                                }
                                return Ok(flow);
                            }
                            ControlFlow::Return { .. } | ControlFlow::Exit { .. } => {
                                return Ok(flow);
                            }
                        }
                    }
                }

                Ok(ControlFlow::ok(result))
            }
            Stmt::Case(case_stmt) => {
                // Evaluate the expression to match against
                let match_value = {
                    let value = self.eval_expr_async(&case_stmt.expr).await?;
                    value_to_string(&value)
                };

                // Try each branch until we find a match
                for branch in &case_stmt.branches {
                    let matched = branch.patterns.iter().any(|pattern| {
                        glob_match(pattern, &match_value)
                    });

                    if matched {
                        // Execute the branch body
                        let mut result = ExecResult::success("");
                        for stmt in &branch.body {
                            let flow = self.execute_stmt_flow(stmt).await?;
                            match flow {
                                ControlFlow::Normal(r) => {
                                    accumulate_result(&mut result, &r);
                                    self.drain_stderr_into(&mut result).await;
                                }
                                other => {
                                    self.drain_stderr_into(&mut result).await;
                                    return Ok(other);
                                }
                            }
                        }
                        return Ok(ControlFlow::ok(result));
                    }
                }

                // No match - return success with empty output (like sh)
                Ok(ControlFlow::ok(ExecResult::success("")))
            }
            Stmt::Break(levels) => {
                Ok(ControlFlow::break_n(levels.unwrap_or(1)))
            }
            Stmt::Continue(levels) => {
                Ok(ControlFlow::continue_n(levels.unwrap_or(1)))
            }
            Stmt::Return(expr) => {
                // return [N] - N becomes the exit code, NOT stdout
                // Shell semantics: return sets exit code, doesn't produce output
                let result = if let Some(e) = expr {
                    let val = self.eval_expr_async(e).await?;
                    let code = crate::interpreter::value_to_exit_code(&val)
                        .map_err(|e| anyhow::anyhow!("return: {}", e))?;
                    ExecResult::from_parts(code, String::new(), String::new(), None)
                } else {
                    ExecResult::success("")
                };
                Ok(ControlFlow::return_value(result))
            }
            Stmt::Exit(expr) => {
                let code = if let Some(e) = expr {
                    let val = self.eval_expr_async(e).await?;
                    crate::interpreter::value_to_exit_code(&val)
                        .map_err(|e| anyhow::anyhow!("exit: {}", e))?
                } else {
                    0
                };
                Ok(ControlFlow::exit_code(code))
            }
            Stmt::ToolDef(tool_def) => {
                let mut user_tools = self.user_tools.write().await;
                user_tools.insert(tool_def.name.clone(), tool_def.clone());
                Ok(ControlFlow::ok(ExecResult::success("")))
            }
            Stmt::AndChain { left, right } => {
                // cmd1 && cmd2 - run cmd2 only if cmd1 succeeds (exit code 0)
                // Suppress errexit for the left side — && handles failure itself.
                {
                    let mut scope = self.scope.write().await;
                    scope.suppress_errexit();
                }
                let left_flow = match self.execute_stmt_flow(left).await {
                    Ok(f) => f,
                    Err(e) => {
                        let mut scope = self.scope.write().await;
                        scope.unsuppress_errexit();
                        return Err(e);
                    }
                };
                {
                    let mut scope = self.scope.write().await;
                    scope.unsuppress_errexit();
                }
                match left_flow {
                    ControlFlow::Normal(mut left_result) => {
                        self.drain_stderr_into(&mut left_result).await;
                        self.update_last_result(&left_result).await;
                        if left_result.ok() {
                            let right_flow = self.execute_stmt_flow(right).await?;
                            match right_flow {
                                ControlFlow::Normal(mut right_result) => {
                                    self.drain_stderr_into(&mut right_result).await;
                                    self.update_last_result(&right_result).await;
                                    let mut combined = left_result;
                                    accumulate_result(&mut combined, &right_result);
                                    Ok(ControlFlow::ok(combined))
                                }
                                other => Ok(other),
                            }
                        } else {
                            Ok(ControlFlow::ok(left_result))
                        }
                    }
                    _ => Ok(left_flow),
                }
            }
            Stmt::OrChain { left, right } => {
                // cmd1 || cmd2 - run cmd2 only if cmd1 fails (non-zero exit code)
                // Suppress errexit for the left side — || handles failure itself.
                {
                    let mut scope = self.scope.write().await;
                    scope.suppress_errexit();
                }
                let left_flow = match self.execute_stmt_flow(left).await {
                    Ok(f) => f,
                    Err(e) => {
                        let mut scope = self.scope.write().await;
                        scope.unsuppress_errexit();
                        return Err(e);
                    }
                };
                {
                    let mut scope = self.scope.write().await;
                    scope.unsuppress_errexit();
                }
                match left_flow {
                    ControlFlow::Normal(mut left_result) => {
                        self.drain_stderr_into(&mut left_result).await;
                        self.update_last_result(&left_result).await;
                        if !left_result.ok() {
                            let right_flow = self.execute_stmt_flow(right).await?;
                            match right_flow {
                                ControlFlow::Normal(mut right_result) => {
                                    self.drain_stderr_into(&mut right_result).await;
                                    self.update_last_result(&right_result).await;
                                    let mut combined = left_result;
                                    accumulate_result(&mut combined, &right_result);
                                    Ok(ControlFlow::ok(combined))
                                }
                                other => Ok(other),
                            }
                        } else {
                            Ok(ControlFlow::ok(left_result))
                        }
                    }
                    _ => Ok(left_flow), // Propagate non-normal flow
                }
            }
            Stmt::Test(test_expr) => {
                let is_true = self.eval_test_async(test_expr).await?;
                if is_true {
                    Ok(ControlFlow::ok(ExecResult::success("")))
                } else {
                    Ok(ControlFlow::ok(ExecResult::failure(1, "")))
                }
            }
            Stmt::Empty => Ok(ControlFlow::ok(ExecResult::success(""))),
        }
        }.instrument(span))
    }

    /// Execute a pipeline.
    #[tracing::instrument(level = "debug", skip(self, pipeline), fields(background = pipeline.background, command_count = pipeline.commands.len()))]
    async fn execute_pipeline(&self, pipeline: &crate::ast::Pipeline) -> Result<ExecResult> {
        if pipeline.commands.is_empty() {
            return Ok(ExecResult::success(""));
        }

        // Handle background execution (`&` operator)
        if pipeline.background {
            return self.execute_background(pipeline).await;
        }

        // All commands go through the runner with the Kernel as dispatcher.
        // This is the single execution path — no fast path for single commands.
        //
        // IMPORTANT: We snapshot exec_ctx into a local context and release the
        // lock before running. This prevents deadlocks when dispatch_command
        // is called from within the pipeline and recursively triggers another
        // pipeline (e.g., via user-defined tools).
        let mut ctx = {
            let ec = self.exec_ctx.read().await;
            let scope = self.scope.read().await;
            ExecContext {
                backend: ec.backend.clone(),
                scope: scope.clone(),
                cwd: ec.cwd.clone(),
                prev_cwd: ec.prev_cwd.clone(),
                stdin: None,
                stdin_data: None,
                pipe_stdin: None,
                pipe_stdout: None,
                stderr: ec.stderr.clone(),
                tool_schemas: ec.tool_schemas.clone(),
                tools: ec.tools.clone(),
                job_manager: ec.job_manager.clone(),
                pipeline_position: PipelinePosition::Only,
                interactive: self.interactive,
                aliases: ec.aliases.clone(),
                ignore_config: ec.ignore_config.clone(),
                output_limit: ec.output_limit.clone(),
                allow_external_commands: self.allow_external_commands,
                nonce_store: ec.nonce_store.clone(),
                trash_backend: ec.trash_backend.clone(),
                #[cfg(all(unix, feature = "native"))]
                terminal_state: ec.terminal_state.clone(),
                dispatcher: self.dispatcher(),
                cancel: {
                    #[allow(clippy::expect_used)]
                    let token = self.cancel_token.lock().expect("cancel_token poisoned");
                    token.clone()
                },
            }
        }; // locks released

        let mut result = self.runner.run(&pipeline.commands, &mut ctx, self).await;

        // Post-hoc spill check (catches builtins and fast external commands)
        if ctx.output_limit.is_enabled() {
            let _ = crate::output_limit::spill_if_needed(&mut result, &ctx.output_limit).await;
        }

        // Signal spill with exit 3; agent reads the spill file directly
        // (use `set +o output-limit` before cat/head/tail to bypass the limit)
        if result.did_spill {
            result.original_code = Some(result.code);
            result.code = 3;
        }

        // Sync changes back from context
        {
            let mut ec = self.exec_ctx.write().await;
            ec.cwd = ctx.cwd.clone();
            ec.prev_cwd = ctx.prev_cwd.clone();
            ec.aliases = ctx.aliases.clone();
            ec.ignore_config = ctx.ignore_config.clone();
            ec.output_limit = ctx.output_limit.clone();
        }
        {
            let mut scope = self.scope.write().await;
            *scope = ctx.scope.clone();
        }

        Ok(result)
    }

    /// Execute a pipeline in the background.
    ///
    /// The command is spawned as a tokio task, registered with the JobManager,
    /// and its output is captured via BoundedStreams. The job is observable via
    /// `/v/jobs/{id}/stdout`, `/v/jobs/{id}/stderr`, and `/v/jobs/{id}/status`.
    ///
    /// Returns immediately with a job ID like "[1]".
    #[tracing::instrument(level = "debug", skip(self, pipeline), fields(command_count = pipeline.commands.len()))]
    async fn execute_background(&self, pipeline: &crate::ast::Pipeline) -> Result<ExecResult> {
        use tokio::sync::oneshot;

        // Format the command for display in /v/jobs/{id}/command
        let command_str = self.format_pipeline(pipeline);

        // Create bounded streams for output capture
        let stdout = Arc::new(BoundedStream::default_size());
        let stderr = Arc::new(BoundedStream::default_size());

        // Create channel for result notification
        let (tx, rx) = oneshot::channel();

        // Register with JobManager to get job ID and create VFS entries
        let job_id = self.jobs.register_with_streams(
            command_str.clone(),
            rx,
            stdout.clone(),
            stderr.clone(),
        ).await;

        // Fork the kernel for this background job. The fork snapshots the
        // parent's scope/cwd/aliases/user_tools so mutations stay isolated,
        // while sharing the job manager, VFS, and tool registry. The fork's
        // full dispatch chain (user tools, .kai scripts, `$(...)` in args)
        // is available here — something BackendDispatcher couldn't provide.
        let fork = self.fork().await;
        let runner = self.runner.clone();
        let commands = pipeline.commands.clone();

        // Snapshot the fork's exec_ctx for the spawned task. We have to do
        // this before tokio::spawn because the fork's exec_ctx is behind a
        // tokio RwLock and we want the spawned task to own its ctx.
        let mut bg_ctx = {
            let ec = fork.exec_ctx.read().await;
            ec.child_for_pipeline()
        };
        bg_ctx.scope = fork.scope.read().await.clone();
        // The fork's dispatcher points at the fork itself; set it here so
        // builtins inside the background task (e.g. timeout) re-dispatch
        // through the fork, not the parent.
        bg_ctx.dispatcher = fork.dispatcher();

        // Spawn the background task
        tokio::spawn(async move {
            // runner.run needs a &dyn CommandDispatcher; fork.as_ref()
            // gives us that (Kernel implements CommandDispatcher).
            let result = runner.run(&commands, &mut bg_ctx, fork.as_ref()).await;

            // Write output to streams
            let text = result.text_out();
            if !text.is_empty() {
                stdout.write(text.as_bytes()).await;
            }
            if !result.err.is_empty() {
                stderr.write(result.err.as_bytes()).await;
            }

            // Close streams
            stdout.close().await;
            stderr.close().await;

            // Send result to JobManager (ignore error if receiver dropped)
            let _ = tx.send(result);
        });

        Ok(ExecResult::success(format!("[{}]", job_id)))
    }

    /// Format a pipeline as a command string for display.
    fn format_pipeline(&self, pipeline: &crate::ast::Pipeline) -> String {
        pipeline.commands
            .iter()
            .map(|cmd| {
                let mut parts = vec![cmd.name.clone()];
                for arg in &cmd.args {
                    match arg {
                        Arg::Positional(expr) => {
                            parts.push(self.format_expr(expr));
                        }
                        Arg::Named { key, value } => {
                            parts.push(format!("{}={}", key, self.format_expr(value)));
                        }
                        Arg::ShortFlag(name) => {
                            parts.push(format!("-{}", name));
                        }
                        Arg::LongFlag(name) => {
                            parts.push(format!("--{}", name));
                        }
                        Arg::DoubleDash => {
                            parts.push("--".to_string());
                        }
                    }
                }
                parts.join(" ")
            })
            .collect::<Vec<_>>()
            .join(" | ")
    }

    /// Format an expression as a string for display.
    fn format_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::Literal(Value::String(s)) => {
                if s.contains(' ') || s.contains('"') {
                    format!("'{}'", s.replace('\'', "\\'"))
                } else {
                    s.clone()
                }
            }
            Expr::Literal(Value::Int(i)) => i.to_string(),
            Expr::Literal(Value::Float(f)) => f.to_string(),
            Expr::Literal(Value::Bool(b)) => b.to_string(),
            Expr::Literal(Value::Null) => "null".to_string(),
            Expr::VarRef(path) => {
                let name = path.segments.iter()
                    .map(|seg| match seg {
                        crate::ast::VarSegment::Field(f) => f.clone(),
                    })
                    .collect::<Vec<_>>()
                    .join(".");
                format!("${{{}}}", name)
            }
            Expr::Interpolated(_) => "\"...\"".to_string(),
            Expr::HereDocBody { .. } => "<<heredoc".to_string(),
            _ => "...".to_string(),
        }
    }

    /// Execute a single command.
    async fn execute_command(&self, name: &str, args: &[Arg]) -> Result<ExecResult> {
        self.execute_command_depth(name, args, 0).await
    }

    #[tracing::instrument(level = "info", skip(self, args, alias_depth), fields(command = %name), err)]
    async fn execute_command_depth(&self, name: &str, args: &[Arg], alias_depth: u8) -> Result<ExecResult> {
        // Special built-ins
        match name {
            "true" => return Ok(ExecResult::success("")),
            "false" => return Ok(ExecResult::failure(1, "")),
            "source" | "." => return self.execute_source(args).await,
            _ => {}
        }

        // Alias expansion (with recursion limit)
        if alias_depth < 10 {
            let alias_value = {
                let ctx = self.exec_ctx.read().await;
                ctx.aliases.get(name).cloned()
            };
            if let Some(alias_val) = alias_value {
                // Split alias value into command + args
                let parts: Vec<&str> = alias_val.split_whitespace().collect();
                if let Some((alias_cmd, alias_args)) = parts.split_first() {
                    let mut new_args: Vec<Arg> = alias_args
                        .iter()
                        .map(|a| Arg::Positional(Expr::Literal(Value::String(a.to_string()))))
                        .collect();
                    new_args.extend_from_slice(args);
                    return Box::pin(self.execute_command_depth(alias_cmd, &new_args, alias_depth + 1)).await;
                }
            }
        }

        // Handle /v/bin/ prefix — dispatch to builtins via virtual path
        if let Some(builtin_name) = name.strip_prefix("/v/bin/") {
            return match self.tools.get(builtin_name) {
                Some(_) => Box::pin(self.execute_command_depth(builtin_name, args, alias_depth)).await,
                None => Ok(ExecResult::failure(127, format!("command not found: {}", name))),
            };
        }

        // Check user-defined tools first
        {
            let user_tools = self.user_tools.read().await;
            if let Some(tool_def) = user_tools.get(name) {
                let tool_def = tool_def.clone();
                drop(user_tools);
                return self.execute_user_tool(tool_def, args).await;
            }
        }

        // Look up builtin tool
        let tool = match self.tools.get(name) {
            Some(t) => t,
            None => {
                // Try executing as .kai script from PATH
                if let Some(result) = self.try_execute_script(name, args).await? {
                    return Ok(result);
                }
                // Try executing as external command from PATH
                if let Some(result) = self.try_execute_external(name, args).await? {
                    return Ok(result);
                }

                // Try backend-registered tools (embedder engines, etc.)
                // Look up tool schema for positional→named mapping.
                // Clone backend and drop read lock before awaiting (may involve network I/O).
                // Backend tools expect named JSON params, so enable positional mapping.
                let backend = self.exec_ctx.read().await.backend.clone();
                let tool_schema = backend.get_tool(name).await.ok().flatten().map(|t| {
                    let mut s = t.schema;
                    s.map_positionals = true;
                    s
                });
                let tool_args = self.build_args_async(args, tool_schema.as_ref()).await?;
                let mut ctx = self.exec_ctx.write().await;
                {
                    let scope = self.scope.read().await;
                    ctx.scope = scope.clone();
                }
                let backend = ctx.backend.clone();
                match backend.call_tool(name, tool_args, &mut ctx).await {
                    Ok(tool_result) => {
                        let mut scope = self.scope.write().await;
                        *scope = ctx.scope.clone();
                        let mut exec = ExecResult::from_output(
                            tool_result.code as i64, tool_result.stdout, tool_result.stderr,
                        );
                        exec.set_output(tool_result.output);
                        return Ok(exec);
                    }
                    Err(BackendError::ToolNotFound(_)) => {
                        // Fall through to "command not found"
                    }
                    Err(e) => {
                        // Backend dispatch is last-resort lookup — if it fails
                        // for any reason, the command simply doesn't exist.
                        tracing::debug!("backend error for {name}: {e}");
                    }
                }

                return Ok(ExecResult::failure(127, format!("command not found: {}", name)));
            }
        };

        // Build arguments (async to support command substitution, schema-aware for flag values)
        let schema = tool.schema();
        let mut tool_args = self.build_args_async(args, Some(&schema)).await?;
        let output_format = extract_output_format(&mut tool_args, Some(&schema));

        // --help / -h: show help unless the tool's schema claims that flag
        let schema_claims = |flag: &str| -> bool {
            let bare = flag.trim_start_matches('-');
            schema.params.iter().any(|p| p.matches_flag(flag) || p.matches_flag(bare))
        };
        let wants_help =
            (tool_args.flags.contains("help") && !schema_claims("help"))
            || (tool_args.flags.contains("h") && !schema_claims("-h"));
        if wants_help {
            let help_topic = crate::help::HelpTopic::Tool(name.to_string());
            let ctx = self.exec_ctx.read().await;
            let content = crate::help::get_help(&help_topic, &ctx.tool_schemas);
            return Ok(ExecResult::with_output(crate::interpreter::OutputData::text(content)));
        }

        // Snapshot exec_ctx into a local context and release the write lock
        // before calling tool.execute. Holding the write across tool execution
        // would deadlock any builtin that re-dispatches through ctx.dispatcher
        // (timeout, scatter) — the inner dispatch_command needs its own
        // exec_ctx.write() and would block forever.
        let mut ctx = {
            let ec = self.exec_ctx.write().await;
            let scope = self.scope.read().await;
            ExecContext {
                backend: ec.backend.clone(),
                scope: scope.clone(),
                cwd: ec.cwd.clone(),
                prev_cwd: ec.prev_cwd.clone(),
                stdin: ec.stdin.clone(),
                stdin_data: ec.stdin_data.clone(),
                pipe_stdin: None, // streaming pipes are per-pipeline; not snapshotted
                pipe_stdout: None,
                stderr: ec.stderr.clone(),
                tool_schemas: ec.tool_schemas.clone(),
                tools: ec.tools.clone(),
                job_manager: ec.job_manager.clone(),
                pipeline_position: ec.pipeline_position,
                interactive: self.interactive,
                aliases: ec.aliases.clone(),
                ignore_config: ec.ignore_config.clone(),
                output_limit: ec.output_limit.clone(),
                allow_external_commands: self.allow_external_commands,
                nonce_store: ec.nonce_store.clone(),
                trash_backend: ec.trash_backend.clone(),
                #[cfg(all(unix, feature = "native"))]
                terminal_state: ec.terminal_state.clone(),
                dispatcher: self.dispatcher(),
                // Use ec.cancel (set by dispatch_command from the runner's
                // ctx.cancel) so any builtin-swapped child token (e.g. timeout's
                // child token) reaches the spawned external via wait_or_kill.
                // Falls back to the kernel's own token when ec.cancel is the
                // default fresh token from a non-dispatch path.
                cancel: ec.cancel.clone(),
            }
        }; // both locks released — tool.execute can re-dispatch safely

        // Move stdin out of self.exec_ctx into the snapshot (consumed-by-tool
        // semantics): take() so a later dispatch doesn't see stale stdin.
        // Done after the snapshot above so we hold the write briefly.
        {
            let mut ec = self.exec_ctx.write().await;
            ctx.stdin = ec.stdin.take();
            ctx.stdin_data = ec.stdin_data.take();
            ctx.pipe_stdin = ec.pipe_stdin.take();
            ctx.pipe_stdout = ec.pipe_stdout.take();
        }

        let result = tool.execute(tool_args, &mut ctx).await;

        // Sync mutations back. Tools may have changed scope (set/cd),
        // cwd/prev_cwd (cd), and aliases (alias). Also return any unused pipe
        // endpoints to self.exec_ctx so dispatch_command's post-execute sync
        // hands them back to the pipeline runner — the runner uses
        // stage_ctx.pipe_stdout to write the result to the next stage when
        // the tool itself didn't take and write to it.
        {
            let mut scope = self.scope.write().await;
            *scope = ctx.scope.clone();
        }
        {
            let mut ec = self.exec_ctx.write().await;
            ec.cwd = ctx.cwd;
            ec.prev_cwd = ctx.prev_cwd;
            ec.aliases = ctx.aliases;
            ec.pipe_stdin = ctx.pipe_stdin.take();
            ec.pipe_stdout = ctx.pipe_stdout.take();
        }

        let result = match output_format {
            Some(format) => apply_output_format(result, format),
            None => result,
        };

        Ok(result)
    }

    /// Pull `consumes` positional args after a non-bool flag and stash them
    /// on `tool_args.named` under the canonical param name.
    ///
    /// - `consumes == 1` keeps the historical contract: a single scalar value.
    /// - `consumes > 1` accumulates each occurrence as an inner
    ///   `serde_json::Value::Array` inside `named[canonical] =
    ///   Value::Json(Array(...))`, preserving invocation order. This is the
    ///   shape jq's `--arg NAME VAL` / `--argjson NAME VAL` land in.
    ///
    /// Errors loudly if the flag is missing required positionals — matches
    /// kaish's "no silent fallback" posture and mirrors real jq, which
    /// errors on `--arg NAME` with no value.
    #[allow(clippy::too_many_arguments)]
    async fn consume_flag_positionals(
        &self,
        args: &[Arg],
        flag_name: &str,
        canonical: &str,
        consumes: usize,
        positional_indices: &[usize],
        consumed: &mut std::collections::HashSet<usize>,
        current_idx: usize,
        tool_args: &mut ToolArgs,
    ) -> Result<()> {
        let mut collected: Vec<Value> = Vec::with_capacity(consumes.max(1));
        for _ in 0..consumes.max(1) {
            let next_pos = positional_indices
                .iter()
                .find(|idx| **idx > current_idx && !consumed.contains(idx))
                .copied();
            match next_pos {
                Some(pos_idx) => {
                    if let Arg::Positional(expr) = &args[pos_idx] {
                        let value = self.eval_expr_async(expr).await?;
                        let value = apply_tilde_expansion(value);
                        collected.push(value);
                        consumed.insert(pos_idx);
                    }
                }
                None => {
                    if consumes <= 1 && collected.is_empty() {
                        // Back-compat: a flag with no follow-up positional
                        // becomes a bare flag. `--path` with nothing after
                        // lands in `flags`, same as before this refactor.
                        tool_args.flags.insert(flag_name.to_string());
                        return Ok(());
                    }
                    anyhow::bail!(
                        "--{flag_name} requires {consumes} argument{}, got {}",
                        if consumes == 1 { "" } else { "s" },
                        collected.len()
                    );
                }
            }
        }

        if consumes <= 1 {
            if let Some(v) = collected.pop() {
                tool_args.named.insert(canonical.to_string(), v);
            }
            return Ok(());
        }

        // Multi-consume: accumulate under named[canonical] as array-of-arrays.
        let occ: Vec<serde_json::Value> = collected
            .into_iter()
            .map(|v| crate::interpreter::value_to_json(&v))
            .collect();
        let entry = tool_args
            .named
            .entry(canonical.to_string())
            .or_insert_with(|| Value::Json(serde_json::Value::Array(Vec::new())));
        if let Value::Json(serde_json::Value::Array(outer)) = entry {
            outer.push(serde_json::Value::Array(occ));
        } else {
            anyhow::bail!(
                "--{flag_name}: named[{canonical}] already holds a non-array value"
            );
        }
        Ok(())
    }

    /// Build tool arguments from AST args.
    ///
    /// Uses async evaluation to support command substitution in arguments.
    async fn build_args_async(&self, args: &[Arg], schema: Option<&crate::tools::ToolSchema>) -> Result<ToolArgs> {
        let mut tool_args = ToolArgs::new();
        let param_lookup = schema.map(schema_param_lookup).unwrap_or_default();

        // Track which positional indices have been consumed as flag values
        let mut consumed: std::collections::HashSet<usize> = std::collections::HashSet::new();
        let mut past_double_dash = false;

        // Find positional arg indices for flag value consumption
        let positional_indices: Vec<usize> = args.iter().enumerate()
            .filter_map(|(i, a)| matches!(a, Arg::Positional(_)).then_some(i))
            .collect();

        let mut i = 0;
        while i < args.len() {
            match &args[i] {
                Arg::DoubleDash => {
                    past_double_dash = true;
                }
                Arg::Positional(expr) => {
                    if !consumed.contains(&i) {
                        // Glob expansion: bare glob patterns expand to matching files
                        if let Expr::GlobPattern(pattern) = expr {
                            let glob_enabled = {
                                let scope = self.scope.read().await;
                                scope.glob_enabled()
                            };
                            if glob_enabled {
                                let (paths, cwd) = {
                                    let ctx = self.exec_ctx.read().await;
                                    let paths = ctx.expand_glob(pattern).await
                                        .map_err(|e| anyhow::anyhow!("glob: {}", e))?;
                                    let cwd = ctx.resolve_path(".");
                                    (paths, cwd)
                                };
                                if paths.is_empty() {
                                    return Err(anyhow::anyhow!("no matches: {}", pattern));
                                }
                                for path in paths {
                                    let display = if !pattern.starts_with('/') {
                                        path.strip_prefix(&cwd)
                                            .unwrap_or(&path)
                                            .to_string_lossy().into_owned()
                                    } else {
                                        path.to_string_lossy().into_owned()
                                    };
                                    tool_args.positional.push(Value::String(display));
                                }
                                i += 1;
                                continue;
                            }
                        }
                        let value = self.eval_expr_async(expr).await?;
                        let value = apply_tilde_expansion(value);
                        tool_args.positional.push(value);
                    }
                }
                Arg::Named { key, value } => {
                    let val = self.eval_expr_async(value).await?;
                    let val = apply_tilde_expansion(val);
                    tool_args.named.insert(key.clone(), val);
                }
                Arg::ShortFlag(name) => {
                    if past_double_dash {
                        tool_args.positional.push(Value::String(format!("-{name}")));
                    } else if name.len() == 1 {
                        let flag_name = name.as_str();
                        let lookup = param_lookup.get(flag_name);
                        let is_bool = lookup.map(|(_, typ, _)| is_bool_type(typ)).unwrap_or(true);

                        if is_bool {
                            tool_args.flags.insert(flag_name.to_string());
                        } else {
                            // Non-bool: consume `consumes` positionals as value(s)
                            let canonical = lookup.map(|(n, _, _)| *n).unwrap_or(flag_name);
                            let consumes = lookup.map(|(_, _, c)| *c).unwrap_or(1);
                            self.consume_flag_positionals(
                                args,
                                name,
                                canonical,
                                consumes,
                                &positional_indices,
                                &mut consumed,
                                i,
                                &mut tool_args,
                            )
                            .await?;
                        }
                    } else if let Some(&(canonical, typ, consumes)) = param_lookup.get(name.as_str()) {
                        // Multi-char short flag matches a schema param (POSIX style: -name value)
                        if is_bool_type(typ) {
                            tool_args.flags.insert(canonical.to_string());
                        } else {
                            self.consume_flag_positionals(
                                args,
                                name,
                                canonical,
                                consumes,
                                &positional_indices,
                                &mut consumed,
                                i,
                                &mut tool_args,
                            )
                            .await?;
                        }
                    } else {
                        // Multi-char combined flags like -la: always boolean
                        for c in name.chars() {
                            tool_args.flags.insert(c.to_string());
                        }
                    }
                }
                Arg::LongFlag(name) => {
                    if past_double_dash {
                        tool_args.positional.push(Value::String(format!("--{name}")));
                    } else {
                        let lookup = param_lookup.get(name.as_str());
                        let is_bool = lookup.map(|(_, typ, _)| is_bool_type(typ)).unwrap_or(true);

                        if is_bool {
                            tool_args.flags.insert(name.clone());
                        } else {
                            let canonical = lookup.map(|(n, _, _)| *n).unwrap_or(name.as_str());
                            let consumes = lookup.map(|(_, _, c)| *c).unwrap_or(1);
                            self.consume_flag_positionals(
                                args,
                                name,
                                canonical,
                                consumes,
                                &positional_indices,
                                &mut consumed,
                                i,
                                &mut tool_args,
                            )
                            .await?;
                        }
                    }
                }
            }
            i += 1;
        }

        // Map remaining positionals to unfilled non-bool schema params (in order).
        // This enables `drift_push "abc" "hello"` → named["target_ctx"] = "abc", named["content"] = "hello"
        // Positionals that appeared after `--` are never mapped (they're raw data).
        // Only for backend/external tools (map_positionals=true). Builtins handle their own positionals.
        if let Some(schema) = schema.filter(|s| s.map_positionals) {
            let pre_dash_count = if past_double_dash {
                let dash_pos = args.iter().position(|a| matches!(a, Arg::DoubleDash)).unwrap_or(args.len());
                positional_indices.iter()
                    .filter(|idx| **idx < dash_pos && !consumed.contains(idx))
                    .count()
            } else {
                tool_args.positional.len()
            };

            let mut remaining = Vec::new();
            let mut positional_iter = tool_args.positional.drain(..).enumerate();

            for param in &schema.params {
                if tool_args.named.contains_key(&param.name) || tool_args.flags.contains(&param.name) {
                    continue;
                }
                if is_bool_type(&param.param_type) {
                    continue;
                }
                loop {
                    match positional_iter.next() {
                        Some((idx, val)) if idx < pre_dash_count => {
                            tool_args.named.insert(param.name.clone(), val);
                            break;
                        }
                        Some((_, val)) => {
                            remaining.push(val);
                        }
                        None => break,
                    }
                }
            }

            remaining.extend(positional_iter.map(|(_, v)| v));
            tool_args.positional = remaining;
        }

        Ok(tool_args)
    }

    /// Build arguments as flat string list for external commands.
    ///
    /// Unlike `build_args_async` which separates flags into a HashSet (for schema-aware builtins),
    /// this preserves the original flag format as strings for external commands:
    /// - `-l` stays as `-l`
    /// - `--verbose` stays as `--verbose`
    /// - `key=value` stays as `key=value`
    ///
    /// This is what external commands expect in their argv.
    #[cfg(feature = "native")]
    async fn build_args_flat(&self, args: &[Arg]) -> Result<Vec<String>> {
        let mut argv = Vec::new();
        for arg in args {
            match arg {
                Arg::Positional(expr) => {
                    // Glob expansion for external commands
                    if let Expr::GlobPattern(pattern) = expr {
                        let glob_enabled = {
                            let scope = self.scope.read().await;
                            scope.glob_enabled()
                        };
                        if glob_enabled {
                            let (paths, cwd) = {
                                let ctx = self.exec_ctx.read().await;
                                let paths = ctx.expand_glob(pattern).await
                                    .map_err(|e| anyhow::anyhow!("glob: {}", e))?;
                                let cwd = ctx.resolve_path(".");
                                (paths, cwd)
                            };
                            if paths.is_empty() {
                                return Err(anyhow::anyhow!("no matches: {}", pattern));
                            }
                            for path in paths {
                                let display = if !pattern.starts_with('/') {
                                    path.strip_prefix(&cwd)
                                        .unwrap_or(&path)
                                        .to_string_lossy().into_owned()
                                } else {
                                    path.to_string_lossy().into_owned()
                                };
                                argv.push(display);
                            }
                            continue;
                        }
                    }
                    let value = self.eval_expr_async(expr).await?;
                    let value = apply_tilde_expansion(value);
                    argv.push(value_to_string(&value));
                }
                Arg::Named { key, value } => {
                    let val = self.eval_expr_async(value).await?;
                    let val = apply_tilde_expansion(val);
                    argv.push(format!("{}={}", key, value_to_string(&val)));
                }
                Arg::ShortFlag(name) => {
                    // Preserve original format: -l, -la (combined flags)
                    argv.push(format!("-{}", name));
                }
                Arg::LongFlag(name) => {
                    // Preserve original format: --verbose
                    argv.push(format!("--{}", name));
                }
                Arg::DoubleDash => {
                    // Preserve the -- marker
                    argv.push("--".to_string());
                }
            }
        }
        Ok(argv)
    }

    /// Async expression evaluator that supports command substitution.
    ///
    /// This is used for contexts where expressions may contain `$(...)` command
    /// substitution. Unlike the sync `eval_expr`, this can execute pipelines.
    fn eval_expr_async<'a>(&'a self, expr: &'a Expr) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value>> + Send + 'a>> {
        Box::pin(async move {
        match expr {
            Expr::Literal(value) => Ok(value.clone()),
            Expr::VarRef(path) => {
                let scope = self.scope.read().await;
                scope.resolve_path(path)
                    .ok_or_else(|| anyhow::anyhow!("undefined variable"))
            }
            Expr::Interpolated(parts) => {
                let mut result = String::new();
                for part in parts {
                    result.push_str(&self.eval_string_part_async(part).await?);
                }
                Ok(Value::String(result))
            }
            Expr::HereDocBody { parts, strip_tabs } => {
                let mut result = String::new();
                for sp in parts {
                    result.push_str(&self.eval_string_part_async(&sp.part).await?);
                }
                if *strip_tabs {
                    Ok(Value::String(crate::interpreter::strip_leading_tabs(&result)))
                } else {
                    Ok(Value::String(result))
                }
            }
            Expr::BinaryOp { left, op, right } => match op {
                BinaryOp::And => {
                    let left_val = self.eval_expr_async(left).await?;
                    if !is_truthy(&left_val) {
                        return Ok(left_val);
                    }
                    self.eval_expr_async(right).await
                }
                BinaryOp::Or => {
                    let left_val = self.eval_expr_async(left).await?;
                    if is_truthy(&left_val) {
                        return Ok(left_val);
                    }
                    self.eval_expr_async(right).await
                }
            },
            Expr::CommandSubst(pipeline) => {
                // Snapshot scope+cwd before running — only output escapes,
                // not side effects like `cd` or variable assignments.
                let saved_scope = { self.scope.read().await.clone() };
                let saved_cwd = {
                    let ec = self.exec_ctx.read().await;
                    (ec.cwd.clone(), ec.prev_cwd.clone())
                };

                // Capture result without `?` — restore state unconditionally
                let run_result = self.execute_pipeline(pipeline).await;

                // Restore scope and cwd regardless of success/failure
                {
                    let mut scope = self.scope.write().await;
                    *scope = saved_scope;
                    if let Ok(ref r) = run_result {
                        scope.set_last_result(r.clone());
                    }
                }
                {
                    let mut ec = self.exec_ctx.write().await;
                    ec.cwd = saved_cwd.0;
                    ec.prev_cwd = saved_cwd.1;
                }

                // Now propagate the error
                let result = run_result?;

                // Prefer structured data (enables `for i in $(cmd)` iteration)
                if let Some(data) = &result.data {
                    Ok(data.clone())
                } else if let Some(output) = result.output() {
                    // Flat non-text node lists (glob, ls, tree) → iterable array
                    if output.is_flat() && !output.is_simple_text() && !output.root.is_empty() {
                        let items: Vec<serde_json::Value> = output.root.iter()
                            .map(|n| serde_json::Value::String(n.display_name().to_string()))
                            .collect();
                        Ok(Value::Json(serde_json::Value::Array(items)))
                    } else {
                        Ok(Value::String(result.text_out().trim_end().to_string()))
                    }
                } else {
                    // Otherwise return stdout as single string (NO implicit splitting)
                    Ok(Value::String(result.text_out().trim_end().to_string()))
                }
            }
            Expr::Test(test_expr) => {
                Ok(Value::Bool(self.eval_test_async(test_expr).await?))
            }
            Expr::Positional(n) => {
                let scope = self.scope.read().await;
                match scope.get_positional(*n) {
                    Some(s) => Ok(Value::String(s.to_string())),
                    None => Ok(Value::String(String::new())),
                }
            }
            Expr::AllArgs => {
                let scope = self.scope.read().await;
                Ok(Value::String(scope.all_args().join(" ")))
            }
            Expr::ArgCount => {
                let scope = self.scope.read().await;
                Ok(Value::Int(scope.arg_count() as i64))
            }
            Expr::VarLength(name) => {
                let scope = self.scope.read().await;
                match scope.get(name) {
                    Some(value) => Ok(Value::Int(value_to_string(value).len() as i64)),
                    None => Ok(Value::Int(0)),
                }
            }
            Expr::VarWithDefault { name, default } => {
                let scope = self.scope.read().await;
                let use_default = match scope.get(name) {
                    Some(value) => value_to_string(value).is_empty(),
                    None => true,
                };
                drop(scope); // Release the lock before recursive evaluation
                if use_default {
                    // Evaluate the default parts (supports nested expansions)
                    self.eval_string_parts_async(default).await.map(Value::String)
                } else {
                    let scope = self.scope.read().await;
                    scope.get(name).cloned().ok_or_else(|| anyhow::anyhow!("variable '{}' not found", name))
                }
            }
            Expr::Arithmetic(expr_str) => {
                let scope = self.scope.read().await;
                crate::arithmetic::eval_arithmetic(expr_str, &scope)
                    .map(Value::Int)
                    .map_err(|e| anyhow::anyhow!("arithmetic error: {}", e))
            }
            Expr::Command(cmd) => {
                // Execute command and return boolean based on exit code
                let result = self.execute_command(&cmd.name, &cmd.args).await?;
                Ok(Value::Bool(result.code == 0))
            }
            Expr::LastExitCode => {
                let scope = self.scope.read().await;
                Ok(Value::Int(scope.last_result().code))
            }
            Expr::CurrentPid => {
                let scope = self.scope.read().await;
                Ok(Value::Int(scope.pid() as i64))
            }
            Expr::GlobPattern(s) => Ok(Value::String(s.clone())),
        }
        })
    }

    /// Async helper to evaluate multiple StringParts into a single string.
    fn eval_string_parts_async<'a>(&'a self, parts: &'a [StringPart]) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send + 'a>> {
        Box::pin(async move {
            let mut result = String::new();
            for part in parts {
                result.push_str(&self.eval_string_part_async(part).await?);
            }
            Ok(result)
        })
    }

    /// Async helper to evaluate a StringPart.
    /// Evaluate a `[[ ]]` test expression asynchronously, routing file tests
    /// through the VFS backend instead of using raw `std::path`.
    fn eval_test_async<'a>(&'a self, test_expr: &'a TestExpr) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send + 'a>> {
        Box::pin(async move {
            match test_expr {
                TestExpr::FileTest { op, path } => {
                    let path_value = self.eval_expr_async(path).await?;
                    let path_str = value_to_string(&path_value);
                    let backend = self.exec_ctx.read().await.backend.clone();
                    let entry = backend.stat(std::path::Path::new(&path_str)).await.ok();
                    Ok(match op {
                        FileTestOp::Exists => entry.is_some(),
                        FileTestOp::IsFile => entry.as_ref().is_some_and(|e| e.is_file()),
                        FileTestOp::IsDir => entry.as_ref().is_some_and(|e| e.is_dir()),
                        FileTestOp::Readable => entry.is_some(),
                        FileTestOp::Writable => entry.as_ref().is_some_and(|e| {
                            e.permissions.is_none_or(|p| p & 0o222 != 0)
                        }),
                        FileTestOp::Executable => entry.as_ref().is_some_and(|e| {
                            e.permissions.is_some_and(|p| p & 0o111 != 0)
                        }),
                    })
                }
                TestExpr::StringTest { op, value } => {
                    let val = self.eval_expr_async(value).await?;
                    let s = value_to_string(&val);
                    Ok(match op {
                        crate::ast::StringTestOp::IsEmpty => s.is_empty(),
                        crate::ast::StringTestOp::IsNonEmpty => !s.is_empty(),
                    })
                }
                TestExpr::Comparison { left, op, right } => {
                    // Evaluate operands async (handles $(cmd)), then compare sync
                    let left_val = self.eval_expr_async(left).await?;
                    let right_val = self.eval_expr_async(right).await?;
                    let resolved = TestExpr::Comparison {
                        left: Box::new(Expr::Literal(left_val)),
                        op: *op,
                        right: Box::new(Expr::Literal(right_val)),
                    };
                    let expr = Expr::Test(Box::new(resolved));
                    let mut scope = self.scope.write().await;
                    let value = eval_expr(&expr, &mut scope)
                        .map_err(|e| anyhow::anyhow!("{}", e))?;
                    Ok(value_to_bool(&value))
                }
                TestExpr::And { left, right } => {
                    if !self.eval_test_async(left).await? {
                        Ok(false)
                    } else {
                        self.eval_test_async(right).await
                    }
                }
                TestExpr::Or { left, right } => {
                    if self.eval_test_async(left).await? {
                        Ok(true)
                    } else {
                        self.eval_test_async(right).await
                    }
                }
                TestExpr::Not { expr } => {
                    Ok(!self.eval_test_async(expr).await?)
                }
            }
        })
    }

    fn eval_string_part_async<'a>(&'a self, part: &'a StringPart) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send + 'a>> {
        Box::pin(async move {
            match part {
                StringPart::Literal(s) => Ok(s.clone()),
                StringPart::Var(path) => {
                    let scope = self.scope.read().await;
                    match scope.resolve_path(path) {
                        Some(value) => Ok(value_to_string(&value)),
                        None => Ok(String::new()), // Unset vars expand to empty
                    }
                }
                StringPart::VarWithDefault { name, default } => {
                    let scope = self.scope.read().await;
                    let use_default = match scope.get(name) {
                        Some(value) => value_to_string(value).is_empty(),
                        None => true,
                    };
                    drop(scope); // Release lock before recursive evaluation
                    if use_default {
                        // Evaluate the default parts (supports nested expansions)
                        self.eval_string_parts_async(default).await
                    } else {
                        let scope = self.scope.read().await;
                        Ok(value_to_string(scope.get(name).ok_or_else(|| anyhow::anyhow!("variable '{}' not found", name))?))
                    }
                }
            StringPart::VarLength(name) => {
                let scope = self.scope.read().await;
                match scope.get(name) {
                    Some(value) => Ok(value_to_string(value).len().to_string()),
                    None => Ok("0".to_string()),
                }
            }
            StringPart::Positional(n) => {
                let scope = self.scope.read().await;
                match scope.get_positional(*n) {
                    Some(s) => Ok(s.to_string()),
                    None => Ok(String::new()),
                }
            }
            StringPart::AllArgs => {
                let scope = self.scope.read().await;
                Ok(scope.all_args().join(" "))
            }
            StringPart::ArgCount => {
                let scope = self.scope.read().await;
                Ok(scope.arg_count().to_string())
            }
            StringPart::Arithmetic(expr) => {
                let scope = self.scope.read().await;
                match crate::arithmetic::eval_arithmetic(expr, &scope) {
                    Ok(value) => Ok(value.to_string()),
                    Err(_) => Ok(String::new()),
                }
            }
            StringPart::CommandSubst(pipeline) => {
                // Snapshot scope+cwd — command substitution in strings must
                // not leak side effects (e.g., `"dir: $(cd /; pwd)"` must not change cwd).
                let saved_scope = { self.scope.read().await.clone() };
                let saved_cwd = {
                    let ec = self.exec_ctx.read().await;
                    (ec.cwd.clone(), ec.prev_cwd.clone())
                };

                // Capture result without `?` — restore state unconditionally
                let run_result = self.execute_pipeline(pipeline).await;

                // Restore scope and cwd regardless of success/failure
                {
                    let mut scope = self.scope.write().await;
                    *scope = saved_scope;
                    if let Ok(ref r) = run_result {
                        scope.set_last_result(r.clone());
                    }
                }
                {
                    let mut ec = self.exec_ctx.write().await;
                    ec.cwd = saved_cwd.0;
                    ec.prev_cwd = saved_cwd.1;
                }

                // Now propagate the error
                let result = run_result?;

                Ok(result.text_out().trim_end_matches('\n').to_string())
            }
            StringPart::LastExitCode => {
                let scope = self.scope.read().await;
                Ok(scope.last_result().code.to_string())
            }
            StringPart::CurrentPid => {
                let scope = self.scope.read().await;
                Ok(scope.pid().to_string())
            }
        }
        })
    }

    /// Update the last result in scope.
    async fn update_last_result(&self, result: &ExecResult) {
        let mut scope = self.scope.write().await;
        scope.set_last_result(result.clone());
    }

    /// Drain accumulated pipeline stderr into a result.
    ///
    /// Called after each sub-statement inside control structures (`if`, `for`,
    /// `while`, `case`, `&&`, `||`) so that stderr appears incrementally rather
    /// than batching until the entire structure finishes.
    async fn drain_stderr_into(&self, result: &mut ExecResult) {
        let drained = {
            let mut receiver = self.stderr_receiver.lock().await;
            receiver.drain_lossy()
        };
        if !drained.is_empty() {
            if !result.err.is_empty() && !result.err.ends_with('\n') {
                result.err.push('\n');
            }
            result.err.push_str(&drained);
        }
    }

    /// Execute a user-defined function with local variable scoping.
    ///
    /// Functions push a new scope frame for local variables. Variables declared
    /// with `local` are scoped to the function; other assignments modify outer
    /// scopes (or create in root if new).
    async fn execute_user_tool(&self, def: ToolDef, args: &[Arg]) -> Result<ExecResult> {
        // 1. Build function args from AST args (async to support command substitution)
        let tool_args = self.build_args_async(args, None).await?;

        // 2. Push a new scope frame for local variables
        {
            let mut scope = self.scope.write().await;
            scope.push_frame();
        }

        // 3. Save current positional parameters and set new ones for this function
        let saved_positional = {
            let mut scope = self.scope.write().await;
            let saved = scope.save_positional();

            // Set up new positional parameters ($0 = function name, $1, $2, ... = args)
            let positional_args: Vec<String> = tool_args.positional
                .iter()
                .map(value_to_string)
                .collect();
            scope.set_positional(&def.name, positional_args);

            saved
        };

        // 3. Execute body statements with control flow handling
        // Accumulate output across statements (like sh)
        let mut accumulated_out = String::new();
        let mut accumulated_err = String::new();
        let mut last_code = 0i64;
        let mut last_data: Option<Value> = None;

        // Track execution error for propagation after cleanup
        let mut exec_error: Option<anyhow::Error> = None;
        let mut exit_code: Option<i64> = None;

        for stmt in &def.body {
            match self.execute_stmt_flow(stmt).await {
                Ok(flow) => {
                    // Drain pipeline stderr after each sub-statement.
                    let drained = {
                        let mut receiver = self.stderr_receiver.lock().await;
                        receiver.drain_lossy()
                    };
                    if !drained.is_empty() {
                        accumulated_err.push_str(&drained);
                    }

                    match flow {
                        ControlFlow::Normal(r) => {
                            accumulated_out.push_str(&r.text_out());
                            accumulated_err.push_str(&r.err);
                            last_code = r.code;
                            last_data = r.data;
                        }
                        ControlFlow::Return { value } => {
                            accumulated_out.push_str(&value.text_out());
                            accumulated_err.push_str(&value.err);
                            last_code = value.code;
                            last_data = value.data;
                            break;
                        }
                        ControlFlow::Exit { code } => {
                            exit_code = Some(code);
                            break;
                        }
                        ControlFlow::Break { result: r, .. } | ControlFlow::Continue { result: r, .. } => {
                            accumulated_out.push_str(&r.text_out());
                            accumulated_err.push_str(&r.err);
                            last_code = r.code;
                            last_data = r.data;
                        }
                    }
                }
                Err(e) => {
                    exec_error = Some(e);
                    break;
                }
            }
        }

        // 4. Pop scope frame and restore original positional parameters (unconditionally)
        {
            let mut scope = self.scope.write().await;
            scope.pop_frame();
            scope.set_positional(saved_positional.0, saved_positional.1);
        }

        // 5. Propagate error or exit after cleanup
        if let Some(e) = exec_error {
            return Err(e);
        }
        if let Some(code) = exit_code {
            return Ok(ExecResult::from_parts(code, accumulated_out, accumulated_err, last_data));
        }

        Ok(ExecResult::from_parts(last_code, accumulated_out, accumulated_err, last_data))
    }

    /// Execute the `source` / `.` command to include and run a script.
    ///
    /// Unlike regular tool execution, `source` executes in the CURRENT scope,
    /// allowing the sourced script to set variables and modify shell state.
    async fn execute_source(&self, args: &[Arg]) -> Result<ExecResult> {
        // Get the file path from the first positional argument
        let tool_args = self.build_args_async(args, None).await?;
        let path = match tool_args.positional.first() {
            Some(Value::String(s)) => s.clone(),
            Some(v) => value_to_string(v),
            None => {
                return Ok(ExecResult::failure(1, "source: missing filename"));
            }
        };

        // Resolve path relative to cwd
        let full_path = {
            let ctx = self.exec_ctx.read().await;
            if path.starts_with('/') {
                std::path::PathBuf::from(&path)
            } else {
                ctx.cwd.join(&path)
            }
        };

        // Read file content via backend
        let content = {
            let ctx = self.exec_ctx.read().await;
            match ctx.backend.read(&full_path, None).await {
                Ok(bytes) => {
                    String::from_utf8(bytes).map_err(|e| {
                        anyhow::anyhow!("source: {}: invalid UTF-8: {}", path, e)
                    })?
                }
                Err(e) => {
                    return Ok(ExecResult::failure(
                        1,
                        format!("source: {}: {}", path, e),
                    ));
                }
            }
        };

        // Parse the content
        let program = match crate::parser::parse(&content) {
            Ok(p) => p,
            Err(errors) => {
                let msg = errors
                    .iter()
                    .map(|e| format!("{}:{}: {}", path, e.span.start, e.message))
                    .collect::<Vec<_>>()
                    .join("\n");
                return Ok(ExecResult::failure(1, format!("source: {}", msg)));
            }
        };

        // Execute each statement in the CURRENT scope (not isolated)
        let mut result = ExecResult::success("");
        for stmt in program.statements {
            if matches!(stmt, crate::ast::Stmt::Empty) {
                continue;
            }

            match self.execute_stmt_flow(&stmt).await {
                Ok(flow) => {
                    self.drain_stderr_into(&mut result).await;
                    match flow {
                        ControlFlow::Normal(r) => {
                            result = r.clone();
                            self.update_last_result(&r).await;
                        }
                        ControlFlow::Break { .. } | ControlFlow::Continue { .. } => {
                            return Err(anyhow::anyhow!(
                                "source: {}: unexpected break/continue outside loop",
                                path
                            ));
                        }
                        ControlFlow::Return { value } => {
                            return Ok(value);
                        }
                        ControlFlow::Exit { code } => {
                            result.code = code;
                            return Ok(result);
                        }
                    }
                }
                Err(e) => {
                    return Err(e.context(format!("source: {}", path)));
                }
            }
        }

        Ok(result)
    }

    /// Try to execute a script from PATH directories.
    ///
    /// Searches PATH for `{name}.kai` files and executes them in isolated scope
    /// (like user-defined tools). Returns None if no script is found.
    async fn try_execute_script(&self, name: &str, args: &[Arg]) -> Result<Option<ExecResult>> {
        // Get PATH from scope (default to "/bin")
        let path_value = {
            let scope = self.scope.read().await;
            scope
                .get("PATH")
                .map(value_to_string)
                .unwrap_or_else(|| "/bin".to_string())
        };

        // Search PATH directories for script
        for dir in path_value.split(':') {
            if dir.is_empty() {
                continue;
            }

            // Build script path: {dir}/{name}.kai
            let script_path = PathBuf::from(dir).join(format!("{}.kai", name));

            // Check if script exists
            let exists = {
                let ctx = self.exec_ctx.read().await;
                ctx.backend.exists(&script_path).await
            };

            if !exists {
                continue;
            }

            // Read script content
            let content = {
                let ctx = self.exec_ctx.read().await;
                match ctx.backend.read(&script_path, None).await {
                    Ok(bytes) => match String::from_utf8(bytes) {
                        Ok(s) => s,
                        Err(e) => {
                            return Ok(Some(ExecResult::failure(
                                1,
                                format!("{}: invalid UTF-8: {}", script_path.display(), e),
                            )));
                        }
                    },
                    Err(e) => {
                        return Ok(Some(ExecResult::failure(
                            1,
                            format!("{}: {}", script_path.display(), e),
                        )));
                    }
                }
            };

            // Parse the script
            let program = match crate::parser::parse(&content) {
                Ok(p) => p,
                Err(errors) => {
                    let msg = errors
                        .iter()
                        .map(|e| format!("{}:{}: {}", script_path.display(), e.span.start, e.message))
                        .collect::<Vec<_>>()
                        .join("\n");
                    return Ok(Some(ExecResult::failure(1, msg)));
                }
            };

            // Build tool_args from args (async for command substitution support)
            let tool_args = self.build_args_async(args, None).await?;

            // Create isolated scope (like user tools)
            let mut isolated_scope = Scope::new();

            // Set up positional parameters ($0 = script name, $1, $2, ... = args)
            let positional_args: Vec<String> = tool_args.positional
                .iter()
                .map(value_to_string)
                .collect();
            isolated_scope.set_positional(name, positional_args);

            // Save current scope and swap with isolated scope
            let original_scope = {
                let mut scope = self.scope.write().await;
                std::mem::replace(&mut *scope, isolated_scope)
            };

            // Execute script statements — track outcome for cleanup
            let mut result = ExecResult::success("");
            let mut exec_error: Option<anyhow::Error> = None;
            let mut exit_code: Option<i64> = None;

            for stmt in program.statements {
                if matches!(stmt, crate::ast::Stmt::Empty) {
                    continue;
                }

                match self.execute_stmt_flow(&stmt).await {
                    Ok(flow) => {
                        match flow {
                            ControlFlow::Normal(r) => result = r,
                            ControlFlow::Return { value } => {
                                result = value;
                                break;
                            }
                            ControlFlow::Exit { code } => {
                                exit_code = Some(code);
                                break;
                            }
                            ControlFlow::Break { result: r, .. } | ControlFlow::Continue { result: r, .. } => {
                                result = r;
                            }
                        }
                    }
                    Err(e) => {
                        exec_error = Some(e);
                        break;
                    }
                }
            }

            // Restore original scope unconditionally
            {
                let mut scope = self.scope.write().await;
                *scope = original_scope;
            }

            // Propagate error or exit after cleanup
            if let Some(e) = exec_error {
                return Err(e.context(format!("script: {}", script_path.display())));
            }
            if let Some(code) = exit_code {
                result.code = code;
                return Ok(Some(result));
            }

            return Ok(Some(result));
        }

        // No script found
        Ok(None)
    }

    /// Try to execute an external command from PATH.
    ///
    /// This is the fallback when no builtin or user-defined tool matches.
    /// External commands receive a clean argv (flags preserved in their original format).
    ///
    /// # Requirements
    /// - Command must be found in PATH
    /// - Current working directory must be on a real filesystem (not virtual like /v)
    ///
    /// # Returns
    /// - `Ok(Some(result))` if command was found and executed
    /// - `Ok(None)` if command was not found in PATH
    /// - `Err` on execution errors
    #[cfg(not(feature = "native"))]
    async fn try_execute_external(&self, _name: &str, _args: &[Arg]) -> Result<Option<ExecResult>> {
        Ok(None)
    }

    /// Try to execute an external command from PATH.
    #[cfg(feature = "native")]
    #[tracing::instrument(level = "debug", skip(self, args), fields(command = %name))]
    async fn try_execute_external(&self, name: &str, args: &[Arg]) -> Result<Option<ExecResult>> {
        // Read the cancel token from `self.exec_ctx`, which `dispatch_command`
        // populates from the inbound ctx.cancel on every dispatch. This is
        // what makes the `timeout` builtin's swapped child token reach the
        // wait_or_kill discipline below — reading `self.cancel_token` would
        // give the kernel-wide token and miss the timeout's child cascade.
        let cancel = {
            let ec = self.exec_ctx.read().await;
            ec.cancel.clone()
        };
        let kill_grace = self.kill_grace;
        if !self.allow_external_commands {
            return Ok(None);
        }

        // Get real working directory for relative path resolution and child cwd.
        // If the CWD is virtual (no real filesystem path), skip external command
        // execution entirely — return None so the dispatch can fall through to
        // backend-registered tools.
        let real_cwd = {
            let ctx = self.exec_ctx.read().await;
            match ctx.backend.resolve_real_path(&ctx.cwd) {
                Some(p) => p,
                None => return Ok(None),
            }
        };

        let executable = if name.contains('/') {
            // Resolve relative paths (./script, ../bin/tool) against the shell's cwd
            let resolved = if std::path::Path::new(name).is_absolute() {
                std::path::PathBuf::from(name)
            } else {
                real_cwd.join(name)
            };
            if !resolved.exists() {
                return Ok(Some(ExecResult::failure(
                    127,
                    format!("{}: No such file or directory", name),
                )));
            }
            if !resolved.is_file() {
                return Ok(Some(ExecResult::failure(
                    126,
                    format!("{}: Is a directory", name),
                )));
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&resolved)
                    .map(|m| m.permissions().mode())
                    .unwrap_or(0);
                if mode & 0o111 == 0 {
                    return Ok(Some(ExecResult::failure(
                        126,
                        format!("{}: Permission denied", name),
                    )));
                }
            }
            resolved.to_string_lossy().into_owned()
        } else {
            // Get PATH from scope or environment
            let path_var = {
                let scope = self.scope.read().await;
                scope
                    .get("PATH")
                    .map(value_to_string)
                    .unwrap_or_else(|| std::env::var("PATH").unwrap_or_default())
            };

            // Resolve command in PATH
            match resolve_in_path(name, &path_var) {
                Some(path) => path,
                None => return Ok(None), // Not found - let caller handle error
            }
        };

        tracing::debug!(executable = %executable, "resolved external command");

        // Build flat argv (preserves flag format)
        let argv = self.build_args_flat(args).await?;

        // Get stdin if available
        let stdin_data = {
            let mut ctx = self.exec_ctx.write().await;
            ctx.take_stdin()
        };

        // Build and spawn the command
        use tokio::process::Command;

        let mut cmd = Command::new(&executable);
        cmd.args(&argv);
        cmd.current_dir(&real_cwd);

        // Hermetic env: child sees only kaish's exported vars, not the kaish
        // process's OS env. Frontends that want OS-env passthrough (REPL, MCP)
        // populate it via KernelConfig::initial_vars at construction.
        cmd.env_clear();
        {
            let scope = self.scope.read().await;
            for (var_name, value) in scope.exported_vars() {
                cmd.env(var_name, value_to_string(&value));
            }
        }

        // Handle stdin
        cmd.stdin(if stdin_data.is_some() {
            std::process::Stdio::piped()
        } else if self.interactive {
            std::process::Stdio::inherit()
        } else {
            std::process::Stdio::null()
        });

        // In interactive mode, standalone or last-in-pipeline commands inherit
        // the terminal's stdout/stderr so output streams in real-time.
        // First/middle commands must capture stdout for the pipe — same as bash.
        let pipeline_position = {
            let ctx = self.exec_ctx.read().await;
            ctx.pipeline_position
        };
        let inherit_output = self.interactive
            && matches!(pipeline_position, PipelinePosition::Only | PipelinePosition::Last);

        if inherit_output {
            cmd.stdout(std::process::Stdio::inherit());
            cmd.stderr(std::process::Stdio::inherit());
        } else {
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
        }

        // On Unix, always put the child in its own process group so cancellation
        // can `killpg` the whole tree (the child plus any grandchildren).
        // Restoring default tty-related signal handlers stays gated on
        // job-control mode — those only matter when the child has a controlling
        // terminal.
        #[cfg(unix)]
        {
            let restore_jc_signals = self.terminal_state.is_some() && inherit_output;
            // SAFETY: setpgid and sigaction(SIG_DFL) are async-signal-safe per POSIX
            #[allow(unsafe_code)]
            unsafe {
                cmd.pre_exec(move || {
                    // Own process group — for kill scope.
                    nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0))
                        .map_err(|e| std::io::Error::from_raw_os_error(e as i32))?;
                    if restore_jc_signals {
                        use nix::libc::{sigaction, SIGTSTP, SIGTTOU, SIGTTIN, SIGINT, SIG_DFL};
                        let mut sa: nix::libc::sigaction = std::mem::zeroed();
                        sa.sa_sigaction = SIG_DFL;
                        if sigaction(SIGTSTP, &sa, std::ptr::null_mut()) != 0 {
                            return Err(std::io::Error::last_os_error());
                        }
                        if sigaction(SIGTTOU, &sa, std::ptr::null_mut()) != 0 {
                            return Err(std::io::Error::last_os_error());
                        }
                        if sigaction(SIGTTIN, &sa, std::ptr::null_mut()) != 0 {
                            return Err(std::io::Error::last_os_error());
                        }
                        if sigaction(SIGINT, &sa, std::ptr::null_mut()) != 0 {
                            return Err(std::io::Error::last_os_error());
                        }
                    }
                    Ok(())
                });
            }
        }

        // Backstop for kill on drop in case our explicit kill path is bypassed
        // (panic, early return, etc) on the **capture** wait path. We do NOT
        // set this on the JC inherit path: that uses sync `waitpid` outside
        // tokio's view of the child, so on drop tokio would try to kill an
        // already-reaped (possibly-reused) PID. The JC path has its own
        // cancel handling via the side-task watcher.
        let in_jc_inherit_path = inherit_output && self.terminal_state.is_some();
        if !in_jc_inherit_path {
            cmd.kill_on_drop(true);
        }

        // Spawn the process. Capture a `KillTarget` immediately so cancel/
        // timeout paths can deliver signals via pidfd (Linux ≥ 5.3) — bound
        // to this process's generation, immune to PID reuse if the OS reaps
        // the child before our kill syscalls fire.
        let mut child = match cmd.spawn() {
            Ok(child) => child,
            Err(e) => {
                return Ok(Some(ExecResult::failure(
                    127,
                    format!("{}: {}", name, e),
                )));
            }
        };
        let kill_target = crate::pidfd::KillTarget::from_child(&child);

        // Write stdin if present
        if let Some(data) = stdin_data
            && let Some(mut stdin) = child.stdin.take()
        {
            use tokio::io::AsyncWriteExt;
            if let Err(e) = stdin.write_all(data.as_bytes()).await {
                return Ok(Some(ExecResult::failure(
                    1,
                    format!("{}: failed to write stdin: {}", name, e),
                )));
            }
            // Drop stdin to signal EOF
        }

        if inherit_output {
            // Job control path: use waitpid with WUNTRACED for Ctrl-Z support
            #[cfg(unix)]
            if let Some(ref term) = self.terminal_state {
                let child_id = child.id().unwrap_or(0);
                let pid = nix::unistd::Pid::from_raw(child_id as i32);
                let pgid = pid; // child is its own pgid leader

                // Give the terminal to the child's process group
                if let Err(e) = term.give_terminal_to(pgid) {
                    tracing::warn!("failed to give terminal to child: {}", e);
                }

                let term_clone = term.clone();
                let cmd_name = name.to_string();
                let cmd_display = format!("{} {}", name, argv.join(" "));
                let jobs = self.jobs.clone();

                // Side task that watches for cancellation while the blocking
                // waitpid runs. On cancel, it SIGTERMs the process group, waits
                // the grace period, then SIGKILLs. The blocking waitpid returns
                // when the child dies. AbortOnDrop guard cancels the watcher
                // on the success path so it doesn't keep running after wait
                // returns naturally.
                //
                // `wait_complete` shrinks the PID-reuse race: the watcher
                // checks it before each kill syscall and bails out if
                // wait_for_foreground has already reaped the child. This
                // doesn't fully eliminate the race (atomic load + kill is
                // not atomic with the OS reap+reuse), but narrows the window
                // to nanoseconds — enough to be ignorable in practice.
                let wait_complete = std::sync::Arc::new(
                    std::sync::atomic::AtomicBool::new(false)
                );
                let cancel_watcher = {
                    let cancel = cancel.clone();
                    let wc = wait_complete.clone();
                    // Ownership transfer: the JC path's sync wait inside
                    // block_in_place owns the child's reaping, so the
                    // cancel_watcher drives the kill side via KillTarget
                    // (pidfd-bound on Linux). When kill_target is None
                    // (older kernel + open failure, or non-Linux), falls
                    // through to the older PID-based path the closure
                    // captures from `pid`.
                    let target = kill_target.as_ref().map(|t| {
                        // Re-borrow the components we need into Owned-ish form
                        // so the spawned task is 'static. We can't move
                        // KillTarget directly because try_execute_external
                        // still uses it after the spawn — but on the JC path
                        // there is no further use after the watcher spawn,
                        // so a clone-of-pid + owned None pidfd is safe.
                        // Simpler: signal via the existing target by cloning
                        // a fresh pidfd; the original keeps its handle.
                        // Pidfd is just an OwnedFd — not Clone — so do it
                        // by re-opening from the pid. Fall back if reopen
                        // fails (race already reaped → best-effort kill).
                        crate::pidfd::KillTarget::from_pid(t.pid())
                    });
                    tokio::spawn(async move {
                        cancel.cancelled().await;
                        if wc.load(std::sync::atomic::Ordering::SeqCst) { return; }
                        use nix::sys::signal::Signal;
                        if let Some(t) = &target {
                            t.signal(Signal::SIGTERM);
                            t.signal_pg(Signal::SIGTERM);
                        } else {
                            let _ = nix::sys::signal::kill(pid, Signal::SIGTERM);
                            let _ = nix::sys::signal::killpg(pid, Signal::SIGTERM);
                        }
                        if kill_grace > Duration::ZERO {
                            tokio::time::sleep(kill_grace).await;
                            if wc.load(std::sync::atomic::Ordering::SeqCst) { return; }
                        }
                        if let Some(t) = &target {
                            t.signal(Signal::SIGKILL);
                            t.signal_pg(Signal::SIGKILL);
                        } else {
                            let _ = nix::sys::signal::kill(pid, Signal::SIGKILL);
                            let _ = nix::sys::signal::killpg(pid, Signal::SIGKILL);
                        }
                    })
                };
                struct AbortOnDrop(tokio::task::JoinHandle<()>);
                impl Drop for AbortOnDrop {
                    fn drop(&mut self) {
                        self.0.abort();
                    }
                }
                let _watcher_guard = AbortOnDrop(cancel_watcher);

                let wait_complete_setter = wait_complete.clone();
                let code = tokio::task::block_in_place(move || {
                    let result = term_clone.wait_for_foreground(pid);
                    // Mark wait done before the watcher might fire.
                    wait_complete_setter.store(true, std::sync::atomic::Ordering::SeqCst);

                    // Always reclaim the terminal
                    if let Err(e) = term_clone.reclaim_terminal() {
                        tracing::warn!("failed to reclaim terminal: {}", e);
                    }

                    match result {
                        crate::terminal::WaitResult::Exited(code) => code as i64,
                        crate::terminal::WaitResult::Signaled(sig) => 128 + sig as i64,
                        crate::terminal::WaitResult::Stopped(_sig) => {
                            // Register as a stopped job
                            let rt = tokio::runtime::Handle::current();
                            let job_id = rt.block_on(jobs.register_stopped(
                                cmd_display,
                                child_id,
                                child_id, // pgid = pid for group leader
                            ));
                            eprintln!("\n[{}]+ Stopped\t{}", job_id, cmd_name);
                            148 // 128 + SIGTSTP(20) on most systems, but we use a fixed value
                        }
                    }
                });

                return Ok(Some(ExecResult::from_output(code, String::new(), String::new())));
            }

            // Non-job-control path with inherited stdio.
            let status = match wait_or_kill(&mut child, kill_target.as_ref(), &cancel, kill_grace).await {
                Ok(s) => s,
                Err(e) => {
                    return Ok(Some(ExecResult::failure(
                        1,
                        format!("{}: failed to wait: {}", name, e),
                    )));
                }
            };

            let code = status.code().unwrap_or_else(|| {
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt;
                    128 + status.signal().unwrap_or(0)
                }
                #[cfg(not(unix))]
                {
                    -1
                }
            }) as i64;

            // stdout/stderr already went to the terminal
            Ok(Some(ExecResult::from_output(code, String::new(), String::new())))
        } else {
            // Capture output via bounded streams
            let stdout_stream = Arc::new(BoundedStream::new(DEFAULT_STREAM_MAX_SIZE));
            let stderr_stream = Arc::new(BoundedStream::new(DEFAULT_STREAM_MAX_SIZE));

            let stdout_pipe = child.stdout.take();
            let stderr_pipe = child.stderr.take();

            let stdout_clone = stdout_stream.clone();
            let stderr_clone = stderr_stream.clone();

            let stdout_task = stdout_pipe.map(|pipe| {
                tokio::spawn(async move {
                    drain_to_stream(pipe, stdout_clone).await;
                })
            });

            let stderr_task = stderr_pipe.map(|pipe| {
                tokio::spawn(async move {
                    drain_to_stream(pipe, stderr_clone).await;
                })
            });

            let cancelled_before_wait = cancel.is_cancelled();
            let status = match wait_or_kill(&mut child, kill_target.as_ref(), &cancel, kill_grace).await {
                Ok(s) => s,
                Err(e) => {
                    if let Some(task) = stdout_task { task.abort(); let _ = task.await; }
                    if let Some(task) = stderr_task { task.abort(); let _ = task.await; }
                    return Ok(Some(ExecResult::failure(
                        1,
                        format!("{}: failed to wait: {}", name, e),
                    )));
                }
            };

            // On cancel, abort the drain tasks (the child's pipes are gone;
            // late output is lost but predictable death beats partial capture).
            // On normal exit, await drains so we don't lose buffered output.
            if cancelled_before_wait || cancel.is_cancelled() {
                if let Some(task) = stdout_task { task.abort(); let _ = task.await; }
                if let Some(task) = stderr_task { task.abort(); let _ = task.await; }
            } else {
                if let Some(task) = stdout_task {
                    // Ignore join error — the drain task logs its own errors
                    let _ = task.await;
                }
                if let Some(task) = stderr_task {
                    let _ = task.await;
                }
            }

            let code = status.code().unwrap_or_else(|| {
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt;
                    128 + status.signal().unwrap_or(0)
                }
                #[cfg(not(unix))]
                {
                    -1
                }
            }) as i64;

            let stdout = stdout_stream.read_string().await;
            let stderr = stderr_stream.read_string().await;

            Ok(Some(ExecResult::from_output(code, stdout, stderr)))
        }
    }

    // --- Variable Access ---

    /// Get a variable value.
    pub async fn get_var(&self, name: &str) -> Option<Value> {
        let scope = self.scope.read().await;
        scope.get(name).cloned()
    }

    /// Check if error-exit mode is enabled (for testing).
    #[cfg(test)]
    pub async fn error_exit_enabled(&self) -> bool {
        let scope = self.scope.read().await;
        scope.error_exit_enabled()
    }

    /// Set a variable value.
    pub async fn set_var(&self, name: &str, value: Value) {
        let mut scope = self.scope.write().await;
        scope.set(name.to_string(), value);
    }

    /// Set positional parameters ($0 script name and $1-$9 args).
    pub async fn set_positional(&self, script_name: impl Into<String>, args: Vec<String>) {
        let mut scope = self.scope.write().await;
        scope.set_positional(script_name, args);
    }

    /// List all variables.
    pub async fn list_vars(&self) -> Vec<(String, Value)> {
        let scope = self.scope.read().await;
        scope.all()
    }

    // --- CWD ---

    /// Get current working directory.
    pub async fn cwd(&self) -> PathBuf {
        self.exec_ctx.read().await.cwd.clone()
    }

    /// Set current working directory.
    pub async fn set_cwd(&self, path: PathBuf) {
        let mut ctx = self.exec_ctx.write().await;
        ctx.set_cwd(path);
    }

    // --- Last Result ---

    /// Get the last result ($?).
    pub async fn last_result(&self) -> ExecResult {
        let scope = self.scope.read().await;
        scope.last_result().clone()
    }

    // --- Tools ---

    /// Check if a user-defined function exists.
    pub async fn has_function(&self, name: &str) -> bool {
        self.user_tools.read().await.contains_key(name)
    }

    /// Get available tool schemas.
    pub fn tool_schemas(&self) -> Vec<crate::tools::ToolSchema> {
        self.tools.schemas()
    }

    // --- Jobs ---

    /// Get job manager.
    pub fn jobs(&self) -> Arc<JobManager> {
        self.jobs.clone()
    }

    // --- VFS ---

    /// Get VFS router.
    pub fn vfs(&self) -> Arc<VfsRouter> {
        self.vfs.clone()
    }

    // --- State ---

    /// Reset kernel to initial state.
    ///
    /// Clears in-memory variables and resets cwd to root.
    /// History is not cleared (it persists across resets).
    pub async fn reset(&self) -> Result<()> {
        {
            let mut scope = self.scope.write().await;
            *scope = Scope::new();
        }
        {
            let mut ctx = self.exec_ctx.write().await;
            ctx.cwd = PathBuf::from("/");
        }
        Ok(())
    }

    /// Shutdown the kernel.
    pub async fn shutdown(self) -> Result<()> {
        // Wait for all background jobs
        self.jobs.wait_all().await;
        Ok(())
    }

    /// Dispatch a single command using the full resolution chain.
    ///
    /// This is the core of `CommandDispatcher` — it syncs state between the
    /// passed-in `ExecContext` and kernel-internal state (scope, exec_ctx),
    /// then delegates to `execute_command` for the actual dispatch.
    ///
    /// State flow:
    /// 1. ctx → self: sync scope, cwd, stdin so internal methods see current state
    /// 2. execute_command: full dispatch chain (user tools, builtins, scripts, external, backend)
    /// 3. self → ctx: sync scope, cwd changes back so the pipeline runner sees them
    async fn dispatch_command(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult> {
        // Ensure nested dispatch (e.g. the `timeout` builtin re-dispatching
        // its inner command via ctx.dispatcher) routes through THIS kernel,
        // not a stale parent. Critical for forks: the fork's builtins must
        // use the fork's dispatcher, not the parent's.
        if let Some(d) = self.dispatcher() {
            ctx.dispatcher = Some(d);
        }

        // 1. Sync ctx → self internals
        {
            let mut scope = self.scope.write().await;
            *scope = ctx.scope.clone();
        }
        {
            let mut ec = self.exec_ctx.write().await;
            ec.cwd = ctx.cwd.clone();
            ec.prev_cwd = ctx.prev_cwd.clone();
            ec.stdin = ctx.stdin.take();
            ec.stdin_data = ctx.stdin_data.take();
            // Streaming pipe endpoints and kernel stderr must flow to the
            // tool via self.exec_ctx — execute_command reads that, not the
            // passed-in ctx. Without moving these, concurrent pipeline
            // stages dispatched via a fork get pipe_stdin = None and
            // silently read nothing.
            ec.pipe_stdin = ctx.pipe_stdin.take();
            ec.pipe_stdout = ctx.pipe_stdout.take();
            if let Some(stderr) = ctx.stderr.clone() {
                ec.stderr = Some(stderr);
            }
            ec.aliases = ctx.aliases.clone();
            ec.ignore_config = ctx.ignore_config.clone();
            ec.output_limit = ctx.output_limit.clone();
            ec.pipeline_position = ctx.pipeline_position;
            // Sync the cancel token from ctx → ec. Builtins like `timeout`
            // swap ctx.cancel to a derived child token before re-dispatching;
            // execute_command's snapshot reads ec.cancel (kept aligned by
            // this sync), so try_execute_external sees the right token.
            ec.cancel = ctx.cancel.clone();
        }

        // 2. Execute via the full dispatch chain
        let result = self.execute_command(&cmd.name, &cmd.args).await?;

        // 3. Sync self → ctx
        {
            let scope = self.scope.read().await;
            ctx.scope = scope.clone();
        }
        {
            let mut ec = self.exec_ctx.write().await;
            ctx.cwd = ec.cwd.clone();
            ctx.prev_cwd = ec.prev_cwd.clone();
            ctx.aliases = ec.aliases.clone();
            ctx.ignore_config = ec.ignore_config.clone();
            ctx.output_limit = ec.output_limit.clone();
            // Return any pipe endpoints that the tool didn't consume.
            // `take()` here keeps the fork's exec_ctx in a clean state for
            // the next dispatch — these are per-command and shouldn't leak
            // between calls.
            ctx.pipe_stdin = ec.pipe_stdin.take();
            ctx.pipe_stdout = ec.pipe_stdout.take();
        }

        Ok(result)
    }
}

#[async_trait]
impl CommandDispatcher for Kernel {
    /// Dispatch a command through the Kernel's full resolution chain.
    ///
    /// This is the single path for all command execution when called from
    /// the pipeline runner. It provides the full dispatch chain:
    /// user tools → builtins → .kai scripts → external commands → backend tools.
    async fn dispatch(&self, cmd: &Command, ctx: &mut ExecContext) -> Result<ExecResult> {
        self.dispatch_command(cmd, ctx).await
    }

    /// Produce a forked dispatcher with independent mutable state (detached).
    ///
    /// Calls the inherent `Kernel::fork` method (note the UFCS to avoid
    /// recursing into the trait method we're defining) and coerces the
    /// returned `Arc<Kernel>` to `Arc<dyn CommandDispatcher>`.
    async fn fork(&self) -> Arc<dyn CommandDispatcher> {
        let fork: Arc<Kernel> = Kernel::fork(self).await;
        fork
    }

    /// Produce a forked dispatcher with cancellation cascading from this kernel.
    async fn fork_attached(&self) -> Arc<dyn CommandDispatcher> {
        let fork: Arc<Kernel> = Kernel::fork_attached(self).await;
        fork
    }
}

/// Accumulate output from one result into another.
///
/// This appends stdout and stderr (with newlines as separators) and updates
/// the exit code to match the new result. Used to preserve output from
/// multiple statements, loop iterations, and command chains.
fn accumulate_result(accumulated: &mut ExecResult, new: &ExecResult) {
    // Materialize lazy OutputData into .out before accumulating.
    // Without this, the first command's output stays in .output while
    // the second's text gets appended to .out, losing the first.
    accumulated.materialize();
    let new_text = new.text_out();
    if !accumulated.text_out().is_empty() && !new_text.is_empty() && !accumulated.text_out().ends_with('\n') {
        accumulated.push_out("\n");
    }
    accumulated.push_out(&new_text);
    if !accumulated.err.is_empty() && !new.err.is_empty() && !accumulated.err.ends_with('\n') {
        accumulated.err.push('\n');
    }
    accumulated.err.push_str(&new.err);
    accumulated.code = new.code;
    accumulated.data = new.data.clone();
    accumulated.did_spill = new.did_spill;
    accumulated.original_code = new.original_code;
    accumulated.content_type = new.content_type.clone();
    accumulated.baggage.clone_from(&new.baggage);
}

/// Check if a value is truthy.
fn is_truthy(value: &Value) -> bool {
    match value {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Int(i) => *i != 0,
        Value::Float(f) => *f != 0.0,
        Value::String(s) => !s.is_empty(),
        Value::Json(json) => match json {
            serde_json::Value::Null => false,
            serde_json::Value::Array(arr) => !arr.is_empty(),
            serde_json::Value::Object(obj) => !obj.is_empty(),
            serde_json::Value::Bool(b) => *b,
            serde_json::Value::Number(n) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
            serde_json::Value::String(s) => !s.is_empty(),
        },
        Value::Blob(_) => true, // Blob references are always truthy
    }
}

/// Apply tilde expansion to a value.
///
/// Only string values starting with `~` are expanded.
fn apply_tilde_expansion(value: Value) -> Value {
    match value {
        Value::String(s) if s.starts_with('~') => Value::String(expand_tilde(&s)),
        _ => value,
    }
}

/// Wait for a child to exit, killing it if `cancel` fires first.
///
/// `target` carries a Linux pidfd (when available) for race-free direct-child
/// kill; fall-through to PID-based kill otherwise. On non-unix targets the
/// parameter is ignored and we use tokio's cross-platform `start_kill`.
#[cfg(all(unix, feature = "native"))]
pub(crate) async fn wait_or_kill(
    child: &mut tokio::process::Child,
    target: Option<&crate::pidfd::KillTarget>,
    cancel: &tokio_util::sync::CancellationToken,
    grace: Duration,
) -> std::io::Result<std::process::ExitStatus> {
    tokio::select! {
        biased;
        status = child.wait() => status,
        _ = cancel.cancelled() => kill_with_grace(child, target, grace).await,
    }
}

#[cfg(all(not(unix), feature = "native"))]
pub(crate) async fn wait_or_kill(
    child: &mut tokio::process::Child,
    _target: Option<&()>,
    cancel: &tokio_util::sync::CancellationToken,
    _grace: Duration,
) -> std::io::Result<std::process::ExitStatus> {
    tokio::select! {
        biased;
        status = child.wait() => status,
        _ = cancel.cancelled() => {
            let _ = child.start_kill();
            child.wait().await
        }
    }
}

/// Send SIGTERM to the child and its process group; wait `grace`; then SIGKILL.
///
/// Direct-child kill goes through `target.signal()`, which on Linux uses a
/// pidfd (immune to PID reuse). Process-group kill uses `killpg` — there is
/// no PGID-equivalent of pidfd, so grandchildren retain a small reuse window.
#[cfg(all(unix, feature = "native"))]
pub(crate) async fn kill_with_grace(
    child: &mut tokio::process::Child,
    target: Option<&crate::pidfd::KillTarget>,
    grace: Duration,
) -> std::io::Result<std::process::ExitStatus> {
    use nix::sys::signal::Signal;

    if let Some(t) = target {
        t.signal(Signal::SIGTERM);
        t.signal_pg(Signal::SIGTERM);
        if grace > Duration::ZERO
            && let Ok(status) = tokio::time::timeout(grace, child.wait()).await
        {
            return status;
        }
        t.signal(Signal::SIGKILL);
        t.signal_pg(Signal::SIGKILL);
    }
    child.wait().await
}

#[cfg(all(test, feature = "native"))]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_kernel_transient() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        assert_eq!(kernel.name(), "transient");
    }

    #[tokio::test]
    async fn test_kernel_execute_echo() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel.execute("echo hello").await.expect("execution failed");
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "hello");
    }

    #[tokio::test]
    async fn test_multiple_statements_accumulate_output() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute("echo one\necho two\necho three")
            .await
            .expect("execution failed");
        assert!(result.ok());
        // Should have all three outputs separated by newlines
        assert!(result.text_out().contains("one"), "missing 'one': {}", result.text_out());
        assert!(result.text_out().contains("two"), "missing 'two': {}", result.text_out());
        assert!(result.text_out().contains("three"), "missing 'three': {}", result.text_out());
    }

    #[tokio::test]
    async fn test_and_chain_accumulates_output() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute("echo first && echo second")
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert!(result.text_out().contains("first"), "missing 'first': {}", result.text_out());
        assert!(result.text_out().contains("second"), "missing 'second': {}", result.text_out());
    }

    #[tokio::test]
    async fn test_for_loop_accumulates_output() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute(r#"for X in a b c; do echo "item: ${X}"; done"#)
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert!(result.text_out().contains("item: a"), "missing 'item: a': {}", result.text_out());
        assert!(result.text_out().contains("item: b"), "missing 'item: b': {}", result.text_out());
        assert!(result.text_out().contains("item: c"), "missing 'item: c': {}", result.text_out());
    }

    #[tokio::test]
    async fn test_while_loop_accumulates_output() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute(r#"
                N=3
                while [[ ${N} -gt 0 ]]; do
                    echo "N=${N}"
                    N=$((N - 1))
                done
            "#)
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert!(result.text_out().contains("N=3"), "missing 'N=3': {}", result.text_out());
        assert!(result.text_out().contains("N=2"), "missing 'N=2': {}", result.text_out());
        assert!(result.text_out().contains("N=1"), "missing 'N=1': {}", result.text_out());
    }

    #[tokio::test]
    async fn test_kernel_set_var() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("X=42").await.expect("set failed");

        let value = kernel.get_var("X").await;
        assert_eq!(value, Some(Value::Int(42)));
    }

    #[tokio::test]
    async fn test_kernel_var_expansion() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("NAME=\"world\"").await.expect("set failed");
        let result = kernel.execute("echo \"hello ${NAME}\"").await.expect("echo failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "hello world");
    }

    #[tokio::test]
    async fn test_kernel_last_result() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("echo test").await.expect("echo failed");

        let last = kernel.last_result().await;
        assert!(last.ok());
        assert_eq!(last.text_out().trim(), "test");
    }

    #[tokio::test]
    async fn test_kernel_tool_not_found() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel.execute("nonexistent_tool").await.expect("execution failed");
        assert!(!result.ok());
        assert_eq!(result.code, 127);
        assert!(result.err.contains("command not found"));
    }

    #[tokio::test]
    async fn test_external_command_true() {
        // Use REPL config for passthrough filesystem access
        let kernel = Kernel::new(KernelConfig::repl()).expect("failed to create kernel");

        // /bin/true should be available on any Unix system
        let result = kernel.execute("true").await.expect("execution failed");
        // This should use the builtin true, which returns 0
        assert!(result.ok(), "true should succeed: {:?}", result);
    }

    #[tokio::test]
    async fn test_external_command_basic() {
        // Use REPL config for passthrough filesystem access
        let kernel = Kernel::new(KernelConfig::repl()).expect("failed to create kernel");

        // Test with /bin/echo which is external
        // Note: kaish has a builtin echo, so this will use the builtin
        // Let's test with a command that's not a builtin
        // Actually, let's just test that PATH resolution works by checking the PATH var
        let path_var = std::env::var("PATH").unwrap_or_default();
        eprintln!("System PATH: {}", path_var);

        // Set PATH in kernel to ensure it's available
        kernel.execute(&format!(r#"PATH="{}""#, path_var)).await.expect("set PATH failed");

        // Now try an external command like /usr/bin/env
        // But env is also a builtin... let's try uname
        let result = kernel.execute("uname").await.expect("execution failed");
        eprintln!("uname result: {:?}", result);
        // uname should succeed if external commands work
        assert!(result.ok() || result.code == 127, "uname: {:?}", result);
    }

    #[tokio::test]
    async fn test_kernel_reset() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("X=1").await.expect("set failed");
        assert!(kernel.get_var("X").await.is_some());

        kernel.reset().await.expect("reset failed");
        assert!(kernel.get_var("X").await.is_none());
    }

    #[tokio::test]
    async fn test_kernel_cwd() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Transient kernel uses sandboxed mode with cwd=$HOME
        let cwd = kernel.cwd().await;
        let home = std::env::var("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("/"));
        assert_eq!(cwd, home);

        kernel.set_cwd(PathBuf::from("/tmp")).await;
        assert_eq!(kernel.cwd().await, PathBuf::from("/tmp"));
    }

    #[tokio::test]
    async fn test_kernel_list_vars() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("A=1").await.ok();
        kernel.execute("B=2").await.ok();

        let vars = kernel.list_vars().await;
        assert!(vars.iter().any(|(n, v)| n == "A" && *v == Value::Int(1)));
        assert!(vars.iter().any(|(n, v)| n == "B" && *v == Value::Int(2)));
    }

    #[tokio::test]
    async fn test_is_truthy() {
        assert!(!is_truthy(&Value::Null));
        assert!(!is_truthy(&Value::Bool(false)));
        assert!(is_truthy(&Value::Bool(true)));
        assert!(!is_truthy(&Value::Int(0)));
        assert!(is_truthy(&Value::Int(1)));
        assert!(!is_truthy(&Value::String("".into())));
        assert!(is_truthy(&Value::String("x".into())));
    }

    #[tokio::test]
    async fn test_jq_in_pipeline() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        // kaish uses double quotes only; escape inner quotes
        let result = kernel
            .execute(r#"echo "{\"name\": \"Alice\"}" | jq ".name" -r"#)
            .await
            .expect("execution failed");
        assert!(result.ok(), "jq pipeline failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Alice");
    }

    #[tokio::test]
    async fn test_user_defined_tool() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define a function
        kernel
            .execute(r#"greet() { echo "Hello, $1!" }"#)
            .await
            .expect("function definition failed");

        // Call the function
        let result = kernel
            .execute(r#"greet "World""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "greet failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hello, World!");
    }

    #[tokio::test]
    async fn test_user_tool_positional_args() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define a function with positional param
        kernel
            .execute(r#"greet() { echo "Hi $1" }"#)
            .await
            .expect("function definition failed");

        // Call with positional argument
        let result = kernel
            .execute(r#"greet "Amy""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "greet failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hi Amy");
    }

    #[tokio::test]
    async fn test_function_shared_scope() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Set a variable in parent scope
        kernel
            .execute(r#"SECRET="hidden""#)
            .await
            .expect("set failed");

        // Define a function that accesses and modifies parent variable
        kernel
            .execute(r#"access_parent() {
                echo "${SECRET}"
                SECRET="modified"
            }"#)
            .await
            .expect("function definition failed");

        // Call the function - it SHOULD see SECRET (shared scope like sh)
        let result = kernel.execute("access_parent").await.expect("function call failed");

        // Function should have access to parent scope
        assert!(
            result.text_out().contains("hidden"),
            "Function should access parent scope, got: {}",
            result.text_out()
        );

        // Function should have modified the parent variable
        let secret = kernel.get_var("SECRET").await;
        assert_eq!(
            secret,
            Some(Value::String("modified".into())),
            "Function should modify parent scope"
        );
    }

    #[tokio::test]
    #[ignore = "exec replaces the test binary via CommandExt::exec, hangs libtest; cannot be run under cargo test"]
    async fn test_exec_builtin() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        // argv is now a space-separated string or JSON array string
        let result = kernel
            .execute(r#"exec command="/bin/echo" argv="hello world""#)
            .await
            .expect("exec failed");

        assert!(result.ok(), "exec failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "hello world");
    }

    #[tokio::test]
    async fn test_while_false_never_runs() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // A while loop with false condition should never run
        let result = kernel
            .execute(r#"
                while false; do
                    echo "should not run"
                done
            "#)
            .await
            .expect("while false failed");

        assert!(result.ok());
        assert!(result.text_out().is_empty(), "while false should not execute body: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_while_string_comparison() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Set a flag
        kernel.execute(r#"FLAG="go""#).await.expect("set failed");

        // Use string comparison as condition (shell-compatible [[ ]] syntax)
        // Note: Put echo last so we can check the output
        let result = kernel
            .execute(r#"
                while [[ ${FLAG} == "go" ]]; do
                    FLAG="stop"
                    echo "running"
                done
            "#)
            .await
            .expect("while with string cmp failed");

        assert!(result.ok());
        assert!(result.text_out().contains("running"), "should have run once: {}", result.text_out());

        // Verify flag was changed
        let flag = kernel.get_var("FLAG").await;
        assert_eq!(flag, Some(Value::String("stop".into())));
    }

    #[tokio::test]
    async fn test_while_numeric_comparison() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Test > comparison (shell-compatible [[ ]] with -gt)
        kernel.execute("N=5").await.expect("set failed");

        // Note: Put echo last so we can check the output
        let result = kernel
            .execute(r#"
                while [[ ${N} -gt 3 ]]; do
                    N=3
                    echo "N was greater"
                done
            "#)
            .await
            .expect("while with > failed");

        assert!(result.ok());
        assert!(result.text_out().contains("N was greater"), "should have run once: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_break_in_while_loop() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                I=0
                while true; do
                    I=1
                    echo "before break"
                    break
                    echo "after break"
                done
            "#)
            .await
            .expect("while with break failed");

        assert!(result.ok());
        assert!(result.text_out().contains("before break"), "should see before break: {}", result.text_out());
        assert!(!result.text_out().contains("after break"), "should not see after break: {}", result.text_out());

        // Verify we exited the loop
        let i = kernel.get_var("I").await;
        assert_eq!(i, Some(Value::Int(1)));
    }

    #[tokio::test]
    async fn test_continue_in_while_loop() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Test continue in a while loop where variables persist
        // We use string state transition: "start" -> "middle" -> "end"
        // continue on "middle" should skip to next iteration
        // Shell-compatible: use [[ ]] for comparisons
        let result = kernel
            .execute(r#"
                STATE="start"
                AFTER_CONTINUE="no"
                while [[ ${STATE} != "done" ]]; do
                    if [[ ${STATE} == "start" ]]; then
                        STATE="middle"
                        continue
                        AFTER_CONTINUE="yes"
                    fi
                    if [[ ${STATE} == "middle" ]]; then
                        STATE="done"
                    fi
                done
            "#)
            .await
            .expect("while with continue failed");

        assert!(result.ok());

        // STATE should be "done" (we completed the loop)
        let state = kernel.get_var("STATE").await;
        assert_eq!(state, Some(Value::String("done".into())));

        // AFTER_CONTINUE should still be "no" (continue skipped the assignment)
        let after = kernel.get_var("AFTER_CONTINUE").await;
        assert_eq!(after, Some(Value::String("no".into())));
    }

    #[tokio::test]
    async fn test_break_with_level() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Nested loop with break 2 to exit both loops
        // We verify by checking OUTER value:
        // - If break 2 works, OUTER stays at 1 (set before for loop)
        // - If break 2 fails, OUTER becomes 2 (set after for loop)
        let result = kernel
            .execute(r#"
                OUTER=0
                while true; do
                    OUTER=1
                    for X in "1 2"; do
                        break 2
                    done
                    OUTER=2
                done
            "#)
            .await
            .expect("nested break failed");

        assert!(result.ok());

        // OUTER should be 1 (set before for loop), not 2 (would be set after for loop)
        let outer = kernel.get_var("OUTER").await;
        assert_eq!(outer, Some(Value::Int(1)), "break 2 should have skipped OUTER=2");
    }

    #[tokio::test]
    async fn test_return_from_tool() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define a function that returns early
        kernel
            .execute(r#"early_return() {
                if [[ $1 == 1 ]]; then
                    return 42
                fi
                echo "not returned"
            }"#)
            .await
            .expect("function definition failed");

        // Call with arg=1 should return with exit code 42
        // (POSIX shell behavior: return N sets exit code, doesn't output N)
        let result = kernel
            .execute("early_return 1")
            .await
            .expect("function call failed");

        // Exit code should be 42 (non-zero, so not ok())
        assert_eq!(result.code, 42);
        // Output should be empty (we returned before echo)
        assert!(result.text_out().is_empty());
    }

    #[tokio::test]
    async fn test_return_without_value() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define a function that returns without a value
        kernel
            .execute(r#"early_exit() {
                if [[ $1 == "stop" ]]; then
                    return
                fi
                echo "continued"
            }"#)
            .await
            .expect("function definition failed");

        // Call with arg="stop" should return early
        let result = kernel
            .execute(r#"early_exit "stop""#)
            .await
            .expect("function call failed");

        assert!(result.ok());
        assert!(result.text_out().is_empty() || result.text_out().trim().is_empty());
    }

    #[tokio::test]
    async fn test_exit_stops_execution() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // exit should stop further execution
        kernel
            .execute(r#"
                BEFORE="yes"
                exit 0
                AFTER="yes"
            "#)
            .await
            .expect("execution failed");

        // BEFORE should be set, AFTER should not
        let before = kernel.get_var("BEFORE").await;
        assert_eq!(before, Some(Value::String("yes".into())));

        let after = kernel.get_var("AFTER").await;
        assert!(after.is_none(), "AFTER should not be set after exit");
    }

    #[tokio::test]
    async fn test_exit_with_code() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // exit with code should propagate the exit code
        let result = kernel
            .execute("exit 42")
            .await
            .expect("exit failed");

        assert_eq!(result.code, 42);
        assert!(result.text_out().is_empty(), "exit should not produce stdout");
    }

    #[tokio::test]
    async fn test_set_e_stops_on_failure() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Enable error-exit mode
        kernel.execute("set -e").await.expect("set -e failed");

        // Run a sequence where the middle command fails
        kernel
            .execute(r#"
                STEP1="done"
                false
                STEP2="done"
            "#)
            .await
            .expect("execution failed");

        // STEP1 should be set, but STEP2 should NOT be set (exit on false)
        let step1 = kernel.get_var("STEP1").await;
        assert_eq!(step1, Some(Value::String("done".into())));

        let step2 = kernel.get_var("STEP2").await;
        assert!(step2.is_none(), "STEP2 should not be set after false with set -e");
    }

    #[tokio::test]
    async fn test_set_plus_e_disables_error_exit() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Enable then disable error-exit mode
        kernel.execute("set -e").await.expect("set -e failed");
        kernel.execute("set +e").await.expect("set +e failed");

        // Now failure should NOT stop execution
        kernel
            .execute(r#"
                STEP1="done"
                false
                STEP2="done"
            "#)
            .await
            .expect("execution failed");

        // Both should be set since +e disables error exit
        let step1 = kernel.get_var("STEP1").await;
        assert_eq!(step1, Some(Value::String("done".into())));

        let step2 = kernel.get_var("STEP2").await;
        assert_eq!(step2, Some(Value::String("done".into())));
    }

    #[tokio::test]
    async fn test_set_ignores_unknown_options() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Bash idiom: set -euo pipefail (we support -e, ignore the rest)
        let result = kernel
            .execute("set -e -u -o pipefail")
            .await
            .expect("set with unknown options failed");

        assert!(result.ok(), "set should succeed with unknown options");

        // -e should still be enabled
        kernel
            .execute(r#"
                BEFORE="yes"
                false
                AFTER="yes"
            "#)
            .await
            .ok();

        let after = kernel.get_var("AFTER").await;
        assert!(after.is_none(), "-e should be enabled despite unknown options");
    }

    #[tokio::test]
    async fn test_set_no_args_shows_settings() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Enable -e
        kernel.execute("set -e").await.expect("set -e failed");

        // Call set with no args to see settings
        let result = kernel.execute("set").await.expect("set failed");

        assert!(result.ok());
        assert!(result.text_out().contains("set -e"), "should show -e is enabled: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_set_e_in_pipeline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("set -e").await.expect("set -e failed");

        // Pipeline failure should trigger exit
        kernel
            .execute(r#"
                BEFORE="yes"
                false | cat
                AFTER="yes"
            "#)
            .await
            .ok();

        let before = kernel.get_var("BEFORE").await;
        assert_eq!(before, Some(Value::String("yes".into())));

        // AFTER should not be set if pipeline failure triggers exit
        // Note: The exit code of a pipeline is the exit code of the last command
        // So `false | cat` returns 0 (cat succeeds). This is bash-compatible behavior.
        // To test pipeline failure, we need the last command to fail.
    }

    #[tokio::test]
    async fn test_set_e_with_and_chain() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("set -e").await.expect("set -e failed");

        // Commands in && chain should not trigger -e on the first failure
        // because && explicitly handles the error
        kernel
            .execute(r#"
                RESULT="initial"
                false && RESULT="chained"
                RESULT="continued"
            "#)
            .await
            .ok();

        // In bash, commands in && don't trigger -e. The chain handles the failure.
        // Our implementation may differ - let's verify current behavior.
        let result = kernel.get_var("RESULT").await;
        // If we follow bash semantics, RESULT should be "continued"
        // If we trigger -e on the false, RESULT stays "initial"
        assert!(result.is_some(), "RESULT should be set");
    }

    #[tokio::test]
    async fn test_set_e_exits_in_for_loop() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("set -e").await.expect("set -e failed");

        kernel
            .execute(r#"
                REACHED="no"
                for x in 1 2 3; do
                    false
                    REACHED="yes"
                done
            "#)
            .await
            .ok();

        // With set -e, false should trigger exit; REACHED should remain "no"
        let reached = kernel.get_var("REACHED").await;
        assert_eq!(reached, Some(Value::String("no".into())),
            "set -e should exit on failure in for loop body");
    }

    #[tokio::test]
    async fn test_for_loop_continues_without_set_e() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Without set -e, for loop should continue normally
        kernel
            .execute(r#"
                COUNT=0
                for x in 1 2 3; do
                    false
                    COUNT=$((COUNT + 1))
                done
            "#)
            .await
            .ok();

        let count = kernel.get_var("COUNT").await;
        // Arithmetic produces Int values; accept either Int or String representation
        let count_val = match &count {
            Some(Value::Int(n)) => *n,
            Some(Value::String(s)) => s.parse().unwrap_or(-1),
            _ => -1,
        };
        assert_eq!(count_val, 3,
            "without set -e, loop should complete all iterations (got {:?})", count);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Source Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_source_sets_variables() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Write a script to the VFS
        kernel
            .execute(r#"write "/test.kai" 'FOO="bar"'"#)
            .await
            .expect("write failed");

        // Source the script
        let result = kernel
            .execute(r#"source "/test.kai""#)
            .await
            .expect("source failed");

        assert!(result.ok(), "source should succeed");

        // Variable should be set in current scope
        let foo = kernel.get_var("FOO").await;
        assert_eq!(foo, Some(Value::String("bar".into())));
    }

    #[tokio::test]
    async fn test_source_with_dot_alias() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Write a script to the VFS
        kernel
            .execute(r#"write "/vars.kai" 'X=42'"#)
            .await
            .expect("write failed");

        // Source using . alias
        let result = kernel
            .execute(r#". "/vars.kai""#)
            .await
            .expect(". failed");

        assert!(result.ok(), ". should succeed");

        // Variable should be set in current scope
        let x = kernel.get_var("X").await;
        assert_eq!(x, Some(Value::Int(42)));
    }

    #[tokio::test]
    async fn test_source_not_found() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Try to source a non-existent file
        let result = kernel
            .execute(r#"source "/nonexistent.kai""#)
            .await
            .expect("source should not fail with error");

        assert!(!result.ok(), "source of non-existent file should fail");
        assert!(result.err.contains("nonexistent.kai"), "error should mention filename");
    }

    #[tokio::test]
    async fn test_source_missing_filename() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Call source with no arguments
        let result = kernel
            .execute("source")
            .await
            .expect("source should not fail with error");

        assert!(!result.ok(), "source without filename should fail");
        assert!(result.err.contains("missing filename"), "error should mention missing filename");
    }

    #[tokio::test]
    async fn test_source_executes_multiple_statements() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Write a script with multiple statements
        kernel
            .execute(r#"write "/multi.kai" 'A=1
B=2
C=3'"#)
            .await
            .expect("write failed");

        // Source it
        kernel
            .execute(r#"source "/multi.kai""#)
            .await
            .expect("source failed");

        // All variables should be set
        assert_eq!(kernel.get_var("A").await, Some(Value::Int(1)));
        assert_eq!(kernel.get_var("B").await, Some(Value::Int(2)));
        assert_eq!(kernel.get_var("C").await, Some(Value::Int(3)));
    }

    #[tokio::test]
    async fn test_source_can_define_functions() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Write a script that defines a function
        kernel
            .execute(r#"write "/functions.kai" 'greet() {
    echo "Hello, $1!"
}'"#)
            .await
            .expect("write failed");

        // Source it
        kernel
            .execute(r#"source "/functions.kai""#)
            .await
            .expect("source failed");

        // Use the defined function
        let result = kernel
            .execute(r#"greet "World""#)
            .await
            .expect("greet failed");

        assert!(result.ok());
        assert!(result.text_out().contains("Hello, World!"));
    }

    #[tokio::test]
    async fn test_source_inherits_error_exit() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Enable error exit
        kernel.execute("set -e").await.expect("set -e failed");

        // Write a script that has a failure
        kernel
            .execute(r#"write "/fail.kai" 'BEFORE="yes"
false
AFTER="yes"'"#)
            .await
            .expect("write failed");

        // Source it (should exit on false due to set -e)
        kernel
            .execute(r#"source "/fail.kai""#)
            .await
            .ok();

        // BEFORE should be set, AFTER should NOT be set due to error exit
        let before = kernel.get_var("BEFORE").await;
        assert_eq!(before, Some(Value::String("yes".into())));

        // Note: This test depends on whether error exit is checked within source
        // Currently our implementation checks per-statement in the main kernel
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // set -e with && / || chains
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_set_e_and_chain_left_fails() {
        // set -e; false && echo hi; REACHED=1 → REACHED should be set
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel.execute("set -e").await.expect("set -e failed");

        kernel
            .execute("false && echo hi; REACHED=1")
            .await
            .expect("execution failed");

        let reached = kernel.get_var("REACHED").await;
        assert_eq!(
            reached,
            Some(Value::Int(1)),
            "set -e should not trigger on left side of &&"
        );
    }

    #[tokio::test]
    async fn test_set_e_and_chain_right_fails() {
        // set -e; true && false; REACHED=1 → REACHED should NOT be set
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel.execute("set -e").await.expect("set -e failed");

        kernel
            .execute("true && false; REACHED=1")
            .await
            .expect("execution failed");

        let reached = kernel.get_var("REACHED").await;
        assert!(
            reached.is_none(),
            "set -e should trigger when right side of && fails"
        );
    }

    #[tokio::test]
    async fn test_set_e_or_chain_recovers() {
        // set -e; false || echo recovered; REACHED=1 → REACHED should be set
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel.execute("set -e").await.expect("set -e failed");

        kernel
            .execute("false || echo recovered; REACHED=1")
            .await
            .expect("execution failed");

        let reached = kernel.get_var("REACHED").await;
        assert_eq!(
            reached,
            Some(Value::Int(1)),
            "set -e should not trigger when || recovers the failure"
        );
    }

    #[tokio::test]
    async fn test_set_e_or_chain_both_fail() {
        // set -e; false || false; REACHED=1 → REACHED should NOT be set
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel.execute("set -e").await.expect("set -e failed");

        kernel
            .execute("false || false; REACHED=1")
            .await
            .expect("execution failed");

        let reached = kernel.get_var("REACHED").await;
        assert!(
            reached.is_none(),
            "set -e should trigger when || chain ultimately fails"
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Cancellation Tests
    // ═══════════════════════════════════════════════════════════════════════════

    /// Helper: schedule a cancel after a delay from a background thread.
    /// Uses std::thread because cancel() is sync and Kernel is not Send.
    fn schedule_cancel(kernel: &Arc<Kernel>, delay: std::time::Duration) {
        let k = Arc::clone(kernel);
        std::thread::spawn(move || {
            std::thread::sleep(delay);
            k.cancel();
        });
    }

    #[tokio::test]
    async fn test_cancel_interrupts_for_loop() {
        let kernel = Arc::new(Kernel::transient().expect("failed to create kernel"));

        // Schedule cancel after a short delay from a background OS thread
        schedule_cancel(&kernel, std::time::Duration::from_millis(10));

        let result = kernel
            .execute("for i in $(seq 1 100000); do X=$i; done")
            .await
            .expect("execute failed");

        assert_eq!(result.code, 130, "cancelled execution should exit with code 130");

        // The loop variable should be set to something < 100000
        let x = kernel.get_var("X").await;
        if let Some(Value::Int(n)) = x {
            assert!(n < 100000, "loop should have been interrupted before finishing, got X={n}");
        }
    }

    #[tokio::test]
    async fn test_cancel_interrupts_while_loop() {
        let kernel = Arc::new(Kernel::transient().expect("failed to create kernel"));
        kernel.execute("COUNT=0").await.expect("init failed");

        schedule_cancel(&kernel, std::time::Duration::from_millis(10));

        let result = kernel
            .execute("while true; do COUNT=$((COUNT + 1)); done")
            .await
            .expect("execute failed");

        assert_eq!(result.code, 130);

        let count = kernel.get_var("COUNT").await;
        if let Some(Value::Int(n)) = count {
            assert!(n > 0, "loop should have run at least once");
        }
    }

    #[tokio::test]
    async fn test_reset_after_cancel() {
        // After cancellation, the next execute() should work normally
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel.cancel(); // cancel with nothing running

        let result = kernel.execute("echo hello").await.expect("execute failed");
        assert!(result.ok(), "execute after cancel should succeed");
        assert_eq!(result.text_out().trim(), "hello");
    }

    #[tokio::test]
    async fn test_cancel_interrupts_statement_sequence() {
        let kernel = Arc::new(Kernel::transient().expect("failed to create kernel"));

        // Schedule cancel after the first statement runs but before sleep finishes
        schedule_cancel(&kernel, std::time::Duration::from_millis(50));

        let result = kernel
            .execute("STEP=1; sleep 5; STEP=2; sleep 5; STEP=3")
            .await
            .expect("execute failed");

        assert_eq!(result.code, 130);

        // STEP should be 1 (set before sleep), not 2 or 3
        let step = kernel.get_var("STEP").await;
        assert_eq!(step, Some(Value::Int(1)), "cancel should stop before STEP=2");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Case Statement Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_case_simple_match() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "hello" in
                    hello) echo "matched hello" ;;
                    world) echo "matched world" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "matched hello");
    }

    #[tokio::test]
    async fn test_case_wildcard_match() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "main.rs" in
                    *.py) echo "Python" ;;
                    *.rs) echo "Rust" ;;
                    *) echo "Unknown" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "Rust");
    }

    #[tokio::test]
    async fn test_case_default_match() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "unknown.xyz" in
                    *.py) echo "Python" ;;
                    *.rs) echo "Rust" ;;
                    *) echo "Default" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "Default");
    }

    #[tokio::test]
    async fn test_case_no_match() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Case with no default branch and no match
        let result = kernel
            .execute(r#"
                case "nope" in
                    "yes") echo "yes" ;;
                    "no") echo "no" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert!(result.text_out().is_empty(), "no match should produce empty output");
    }

    #[tokio::test]
    async fn test_case_with_variable() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute(r#"LANG="rust""#).await.expect("set failed");

        let result = kernel
            .execute(r#"
                case ${LANG} in
                    python) echo "snake" ;;
                    rust) echo "crab" ;;
                    go) echo "gopher" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "crab");
    }

    #[tokio::test]
    async fn test_case_multiple_patterns() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "yes" in
                    "y"|"yes"|"Y"|"YES") echo "affirmative" ;;
                    "n"|"no"|"N"|"NO") echo "negative" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "affirmative");
    }

    #[tokio::test]
    async fn test_case_glob_question_mark() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "test1" in
                    test?) echo "matched test?" ;;
                    *) echo "default" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "matched test?");
    }

    #[tokio::test]
    async fn test_case_char_class() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"
                case "Yes" in
                    [Yy]*) echo "yes-like" ;;
                    [Nn]*) echo "no-like" ;;
                esac
            "#)
            .await
            .expect("case failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "yes-like");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Cat Stdin Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_cat_from_pipeline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"echo "piped text" | cat"#)
            .await
            .expect("cat pipeline failed");

        assert!(result.ok(), "cat failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "piped text");
    }

    #[tokio::test]
    async fn test_cat_from_pipeline_multiline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"echo "line1\nline2" | cat -n"#)
            .await
            .expect("cat pipeline failed");

        assert!(result.ok(), "cat failed: {}", result.err);
        assert!(result.text_out().contains("1\t"), "output: {}", result.text_out());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Heredoc Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_heredoc_basic() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute("cat <<EOF\nhello\nEOF")
            .await
            .expect("heredoc failed");

        assert!(result.ok(), "cat with heredoc failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "hello");
    }

    #[tokio::test]
    async fn test_arithmetic_in_string() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"echo "result: $((1 + 2))""#)
            .await
            .expect("arithmetic in string failed");

        assert!(result.ok(), "echo failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "result: 3");
    }

    #[tokio::test]
    async fn test_heredoc_multiline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute("cat <<EOF\nline1\nline2\nline3\nEOF")
            .await
            .expect("heredoc failed");

        assert!(result.ok(), "cat with heredoc failed: {}", result.err);
        assert!(result.text_out().contains("line1"), "output: {}", result.text_out());
        assert!(result.text_out().contains("line2"), "output: {}", result.text_out());
        assert!(result.text_out().contains("line3"), "output: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_heredoc_variable_expansion() {
        // Bug N: unquoted heredoc should expand variables
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("GREETING=hello").await.expect("set var");

        let result = kernel
            .execute("cat <<EOF\n$GREETING world\nEOF")
            .await
            .expect("heredoc expansion failed");

        assert!(result.ok(), "heredoc expansion failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "hello world");
    }

    #[tokio::test]
    async fn test_heredoc_quoted_no_expansion() {
        // Bug N: quoted heredoc (<<'EOF') should NOT expand variables
        let kernel = Kernel::transient().expect("failed to create kernel");

        kernel.execute("GREETING=hello").await.expect("set var");

        let result = kernel
            .execute("cat <<'EOF'\n$GREETING world\nEOF")
            .await
            .expect("quoted heredoc failed");

        assert!(result.ok(), "quoted heredoc failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "$GREETING world");
    }

    #[tokio::test]
    async fn test_heredoc_default_value_expansion() {
        // Bug N: ${VAR:-default} should expand in unquoted heredocs
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute("cat <<EOF\n${UNSET:-fallback}\nEOF")
            .await
            .expect("heredoc default expansion failed");

        assert!(result.ok(), "heredoc default expansion failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "fallback");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Read Builtin Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_read_from_pipeline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Pipe input to read
        let result = kernel
            .execute(r#"echo "Alice" | read NAME; echo "Hello, ${NAME}""#)
            .await
            .expect("read pipeline failed");

        assert!(result.ok(), "read failed: {}", result.err);
        assert!(result.text_out().contains("Hello, Alice"), "output: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_read_multiple_vars_from_pipeline() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel
            .execute(r#"echo "John Doe 42" | read FIRST LAST AGE; echo "${FIRST} is ${AGE}""#)
            .await
            .expect("read pipeline failed");

        assert!(result.ok(), "read failed: {}", result.err);
        assert!(result.text_out().contains("John is 42"), "output: {}", result.text_out());
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Shell-Style Function Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_posix_function_with_positional_params() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define POSIX-style function
        kernel
            .execute(r#"greet() { echo "Hello, $1!" }"#)
            .await
            .expect("function definition failed");

        // Call the function
        let result = kernel
            .execute(r#"greet "Amy""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "greet failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hello, Amy!");
    }

    #[tokio::test]
    async fn test_posix_function_multiple_args() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define function using $1 and $2
        kernel
            .execute(r#"add_greeting() { echo "$1 $2!" }"#)
            .await
            .expect("function definition failed");

        // Call the function
        let result = kernel
            .execute(r#"add_greeting "Hello" "World""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "function failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hello World!");
    }

    #[tokio::test]
    async fn test_bash_function_with_positional_params() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define bash-style function (function keyword, no parens)
        kernel
            .execute(r#"function greet { echo "Hi $1" }"#)
            .await
            .expect("function definition failed");

        // Call the function
        let result = kernel
            .execute(r#"greet "Bob""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "greet failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hi Bob");
    }

    #[tokio::test]
    async fn test_shell_function_with_all_args() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define function using $@ (all args)
        kernel
            .execute(r#"echo_all() { echo "args: $@" }"#)
            .await
            .expect("function definition failed");

        // Call with multiple args
        let result = kernel
            .execute(r#"echo_all "a" "b" "c""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "function failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "args: a b c");
    }

    #[tokio::test]
    async fn test_shell_function_with_arg_count() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Define function using $# (arg count)
        kernel
            .execute(r#"count_args() { echo "count: $#" }"#)
            .await
            .expect("function definition failed");

        // Call with three args
        let result = kernel
            .execute(r#"count_args "x" "y" "z""#)
            .await
            .expect("function call failed");

        assert!(result.ok(), "function failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "count: 3");
    }

    #[tokio::test]
    async fn test_shell_function_shared_scope() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Set a variable in parent scope
        kernel
            .execute(r#"PARENT_VAR="visible""#)
            .await
            .expect("set failed");

        // Define shell function that reads and writes parent variable
        kernel
            .execute(r#"modify_parent() {
                echo "saw: ${PARENT_VAR}"
                PARENT_VAR="changed by function"
            }"#)
            .await
            .expect("function definition failed");

        // Call the function - it SHOULD see PARENT_VAR (bash-compatible shared scope)
        let result = kernel.execute("modify_parent").await.expect("function failed");

        assert!(
            result.text_out().contains("visible"),
            "Shell function should access parent scope, got: {}",
            result.text_out()
        );

        // Parent variable should be modified
        let var = kernel.get_var("PARENT_VAR").await;
        assert_eq!(
            var,
            Some(Value::String("changed by function".into())),
            "Shell function should modify parent scope"
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Script Execution via PATH Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_script_execution_from_path() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Create /bin directory and script
        kernel.execute(r#"mkdir "/bin""#).await.ok();
        kernel
            .execute(r#"write "/bin/hello.kai" 'echo "Hello from script!"'"#)
            .await
            .expect("write script failed");

        // Set PATH to /bin
        kernel.execute(r#"PATH="/bin""#).await.expect("set PATH failed");

        // Call script by name (without .kai extension)
        let result = kernel
            .execute("hello")
            .await
            .expect("script execution failed");

        assert!(result.ok(), "script failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hello from script!");
    }

    #[tokio::test]
    async fn test_script_with_args() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Create script that uses positional params
        kernel.execute(r#"mkdir "/bin""#).await.ok();
        kernel
            .execute(r#"write "/bin/greet.kai" 'echo "Hello, $1!"'"#)
            .await
            .expect("write script failed");

        // Set PATH
        kernel.execute(r#"PATH="/bin""#).await.expect("set PATH failed");

        // Call script with arg
        let result = kernel
            .execute(r#"greet "World""#)
            .await
            .expect("script execution failed");

        assert!(result.ok(), "script failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Hello, World!");
    }

    #[tokio::test]
    async fn test_script_not_found() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Set empty PATH
        kernel.execute(r#"PATH="/nonexistent""#).await.expect("set PATH failed");

        // Call non-existent script
        let result = kernel
            .execute("noscript")
            .await
            .expect("execution failed");

        assert!(!result.ok(), "should fail with command not found");
        assert_eq!(result.code, 127);
        assert!(result.err.contains("command not found"));
    }

    #[tokio::test]
    async fn test_script_path_search_order() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Create two directories with same-named script
        // Note: using "myscript" not "test" to avoid conflict with test builtin
        kernel.execute(r#"mkdir "/first""#).await.ok();
        kernel.execute(r#"mkdir "/second""#).await.ok();
        kernel
            .execute(r#"write "/first/myscript.kai" 'echo "from first"'"#)
            .await
            .expect("write failed");
        kernel
            .execute(r#"write "/second/myscript.kai" 'echo "from second"'"#)
            .await
            .expect("write failed");

        // Set PATH with first before second
        kernel.execute(r#"PATH="/first:/second""#).await.expect("set PATH failed");

        // Should find first one
        let result = kernel
            .execute("myscript")
            .await
            .expect("script execution failed");

        assert!(result.ok(), "script failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "from first");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Special Variable Tests ($?, $$, unset vars)
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_last_exit_code_success() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // true exits with 0
        let result = kernel.execute("true; echo $?").await.expect("execution failed");
        assert!(result.text_out().contains("0"), "expected 0, got: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_last_exit_code_failure() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // false exits with 1
        let result = kernel.execute("false; echo $?").await.expect("execution failed");
        assert!(result.text_out().contains("1"), "expected 1, got: {}", result.text_out());
    }

    #[tokio::test]
    async fn test_current_pid() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        let result = kernel.execute("echo $$").await.expect("execution failed");
        // PID should be a positive number
        let pid: u32 = result.text_out().trim().parse().expect("PID should be a number");
        assert!(pid > 0, "PID should be positive");
    }

    #[tokio::test]
    async fn test_unset_variable_expands_to_empty() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Unset variable in interpolation should be empty
        let result = kernel.execute(r#"echo "prefix:${UNSET_VAR}:suffix""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "prefix::suffix");
    }

    #[tokio::test]
    async fn test_eq_ne_operators() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Test -eq operator
        let result = kernel.execute(r#"if [[ 5 -eq 5 ]]; then echo "eq works"; fi"#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "eq works");

        // Test -ne operator
        let result = kernel.execute(r#"if [[ 5 -ne 3 ]]; then echo "ne works"; fi"#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "ne works");

        // Test -eq with different values
        let result = kernel.execute(r#"if [[ 5 -eq 3 ]]; then echo "wrong"; else echo "correct"; fi"#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "correct");
    }

    #[tokio::test]
    async fn test_escaped_dollar_in_string() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // \$ should produce literal $
        let result = kernel.execute(r#"echo "\$100""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "$100");
    }

    #[tokio::test]
    async fn test_special_vars_in_interpolation() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Test $? in string interpolation
        let result = kernel.execute(r#"true; echo "exit: $?""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "exit: 0");

        // Test $$ in string interpolation
        let result = kernel.execute(r#"echo "pid: $$""#).await.expect("execution failed");
        assert!(result.text_out().starts_with("pid: "), "unexpected output: {}", result.text_out());
        let text = result.text_out();
        let pid_part = text.trim().strip_prefix("pid: ").unwrap();
        let _pid: u32 = pid_part.parse().expect("PID in string should be a number");
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Command Substitution Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_command_subst_assignment() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Command substitution in assignment
        let result = kernel.execute(r#"X=$(echo hello); echo "$X""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "hello");
    }

    #[tokio::test]
    async fn test_command_subst_with_args() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Command substitution with string argument
        let result = kernel.execute(r#"X=$(echo "a b c"); echo "$X""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "a b c");
    }

    #[tokio::test]
    async fn test_command_subst_nested_vars() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Variables inside command substitution
        let result = kernel.execute(r#"Y=world; X=$(echo "hello $Y"); echo "$X""#).await.expect("execution failed");
        assert_eq!(result.text_out().trim(), "hello world");
    }

    #[tokio::test]
    async fn test_background_job_basic() {
        use std::time::Duration;

        let kernel = Kernel::new(KernelConfig::isolated()).expect("failed to create kernel");

        // Run a simple background command
        let result = kernel.execute("echo hello &").await.expect("execution failed");
        assert!(result.ok(), "background command should succeed: {}", result.err);
        assert!(result.text_out().contains("[1]"), "should return job ID: {}", result.text_out());

        // Give the job time to complete
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Check job status
        let status = kernel.execute("cat /v/jobs/1/status").await.expect("status check failed");
        assert!(status.ok(), "status should succeed: {}", status.err);
        assert!(
            status.text_out().contains("done:") || status.text_out().contains("running"),
            "should have valid status: {}",
            status.text_out()
        );

        // Check stdout
        let stdout = kernel.execute("cat /v/jobs/1/stdout").await.expect("stdout check failed");
        assert!(stdout.ok());
        assert!(stdout.text_out().contains("hello"));
    }

    #[tokio::test]
    async fn test_heredoc_piped_to_command() {
        // Bug 4: heredoc content should pipe through to next command
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel.execute("cat <<EOF | cat\nhello world\nEOF").await.expect("exec");
        assert!(result.ok(), "heredoc | cat failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "hello world");
    }

    #[tokio::test]
    async fn test_for_loop_glob_iterates() {
        // Bug 1: for F in $(glob ...) should iterate per file, not once
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_glob_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("echo a > {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("echo b > {dir}/b.txt")).await.unwrap();
        let result = kernel.execute(&format!(r#"
            N=0
            for F in $(glob "{dir}/*.txt"); do
                N=$((N + 1))
            done
            echo $N
        "#)).await.unwrap();
        assert!(result.ok(), "for glob failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "2", "Should iterate 2 files, got: {}", result.text_out());
        kernel.execute(&format!("rm {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("rm {dir}/b.txt")).await.unwrap();
    }

    #[tokio::test]
    async fn test_bare_glob_expansion_echo() {
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_bareglob_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("echo a > {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("echo b > {dir}/b.txt")).await.unwrap();
        kernel.execute(&format!("echo c > {dir}/c.rs")).await.unwrap();
        kernel.execute(&format!("cd {dir}")).await.unwrap();
        let result = kernel.execute("echo *.txt").await.unwrap();
        assert!(result.ok(), "echo *.txt failed: {}", result.err);
        let out = result.text_out();
        let out = out.trim();
        // Should contain both .txt files (order may vary)
        assert!(out.contains("a.txt"), "missing a.txt in: {}", out);
        assert!(out.contains("b.txt"), "missing b.txt in: {}", out);
        assert!(!out.contains("c.rs"), "should not contain c.rs in: {}", out);
        // cleanup
        kernel.execute(&format!("rm {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("rm {dir}/b.txt")).await.unwrap();
        kernel.execute(&format!("rm {dir}/c.rs")).await.unwrap();
    }

    #[tokio::test]
    async fn test_bare_glob_no_matches_errors() {
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_bareglob_nomatch_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("cd {dir}")).await.unwrap();
        let result = kernel.execute("echo *.nonexistent").await;
        match &result {
            Ok(exec) => {
                // No-match glob should produce a non-zero exit code
                assert!(!exec.ok(), "expected failure, got success: out={}, err={}", exec.text_out(), exec.err);
                assert!(exec.err.contains("no matches"), "error should say no matches: {}", exec.err);
            }
            Err(e) => {
                assert!(e.to_string().contains("no matches"), "error should say no matches: {}", e);
            }
        }
    }

    #[tokio::test]
    async fn test_bare_glob_disabled_with_set() {
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_bareglob_noglob_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("echo a > {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("cd {dir}")).await.unwrap();
        // Disable glob expansion
        kernel.execute("set +o glob").await.unwrap();
        let result = kernel.execute("echo *.txt").await.unwrap();
        // With glob disabled, *.txt should be passed as literal string
        assert!(result.ok(), "echo should succeed: {}", result.err);
        assert_eq!(result.text_out().trim(), "*.txt", "should be literal: {}", result.text_out());
        // cleanup
        kernel.execute("set -o glob").await.unwrap();
        kernel.execute(&format!("rm {dir}/a.txt")).await.unwrap();
    }

    #[tokio::test]
    async fn test_bare_glob_quoted_not_expanded() {
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_bareglob_quoted_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("echo a > {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("cd {dir}")).await.unwrap();
        // Quoted globs should NOT expand
        let result = kernel.execute("echo \"*.txt\"").await.unwrap();
        assert!(result.ok(), "echo should succeed: {}", result.err);
        assert_eq!(result.text_out().trim(), "*.txt", "quoted should be literal: {}", result.text_out());
        // cleanup
        kernel.execute(&format!("rm {dir}/a.txt")).await.unwrap();
    }

    #[tokio::test]
    async fn test_bare_glob_for_loop() {
        let kernel = Kernel::transient().expect("kernel");
        let dir = format!("/tmp/kaish_test_bareglob_forloop_{}", std::process::id());
        kernel.execute(&format!("mkdir -p {dir}")).await.unwrap();
        kernel.execute(&format!("echo a > {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("echo b > {dir}/b.txt")).await.unwrap();
        kernel.execute(&format!("cd {dir}")).await.unwrap();
        let result = kernel.execute(r#"
            N=0
            for f in *.txt; do
                N=$((N + 1))
            done
            echo $N
        "#).await.unwrap();
        assert!(result.ok(), "for loop failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "2", "should iterate 2 files: {}", result.text_out());
        // cleanup
        kernel.execute(&format!("rm {dir}/a.txt")).await.unwrap();
        kernel.execute(&format!("rm {dir}/b.txt")).await.unwrap();
    }

    #[tokio::test]
    async fn test_glob_in_assignment_is_literal() {
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel.execute("X=*.txt; echo $X").await.unwrap();
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "*.txt", "glob in assignment should be literal");
    }

    #[tokio::test]
    async fn test_glob_in_test_expr_is_literal() {
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel.execute(r#"
            if [[ *.txt == "*.txt" ]]; then
                echo "match"
            else
                echo "no"
            fi
        "#).await.unwrap();
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "match", "glob in test expr should be literal");
    }

    #[tokio::test]
    async fn test_command_subst_echo_not_iterable() {
        // Regression guard: $(echo "a b c") must remain a single string
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel.execute(r#"
            N=0
            for X in $(echo "a b c"); do N=$((N + 1)); done
            echo $N
        "#).await.unwrap();
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "1", "echo should be one item: {}", result.text_out());
    }

    // -- accumulate_result / newline tests --

    #[test]
    fn test_accumulate_no_double_newlines() {
        // When output already ends with \n, accumulate should not add another
        let mut acc = ExecResult::success("line1\n");
        let new = ExecResult::success("line2\n");
        accumulate_result(&mut acc, &new);
        assert_eq!(&*acc.text_out(), "line1\nline2\n");
        assert!(!acc.text_out().contains("\n\n"), "should not have double newlines: {:?}", acc.text_out());
    }

    #[test]
    fn test_accumulate_adds_separator_when_needed() {
        // When output does NOT end with \n, accumulate adds one
        let mut acc = ExecResult::success("line1");
        let new = ExecResult::success("line2");
        accumulate_result(&mut acc, &new);
        assert_eq!(&*acc.text_out(), "line1\nline2");
    }

    #[test]
    fn test_accumulate_empty_into_nonempty() {
        let mut acc = ExecResult::success("");
        let new = ExecResult::success("hello\n");
        accumulate_result(&mut acc, &new);
        assert_eq!(&*acc.text_out(), "hello\n");
    }

    #[test]
    fn test_accumulate_nonempty_into_empty() {
        let mut acc = ExecResult::success("hello\n");
        let new = ExecResult::success("");
        accumulate_result(&mut acc, &new);
        assert_eq!(&*acc.text_out(), "hello\n");
    }

    #[test]
    fn test_accumulate_stderr_no_double_newlines() {
        let mut acc = ExecResult::failure(1, "err1\n");
        let new = ExecResult::failure(1, "err2\n");
        accumulate_result(&mut acc, &new);
        assert!(!acc.err.contains("\n\n"), "stderr should not have double newlines: {:?}", acc.err);
    }

    #[tokio::test]
    async fn test_multiple_echo_no_blank_lines() {
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel
            .execute("echo one\necho two\necho three")
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert_eq!(&*result.text_out(), "one\ntwo\nthree\n");
    }

    #[tokio::test]
    async fn test_for_loop_no_blank_lines() {
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel
            .execute(r#"for X in a b c; do echo "item: ${X}"; done"#)
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert_eq!(&*result.text_out(), "item: a\nitem: b\nitem: c\n");
    }

    #[tokio::test]
    async fn test_for_command_subst_no_blank_lines() {
        let kernel = Kernel::transient().expect("kernel");
        let result = kernel
            .execute(r#"for N in $(seq 1 3); do echo "n=${N}"; done"#)
            .await
            .expect("execution failed");
        assert!(result.ok());
        assert_eq!(&*result.text_out(), "n=1\nn=2\nn=3\n");
    }

    // ------------------------------------------------------------------
    // build_args_async: multi-consume flags (jq --arg NAME VALUE pattern)
    // ------------------------------------------------------------------

    /// Helper: a throwaway schema with one `--pair` param declared as
    /// consuming two positionals per occurrence. Modelled after what
    /// jq_native will declare for `--arg` / `--argjson`.
    fn multi_consume_schema() -> crate::tools::ToolSchema {
        use crate::tools::{ParamSchema, ToolSchema};
        ToolSchema::new("test", "multi-consume smoke")
            .param(
                ParamSchema::optional("pair", "array", Value::Null, "name+value pair")
                    .consumes(2),
            )
    }

    fn pos(s: &str) -> Arg {
        Arg::Positional(Expr::Literal(Value::String(s.to_string())))
    }

    #[tokio::test]
    async fn build_args_multi_consume_single_occurrence() {
        let kernel = Kernel::transient().expect("kernel");
        let schema = multi_consume_schema();
        // Simulates:  test --pair NAME VALUE filter
        let args = vec![
            Arg::LongFlag("pair".into()),
            pos("NAME"),
            pos("VALUE"),
            pos("filter"),
        ];
        let built = kernel
            .build_args_async(&args, Some(&schema))
            .await
            .expect("build_args should succeed");

        // `--pair` + its two positionals are consumed into named["pair"],
        // which becomes an outer array of one inner 2-element array.
        let pair = built.named.get("pair").expect("named[pair] missing");
        match pair {
            Value::Json(serde_json::Value::Array(occurrences)) => {
                assert_eq!(occurrences.len(), 1, "expected one occurrence");
                match &occurrences[0] {
                    serde_json::Value::Array(values) => {
                        assert_eq!(values.len(), 2, "pair must have 2 values");
                        assert_eq!(values[0], serde_json::Value::String("NAME".into()));
                        assert_eq!(values[1], serde_json::Value::String("VALUE".into()));
                    }
                    other => panic!("expected inner array, got {other:?}"),
                }
            }
            other => panic!("expected Json(Array(...)) for named[pair], got {other:?}"),
        }

        // The un-consumed positional ("filter") remains in `positional`.
        assert_eq!(built.positional.len(), 1);
        assert_eq!(built.positional[0], Value::String("filter".into()));
    }

    #[tokio::test]
    async fn build_args_multi_consume_two_occurrences_accumulate() {
        let kernel = Kernel::transient().expect("kernel");
        let schema = multi_consume_schema();
        // Simulates:  test --pair A 1 --pair B 2 filter
        let args = vec![
            Arg::LongFlag("pair".into()),
            pos("A"),
            pos("1"),
            Arg::LongFlag("pair".into()),
            pos("B"),
            pos("2"),
            pos("filter"),
        ];
        let built = kernel
            .build_args_async(&args, Some(&schema))
            .await
            .expect("build_args should succeed");

        let pair = built.named.get("pair").expect("named[pair] missing");
        match pair {
            Value::Json(serde_json::Value::Array(occurrences)) => {
                assert_eq!(occurrences.len(), 2, "expected two occurrences");
                // Preserved in invocation order.
                match &occurrences[0] {
                    serde_json::Value::Array(values) => {
                        assert_eq!(values[0], serde_json::Value::String("A".into()));
                        assert_eq!(values[1], serde_json::Value::String("1".into()));
                    }
                    other => panic!("expected inner array, got {other:?}"),
                }
                match &occurrences[1] {
                    serde_json::Value::Array(values) => {
                        assert_eq!(values[0], serde_json::Value::String("B".into()));
                        assert_eq!(values[1], serde_json::Value::String("2".into()));
                    }
                    other => panic!("expected inner array, got {other:?}"),
                }
            }
            other => panic!("expected Json(Array(...)), got {other:?}"),
        }
    }

    // ── initial_vars + execute_with_vars + hermetic env ───────────────────

    #[tokio::test]
    async fn test_initial_vars_set_and_exported() {
        let config = KernelConfig::transient()
            .with_var("INIT_FOO", Value::String("bar".into()));
        let kernel = Kernel::new(config).expect("failed to create kernel");

        assert_eq!(
            kernel.get_var("INIT_FOO").await,
            Some(Value::String("bar".into()))
        );
        assert!(
            kernel.scope.read().await.is_exported("INIT_FOO"),
            "initial_vars entries must be marked exported"
        );
    }

    #[tokio::test]
    async fn test_execute_with_vars_overlay_visible() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let mut overlay = HashMap::new();
        overlay.insert("OVERLAY_X".to_string(), Value::String("yes".into()));

        let result = kernel
            .execute_with_options(r#"echo "${OVERLAY_X}""#, ExecuteOptions::new().with_vars(overlay))
            .await
            .expect("execute failed");

        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "yes");
    }

    #[tokio::test]
    async fn test_execute_with_vars_overlay_cleanup() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let mut overlay = HashMap::new();
        overlay.insert("EPHEMERAL".to_string(), Value::String("transient".into()));

        kernel
            .execute_with_options("echo ignored", ExecuteOptions::new().with_vars(overlay))
            .await
            .expect("execute failed");

        assert_eq!(kernel.get_var("EPHEMERAL").await, None);
        assert!(
            !kernel.scope.read().await.is_exported("EPHEMERAL"),
            "overlay-only export must be cleared on return"
        );
    }

    #[tokio::test]
    async fn test_execute_with_vars_does_not_clobber_existing_export() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        kernel
            .execute("export OUTER=outer")
            .await
            .expect("export failed");

        let mut overlay = HashMap::new();
        overlay.insert("OUTER".to_string(), Value::String("inner".into()));
        let result = kernel
            .execute_with_options(r#"echo "${OUTER}""#, ExecuteOptions::new().with_vars(overlay))
            .await
            .expect("execute failed");
        assert_eq!(result.text_out().trim(), "inner");

        assert_eq!(
            kernel.get_var("OUTER").await,
            Some(Value::String("outer".into())),
            "outer value must reappear after pop"
        );
        assert!(
            kernel.scope.read().await.is_exported("OUTER"),
            "outer export must survive overlay"
        );
    }

    #[tokio::test]
    async fn test_execute_with_vars_inner_assignment_is_local() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let mut overlay = HashMap::new();
        overlay.insert("LOCAL_FOO".to_string(), Value::String("from-overlay".into()));

        // Variable assignment inside a single statement uses set() (innermost
        // frame), not set_global() — this matches bash function-local semantics.
        // We explicitly use `local FOO=...` style by relying on the pushed
        // frame; the assignment in the script body modifies the same frame.
        let result = kernel
            .execute_with_options(
                r#"LOCAL_FOO="reassigned"; echo "${LOCAL_FOO}""#,
                ExecuteOptions::new().with_vars(overlay),
            )
            .await
            .expect("execute failed");
        assert!(result.ok());

        // After the call the frame is popped, so LOCAL_FOO is gone regardless
        // of how the script reassigned it.
        assert_eq!(kernel.get_var("LOCAL_FOO").await, None);
    }

    #[tokio::test]
    async fn test_external_command_sees_exported_var() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute("export EXT_FOO=bar; printenv EXT_FOO")
            .await
            .expect("execute failed");

        assert!(result.ok(), "printenv should succeed: stderr={}", result.err);
        assert_eq!(result.text_out().trim(), "bar");
    }

    #[tokio::test]
    async fn test_external_command_does_not_see_unexported_var() {
        let kernel = Kernel::transient().expect("failed to create kernel");

        // Set without exporting; printenv must not see it (exit code != 0,
        // empty stdout per printenv semantics).
        let result = kernel
            .execute("EXT_BAR=hidden; printenv EXT_BAR")
            .await
            .expect("execute failed");

        assert!(!result.ok(), "printenv should fail when var is unexported");
        assert!(
            result.text_out().trim().is_empty(),
            "no stdout when var is missing, got: {}",
            result.text_out()
        );
    }

    #[tokio::test]
    async fn test_external_command_does_not_see_os_env() {
        // The kernel is hermetic: it never reads std::env::vars() and only
        // exports what it has been told to export. Cargo always sets PATH for
        // tests, so PATH is reliably present in the OS env — but a transient
        // kernel doesn't seed it into initial_vars, so `printenv PATH` from
        // inside the kernel must fail.
        assert!(
            std::env::var_os("PATH").is_some(),
            "test precondition: cargo should set PATH"
        );

        let kernel = Kernel::transient().expect("failed to create kernel");
        let result = kernel
            .execute("printenv PATH")
            .await
            .expect("execute failed");

        assert!(
            !result.ok(),
            "printenv PATH must fail in hermetic kernel, got stdout={:?}",
            result.text_out()
        );
        assert!(
            result.text_out().trim().is_empty(),
            "no PATH in subprocess env, got stdout={:?}",
            result.text_out()
        );
    }

    #[tokio::test]
    async fn test_execute_with_vars_overlay_reaches_subprocess() {
        let kernel = Kernel::transient().expect("failed to create kernel");
        let mut overlay = HashMap::new();
        overlay.insert("SUB_FOO".to_string(), Value::String("subproc".into()));

        let result = kernel
            .execute_with_options("printenv SUB_FOO", ExecuteOptions::new().with_vars(overlay))
            .await
            .expect("execute failed");

        assert!(
            result.ok(),
            "printenv should succeed: code={} stdout={:?} stderr={:?}",
            result.code,
            result.text_out(),
            result.err
        );
        assert_eq!(result.text_out().trim(), "subproc");
    }
}