dekopon-shell 0.15.2

Sandboxed bash-flavored script interpreter whose commands dispatch to Dekopon capabilities
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
//! The tree-walking evaluator.
//!
//! # Namespace isolation
//!
//! The variable namespace is seeded **only** from the script's own `NAME=value` assignments. This
//! module never calls [`std::env`]. A script that reads `$PATH` or `$OPENAI_API_KEY` sees an unset
//! variable, not the host process's value, and
//! [`crate::interp::tests::the_process_environment_never_leaks_into_a_script`] proves it.
//!
//! # Scoping
//!
//! Variables are dynamically scoped exactly as bash scopes them: global by default, and `local`
//! shadows a name for the current function frame *and* every frame it calls into.

use std::{
    cmp::Ordering,
    collections::{BTreeMap, BTreeSet},
    rc::Rc,
};

use serde_json::Value;

use crate::{
    CapabilityInvoker, CommandRun, ExitCode, ScriptOutcome,
    ast::{
        AndOr, AndOrList, ArithBinaryOp, ArithExpr, ArithUnaryOp, CasePattern, CaseStatement,
        Command, Conditional, ConditionalTest, DEV_NULL, ForLoop, IfStatement, Index, Modifier,
        Parameter, Pattern, Pipeline, Program, Redirect, RedirectTarget, SimpleCommand, Statement,
        Stream, WhileLoop, Word, WordPart,
    },
    builtins::{
        self, BuiltinContext, BuiltinKind, CommandFailure, CommandResult, FatalError, xargs,
    },
    dispatch::{self, Resolution},
    limits::{Budget, LimitExceeded, Limits, OutputBuffer},
    parser::{
        expanded_case_pattern, expanded_conditional_pattern, expanded_parameter_pattern, parse,
        pattern_metacharacter,
    },
    value::{self, display},
};

use telemetry::CommandKind;

pub(crate) mod telemetry;

/// Control-flow signals that unwind through the evaluator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Flow {
    Normal,
    Break(u32),
    Continue(u32),
    Return(ExitCode),
    Exit(ExitCode),
}

/// What executing one command produced.
enum Executed {
    Result(CommandResult),
    Flow(Flow),
}

/// The shell options `set` toggles.
///
/// Each one is enforced, not accepted-and-ignored: the reason `set` was refused outright before was
/// that an option which changed nothing while looking like it had is exactly the class of silent
/// wrongness this shell exists to refuse. That reason stops applying once the option is real.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct ShellOptions {
    /// `set -e`: a command that fails outside a tested position ends the script.
    errexit: bool,
    /// `set -u`: expanding a parameter nothing ever set ends the script.
    nounset: bool,
    /// `set -o pipefail`: a pipeline reports its rightmost failure, not just its last stage.
    pipefail: bool,
}

/// Where one of a command's two streams ends up.
///
/// [`Sink::Value`] and [`Sink::Diagnostics`] are the two defaults, and they are also what a
/// duplication copies: `2>&1` gives stderr the sink stdout holds, and `>&2` the reverse. They are
/// destinations in their own right rather than "unredirected", which is what makes
/// `x=$(cmd 2>&1)` capture the diagnostics the way a real shell does.
#[derive(Clone, Debug, Eq, PartialEq)]
enum Sink {
    /// The value channel: what the command produces, and what `$( )` captures.
    Value,
    /// The diagnostic channel: text lines that escape a capture, as a terminal's stderr does.
    Diagnostics,
    /// `/dev/null`.
    Discard,
    /// A named in-memory buffer.
    Buffer {
        /// Buffer name.
        name: String,
        /// `true` for the `>>` forms.
        append: bool,
    },
}

/// One entry on the stdin stack: the piped value, and how far `read` has consumed it.
///
/// The cursor is what separates `read` from every other way of looking at input. `cat` is offered
/// the whole value on each pipeline in the body — deliberately, so a condition that never reads it
/// cannot swallow it — while `read` *consumes*, one line per call, which is the only way
/// `while read line` can terminate rather than seeing line one forever.
#[derive(Debug, Default)]
struct StdinSource {
    value: Option<Rc<Value>>,
    /// Lines split from `value`, materialized on the first `read` and never again.
    lines: Option<Vec<String>>,
    /// How many of those lines `read` has taken.
    position: usize,
}

impl StdinSource {
    fn new(value: Option<Rc<Value>>) -> Self {
        Self {
            value,
            lines: None,
            position: 0,
        }
    }

    /// Takes the next unread line, or `None` at end of input.
    fn next_line(&mut self) -> Option<String> {
        let lines = self.lines.get_or_insert_with(|| {
            self.value
                .as_deref()
                .map(value::to_lines)
                .unwrap_or_default()
        });
        let line = lines.get(self.position).cloned();
        if line.is_some() {
            self.position += 1;
        }
        line
    }
}

/// Diagnostics collected while one command's stderr is redirected.
///
/// Bounded by the same output ceilings the combined stream uses. A shell function called as
/// `f 2> log` can run thousands of commands, so this must not be the one accumulator in the
/// interpreter without a ceiling.
#[derive(Debug)]
struct StderrCapture {
    lines: Vec<String>,
    bytes: usize,
    max_lines: usize,
    max_bytes: usize,
    truncated: bool,
}

impl StderrCapture {
    fn new(limits: &Limits) -> Self {
        Self {
            lines: Vec::new(),
            bytes: 0,
            max_lines: limits.max_output_lines,
            max_bytes: limits.max_output_bytes,
            truncated: false,
        }
    }

    fn push(&mut self, line: &str) {
        if self.lines.len() >= self.max_lines || self.bytes + line.len() > self.max_bytes {
            self.truncated = true;
            return;
        }
        self.bytes += line.len();
        self.lines.push(line.to_owned());
    }

    /// Returns the captured lines, with a marker line when any were dropped.
    fn finish(mut self) -> Vec<String> {
        if self.truncated {
            self.lines
                .push("... redirected diagnostics truncated ...".to_owned());
        }
        self.lines
    }
}

/// One shell-function activation.
#[derive(Debug, Default)]
struct Frame {
    locals: BTreeMap<String, Value>,
    positional: Vec<Value>,
}

/// Parses and evaluates one script, returning its outcome.
pub(crate) fn run(script: &str, invoker: &dyn CapabilityInvoker, limits: Limits) -> ScriptOutcome {
    let program = match parse(script) {
        Ok(program) => program,
        Err(error) => {
            return ScriptOutcome {
                output: format!("dekopon-shell: syntax error: {error}"),
                exit_code: ExitCode::SYNTAX,
                truncated: false,
                capability_calls: 0,
                steps: 0,
            };
        }
    };

    let mut evaluator = Evaluator {
        invoker,
        budget: Budget::start(limits),
        limits,
        output: OutputBuffer::new(&limits),
        globals: BTreeMap::new(),
        frames: Vec::new(),
        functions: BTreeMap::new(),
        function_names: BTreeSet::new(),
        buffers: BTreeMap::new(),
        captures: Vec::new(),
        options: ShellOptions::default(),
        testing_status: 0,
        stdin: Vec::new(),
        stderr_capture: Vec::new(),
        counters: telemetry::ScriptCounters::default(),
        last_status: ExitCode::SUCCESS,
        last_substitution_status: ExitCode::SUCCESS,
    };

    // One span for the whole run, so the totals have a home that costs the same whether a script
    // ran three commands or thirty thousand. Every `shell.command` span nests inside it.
    let script = telemetry::script_span();
    let exit_code = {
        let _entered = script.enter();
        match evaluator.execute_program(&program) {
            Ok(Flow::Exit(code)) => code,
            Ok(Flow::Return(code)) => code,
            Ok(_) => evaluator.last_status,
            Err(fatal) => evaluator.report_fatal(&fatal),
        }
    };
    evaluator.counters.record_on(&script);

    evaluator.output.finish();
    ScriptOutcome {
        output: evaluator.output.render(),
        exit_code,
        truncated: evaluator.output.is_truncated(),
        capability_calls: evaluator.budget.capability_calls(),
        steps: evaluator.budget.steps(),
    }
}

/// The evaluator's mutable state for one script execution.
///
/// This is deliberately *not* named `Interpreter`: [`crate::Interpreter`] is the public,
/// immutable configuration handle a caller builds, while this is the private machine that runs
/// one script under it. Sharing a name would send a reader following `Interpreter::run` to the
/// wrong type.
struct Evaluator<'a> {
    invoker: &'a dyn CapabilityInvoker,
    budget: Budget,
    /// The configured bounds, kept for the ceilings a redirected stderr capture reuses.
    limits: Limits,
    output: OutputBuffer,
    globals: BTreeMap<String, Value>,
    frames: Vec<Frame>,
    functions: BTreeMap<String, Rc<Program>>,
    function_names: BTreeSet<String>,
    buffers: BTreeMap<String, Value>,
    captures: Vec<Vec<CommandResult>>,
    /// The value piped into the enclosing call or compound stage, innermost last.
    ///
    /// Separate from [`Frame`] because the two nest differently: a shell function opens a variable
    /// scope *and* receives input, while a compound pipeline stage receives input and deliberately
    /// does not open a scope — `cmd | while read x; do total=$x; done` has to leave `total` set,
    /// which is the opposite of bash's subshell and the whole reason the idiom is worth having.
    ///
    /// Shared rather than owned: every pipeline in the body is offered it, so an owned value would
    /// be deep-copied once per statement — including for the statements that never read input —
    /// and all but the last copy dropped. See [`own`].
    stdin: Vec<StdinSource>,
    /// The options `set` has turned on.
    options: ShellOptions,
    /// How many enclosing positions are *testing* a status rather than depending on it.
    ///
    /// `errexit` must not fire for a command whose failure the script is already asking about: an
    /// `if`/`while`/`until` condition, every operand of an `&&`/`||` chain but the last, and a
    /// pipeline inverted by `!`. Bash draws exactly these three exemptions, and a counter rather
    /// than a flag is what keeps them composing — `if a && b; then` nests two of them.
    testing_status: u32,
    /// Diagnostic capture stack, one frame per command whose stderr is redirected.
    ///
    /// A stack rather than a field because a redirection nests: a shell function called as
    /// `f 2> log` collects its whole body's diagnostics, while a command *inside* that body with
    /// its own `2>` collects only its own and then restores the function's.
    stderr_capture: Vec<StderrCapture>,
    /// Per-script command totals, recorded on the script span when it closes.
    counters: telemetry::ScriptCounters,
    last_status: ExitCode,
    last_substitution_status: ExitCode,
}

impl Evaluator<'_> {
    // -----------------------------------------------------------------------
    // Diagnostics and output
    // -----------------------------------------------------------------------

    /// Reports a fatal error and returns the exit code the script ends with.
    ///
    /// The code half comes from [`telemetry::fatal_exit_code`] rather than from this match, so the
    /// code a `shell.command` span records for an aborted command is by construction the same one
    /// the script itself reports.
    fn report_fatal(&mut self, fatal: &FatalError) -> ExitCode {
        let message = match fatal {
            FatalError::Limit(LimitExceeded::Steps { maximum }) => format!(
                "dekopon-shell: step budget exhausted after {maximum} steps; the script is doing too much work or looping without progress"
            ),
            FatalError::Limit(LimitExceeded::RecursionDepth { maximum }) => {
                format!("dekopon-shell: shell functions nested deeper than {maximum} frames")
            }
            FatalError::Limit(LimitExceeded::Deadline { timeout_ms }) => {
                format!("dekopon-shell: script exceeded its {timeout_ms}ms deadline")
            }
            FatalError::Limit(LimitExceeded::CapabilityCalls { maximum }) => {
                format!("dekopon-shell: script tried to make more than {maximum} capability calls")
            }
            FatalError::Limit(LimitExceeded::ValueBytes { maximum }) => format!(
                "dekopon-shell: script tried to hold more than {maximum} bytes of values in variables, buffers, and substitutions"
            ),
            FatalError::Unsupported(reason) | FatalError::Assertion(reason) => {
                format!("dekopon-shell: {reason}")
            }
        };
        // Straight to the combined output, never into a redirected stderr capture: the script is
        // ending, the capture is about to be abandoned unrouted, and `cmd 2> log` must not be able
        // to swallow the one line explaining why nothing else ran.
        self.output.push_block(&message);
        telemetry::fatal_exit_code(fatal)
    }

    /// Writes one diagnostic to the diagnostic stream.
    ///
    /// Diagnostics escape a `$( )` capture on purpose. Only the *value* of a substitution is being
    /// captured; suppressing its errors too would leave `v=$(nosuchcmd)` with an empty variable, no
    /// explanation, and only a numeric `$?` the script may never inspect. Real shells send command
    /// substitution stderr to the terminal for exactly this reason. A script that *wants* them
    /// captured says so with `2>&1`, which is what the capture stack consulted here implements.
    fn write_line(&mut self, line: &str) {
        if let Some(capture) = self.stderr_capture.last_mut() {
            capture.push(line);
            return;
        }
        self.output.push_block(line);
    }

    /// Writes what one pipeline produced, to the capture that is collecting it or to the output.
    ///
    /// A command that produced no value writes nothing, and that has to be decided *before* the
    /// capture branch rather than after it. `$(true; echo a)` is `a` in bash; retaining `true`'s
    /// null in the capture made it a second element, and [`reduce_captured`] joins elements with a
    /// newline — so the substitution silently gained a leading blank line, or a trailing one for
    /// `$(echo a; true)`, depending on where the command that produced nothing happened to sit.
    /// The status such a command reported is unaffected: it travels through `last_status`, not
    /// through the capture.
    fn emit(&mut self, result: CommandResult) {
        if result.value.is_null() {
            return;
        }
        if let Some(capture) = self.captures.last_mut() {
            capture.push(result);
            return;
        }
        let text = display(&result.value);
        if result.suppress_newline {
            self.output.push_fragment(&text);
        } else {
            self.output.push_block(&text);
        }
    }

    /// Converts a recoverable failure into a status, or propagates a fatal one.
    fn absorb(&mut self, failure: CommandFailure) -> Result<ExitCode, FatalError> {
        match failure {
            CommandFailure::Status { message, status } => {
                self.write_line(&message);
                Ok(status)
            }
            CommandFailure::Fatal(fatal) => Err(fatal),
        }
    }

    /// Routes text a provider command word rendered itself onto the shell's two streams.
    ///
    /// No capability call is charged: the provider printed help, a version, or a usage error and
    /// invoked nothing. The bytes are charged against the value ceiling first, so a provider that
    /// renders a page the size of the ceiling trips the same limit a script materializing it
    /// would, and both streams then obey the output ceilings like any other write.
    ///
    /// Both texts arrive as the provider wrote them, which for `clap` means newline-terminated.
    /// Values here are not newline-terminated — emitting one is what adds the line ending — so
    /// one trailing newline is folded into the value model: `h=$(word --help)` holds the page the
    /// way `h=$(cat <<EOF ...)` would, and printing it adds the newline back exactly once. Text
    /// with no trailing newline is emitted as a fragment, the way `printf '%s'` is.
    fn emit_rendered(
        &mut self,
        stdout: String,
        stderr: String,
        status: u8,
    ) -> Result<Executed, FatalError> {
        self.budget
            .charge_value_bytes((stdout.len() + stderr.len()) as u64)?;
        if !stderr.is_empty() {
            self.write_line(stderr.strip_suffix('\n').unwrap_or(&stderr));
        }
        let status = ExitCode::from(status);
        if stdout.is_empty() {
            return Ok(Executed::Result(CommandResult::status(status)));
        }
        let result = match stdout.strip_suffix('\n') {
            Some(terminated) => CommandResult {
                value: Value::String(terminated.to_owned()),
                status,
                suppress_newline: false,
            },
            None => CommandResult {
                value: Value::String(stdout),
                status,
                suppress_newline: true,
            },
        };
        Ok(Executed::Result(result))
    }

    // -----------------------------------------------------------------------
    // Scope
    // -----------------------------------------------------------------------

    fn lookup(&self, name: &str) -> Option<&Value> {
        for frame in self.frames.iter().rev() {
            if let Some(value) = frame.locals.get(name) {
                return Some(value);
            }
        }
        self.globals.get(name)
    }

    /// Binds a name, charging what the value costs against the value-byte ceiling.
    ///
    /// Every retention point funnels through here, [`Evaluator::declare_local`], and
    /// [`Evaluator::write_buffer`]: `x="$x$x"` is one cheap step but doubles the bytes held, so
    /// counting operations alone leaves memory unbounded.
    fn assign(&mut self, name: &str, value: Value) -> Result<(), LimitExceeded> {
        self.budget.charge_value_bytes(value_bytes(&value))?;
        for frame in self.frames.iter_mut().rev() {
            if let Some(slot) = frame.locals.get_mut(name) {
                *slot = value;
                return Ok(());
            }
        }
        self.globals.insert(name.to_owned(), value);
        Ok(())
    }

    /// Restores a binding captured before a transient prefix assignment.
    fn restore(&mut self, name: &str, previous: Option<Value>) {
        match previous {
            Some(value) => {
                for frame in self.frames.iter_mut().rev() {
                    if let Some(slot) = frame.locals.get_mut(name) {
                        *slot = value;
                        return;
                    }
                }
                self.globals.insert(name.to_owned(), value);
            }
            // The prefix assignment created the binding, so removing it is what "restore" means.
            // `assign` writes to `globals` exactly when no frame already held the name.
            None => {
                self.globals.remove(name);
            }
        }
    }

    fn declare_local(&mut self, name: &str, value: Value) -> Result<(), LimitExceeded> {
        self.budget.charge_value_bytes(value_bytes(&value))?;
        if let Some(frame) = self.frames.last_mut() {
            frame.locals.insert(name.to_owned(), value);
            return Ok(());
        }
        self.globals.insert(name.to_owned(), value);
        Ok(())
    }

    fn positional(&self) -> &[Value] {
        self.frames
            .last()
            .map_or(&[][..], |frame| frame.positional.as_slice())
    }

    // -----------------------------------------------------------------------
    // Statements
    // -----------------------------------------------------------------------

    fn execute_program(&mut self, program: &Program) -> Result<Flow, FatalError> {
        for statement in &program.statements {
            match self.execute_statement(statement)? {
                Flow::Normal => {}
                other => return Ok(other),
            }
        }
        Ok(Flow::Normal)
    }

    fn execute_statement(&mut self, statement: &Statement) -> Result<Flow, FatalError> {
        self.budget.charge_step()?;
        match statement {
            Statement::List(list) => {
                let (status, flow) = self.execute_list(list)?;
                self.last_status = status;
                Ok(flow.unwrap_or(Flow::Normal))
            }
            Statement::If(statement) => self.execute_if(statement),
            Statement::For(statement) => self.execute_for(statement),
            Statement::While(statement) => self.execute_while(statement),
            Statement::Case(statement) => self.execute_case(statement),
            // A group runs its statements in the current scope; it exists to make several of them
            // one command, not to open a subshell this evaluator does not have.
            Statement::Group(body) => self.execute_program(body),
            Statement::Conditional(expression) => {
                let status = match self.evaluate_conditional(expression) {
                    Ok(status) => status,
                    Err(failure) => self.absorb(failure)?,
                };
                self.last_status = status;
                Ok(Flow::Normal)
            }
            Statement::Function(definition) => {
                self.function_names.insert(definition.name.clone());
                self.functions
                    .insert(definition.name.clone(), Rc::new(definition.body.clone()));
                self.last_status = ExitCode::SUCCESS;
                Ok(Flow::Normal)
            }
        }
    }

    fn execute_if(&mut self, statement: &IfStatement) -> Result<Flow, FatalError> {
        for (condition, body) in &statement.branches {
            let (status, flow) =
                self.tested(true, |evaluator| evaluator.execute_list(condition))?;
            self.last_status = status;
            if let Some(flow) = flow {
                return Ok(flow);
            }
            if status == ExitCode::SUCCESS {
                return self.execute_program(body);
            }
        }
        if let Some(otherwise) = &statement.otherwise {
            return self.execute_program(otherwise);
        }
        self.last_status = ExitCode::SUCCESS;
        Ok(Flow::Normal)
    }

    /// Runs the first `case` clause whose pattern matches, and no other.
    ///
    /// Every clause tested charges a step, the way a loop iteration does: a `case` with many
    /// alternatives inside a loop is real work, and a statement-level charge alone would let it
    /// run outside the step budget that bounds everything else.
    fn execute_case(&mut self, statement: &CaseStatement) -> Result<Flow, FatalError> {
        let subject = match self.expand_word(&statement.subject) {
            Ok(expanded) => expanded.join(" "),
            Err(failure) => {
                let status = self.absorb(failure)?;
                self.last_status = status;
                return Ok(Flow::Normal);
            }
        };

        for clause in &statement.clauses {
            for pattern in &clause.patterns {
                self.budget.charge_step()?;
                let matched = match pattern {
                    CasePattern::Any => true,
                    CasePattern::Literal(word) => match self.expand_word(word) {
                        Ok(expanded) => expanded.join(" ") == subject,
                        Err(failure) => {
                            let status = self.absorb(failure)?;
                            self.last_status = status;
                            return Ok(Flow::Normal);
                        }
                    },
                    // A pattern assembled at run time cannot be checked any earlier, so it is
                    // checked here: `p='*.json'; case $f in $p)` must not quietly compare the
                    // subject against the four literal characters `*`, `.`, `j`...
                    CasePattern::Expanded(word) => {
                        let expanded = match self.expand_word(word) {
                            Ok(expanded) => expanded.join(" "),
                            Err(failure) => {
                                let status = self.absorb(failure)?;
                                self.last_status = status;
                                return Ok(Flow::Normal);
                            }
                        };
                        if let Some((character, meaning)) = pattern_metacharacter(&expanded) {
                            self.write_line(&format!(
                                "dekopon-shell: {}",
                                expanded_case_pattern(character, meaning)
                            ));
                            self.last_status = ExitCode::SYNTAX;
                            return Ok(Flow::Normal);
                        }
                        expanded == subject
                    }
                };
                if matched {
                    return self.execute_program(&clause.body);
                }
            }
        }

        // No clause matched. bash reports success for that, and so does this: `case` asked a
        // question, and "none of the above" is an answer rather than a failure.
        self.last_status = ExitCode::SUCCESS;
        Ok(Flow::Normal)
    }

    fn execute_for(&mut self, statement: &ForLoop) -> Result<Flow, FatalError> {
        let mut items = Vec::new();
        for word in &statement.words {
            match self.expand_word(word) {
                Ok(expanded) => items.extend(expanded),
                Err(failure) => {
                    let status = self.absorb(failure)?;
                    self.last_status = status;
                    return Ok(Flow::Normal);
                }
            }
        }

        // A loop reports the status of the last command its body ran, or success when the body
        // never ran. The condition that ended the loop must not leak into `$?`, exactly as in bash.
        let mut body_status = ExitCode::SUCCESS;
        for item in items {
            self.budget.charge_step()?;
            self.assign(&statement.variable, Value::String(item))?;
            let flow = self.execute_program(&statement.body)?;
            body_status = self.last_status;
            match flow {
                Flow::Normal => {}
                Flow::Break(level) => {
                    self.last_status = body_status;
                    return Ok(unwind_break(level));
                }
                Flow::Continue(level) => {
                    if level > 1 {
                        self.last_status = body_status;
                        return Ok(Flow::Continue(level - 1));
                    }
                }
                terminal => return Ok(terminal),
            }
        }
        self.last_status = body_status;
        Ok(Flow::Normal)
    }

    fn execute_while(&mut self, statement: &WhileLoop) -> Result<Flow, FatalError> {
        let mut body_status = ExitCode::SUCCESS;
        loop {
            // Every iteration charges a step. This is the only thing standing between
            // `while true; do :; done` and an unbounded loop.
            self.budget.charge_step()?;
            let (status, flow) = self.tested(true, |evaluator| {
                evaluator.execute_list(&statement.condition)
            })?;
            self.last_status = status;
            if let Some(flow) = flow {
                return Ok(flow);
            }
            let satisfied = if statement.until {
                status != ExitCode::SUCCESS
            } else {
                status == ExitCode::SUCCESS
            };
            if !satisfied {
                self.last_status = body_status;
                return Ok(Flow::Normal);
            }

            let flow = self.execute_program(&statement.body)?;
            body_status = self.last_status;
            match flow {
                Flow::Normal => {}
                Flow::Break(level) => {
                    self.last_status = body_status;
                    return Ok(unwind_break(level));
                }
                Flow::Continue(level) => {
                    if level > 1 {
                        self.last_status = body_status;
                        return Ok(Flow::Continue(level - 1));
                    }
                }
                terminal => return Ok(terminal),
            }
        }
    }

    fn execute_list(&mut self, list: &AndOrList) -> Result<(ExitCode, Option<Flow>), FatalError> {
        // Every operand of an `&&`/`||` chain but the last is a tested status: the chain is asking
        // whether it succeeded, so `errexit` must not answer by ending the script.
        let (mut status, flow) = self.tested(!list.rest.is_empty(), |evaluator| {
            evaluator.execute_pipeline(&list.first)
        })?;
        self.last_status = status;
        if flow.is_some() {
            return Ok((status, flow));
        }

        let last = list.rest.len().saturating_sub(1);
        for (index, (operator, pipeline)) in list.rest.iter().enumerate() {
            let should_run = match operator {
                AndOr::And => status == ExitCode::SUCCESS,
                AndOr::Or => status != ExitCode::SUCCESS,
            };
            if !should_run {
                continue;
            }
            let (next, flow) = self.tested(index < last, |evaluator| {
                evaluator.execute_pipeline(pipeline)
            })?;
            status = next;
            self.last_status = status;
            if flow.is_some() {
                return Ok((status, flow));
            }
        }
        if let Some(exit) = self.errexit_trip(status) {
            return Ok((status, Some(exit)));
        }
        Ok((status, None))
    }

    /// `read [-r] NAME...`: takes one line of input and binds it.
    ///
    /// This is what makes `cmd | while read line; do ...; done` terminate. Input is *consumed*
    /// here, unlike every other way of looking at it: `cat` is offered the whole value on each
    /// pipeline in the body so a condition cannot swallow it, while `read` advances a cursor and
    /// reports failure at end of input, which is what ends the loop.
    ///
    /// A value that reached this command through a pipe is its own one-shot source; one inherited
    /// from an enclosing call or compound stage is read through that stage's shared cursor, so
    /// successive `read`s in a loop body see successive lines.
    fn run_read(
        &mut self,
        arguments: &[String],
        input: Option<Rc<Value>>,
        from_pipe: bool,
    ) -> Result<CommandResult, CommandFailure> {
        let mut names = arguments;
        // `-r` is the only flag, and it is what every correct script already passes. Backslashes
        // are never line continuations here, so it is accepted and changes nothing — said out loud
        // rather than left as a surprise.
        if names.first().is_some_and(|first| first == "-r") {
            names = &names[1..];
        }
        if let Some(flag) = names.first().filter(|first| first.starts_with('-')) {
            return Err(CommandFailure::usage(format!(
                "read: option {flag:?} is not supported; this shell has only `read [-r] NAME...`"
            )));
        }
        if names.is_empty() {
            return Err(CommandFailure::usage(
                "read: needs at least one variable name to bind",
            ));
        }
        for name in names {
            if !is_variable_name(name) {
                return Err(CommandFailure::usage(format!(
                    "read: {name:?} is not a valid variable name"
                )));
            }
        }

        let line = if from_pipe {
            StdinSource::new(input).next_line()
        } else {
            self.stdin.last_mut().and_then(StdinSource::next_line)
        };
        let Some(line) = line else {
            // End of input is a *status*, not a diagnostic: it is the ordinary way a
            // `while read` loop ends, and a message per loop would be one per iteration.
            return Ok(CommandResult::status(ExitCode::FAILURE));
        };

        // Several names split the line on whitespace runs, with the remainder landing in the last,
        // exactly as bash does. This is a rule local to `read` rather than a return of IFS word
        // splitting: there is no `IFS` here to configure, and nothing else splits.
        let fields = split_read_fields(&line, names.len());
        for (index, name) in names.iter().enumerate() {
            let field = fields.get(index).copied().unwrap_or_default();
            self.assign(name, Value::String(field.to_owned()))?;
        }
        Ok(CommandResult::status(ExitCode::SUCCESS))
    }

    /// Applies one `set` invocation.
    ///
    /// Only the three options this shell actually enforces are accepted. Every other letter and
    /// long name **ends the script** by name rather than being ignored: an accepted-and-ignored
    /// option is the exact failure that kept `set` out of this shell in the first place, and a
    /// refusal the script could carry on past would leave it running without the option it asked
    /// for, which is the same failure wearing a status code.
    fn apply_set_options(&mut self, arguments: &[String]) -> Result<(), CommandFailure> {
        if arguments.is_empty() {
            return Err(unsupported_option(
                "set: listing or setting positional parameters is not supported; \
                 use `set -e`, `set -u`, `set -o pipefail`, or their `+` forms",
            ));
        }
        let mut index = 0;
        while index < arguments.len() {
            let argument = arguments[index].as_str();
            let enable = match argument.chars().next() {
                Some('-') => true,
                Some('+') => false,
                _ => {
                    return Err(unsupported_option(format!(
                        "set: {argument:?} is not an option; this shell supports only -e, -u, and \
                         -o pipefail"
                    )));
                }
            };
            if argument.len() == 1 {
                return Err(unsupported_option(format!(
                    "set: {argument:?} on its own is not an option"
                )));
            }
            if argument == "--" || argument == "++" {
                return Err(unsupported_option(
                    "set: `--` sets positional parameters, which this shell has only inside a \
                     function and only from its arguments",
                ));
            }
            index += 1;
            for letter in argument.chars().skip(1) {
                match letter {
                    'e' => self.options.errexit = enable,
                    'u' => self.options.nounset = enable,
                    'o' => {
                        let Some(name) = arguments.get(index) else {
                            return Err(unsupported_option(
                                "set: -o needs an option name; the only one is `pipefail`",
                            ));
                        };
                        index += 1;
                        self.set_long_option(name, enable)?;
                    }
                    other => {
                        return Err(unsupported_option(format!(
                            "set: option -{other} is not supported; this shell has -e, -u, and \
                             -o pipefail"
                        )));
                    }
                }
            }
        }
        Ok(())
    }

    /// Applies one `set -o NAME` / `set +o NAME`.
    fn set_long_option(&mut self, name: &str, enable: bool) -> Result<(), CommandFailure> {
        match name {
            "pipefail" => self.options.pipefail = enable,
            "errexit" => self.options.errexit = enable,
            "nounset" => self.options.nounset = enable,
            other => {
                return Err(unsupported_option(format!(
                    "set: -o {other} is not supported; this shell has pipefail, errexit, and nounset"
                )));
            }
        }
        Ok(())
    }

    /// Publishes one pipeline's per-stage statuses as `PIPESTATUS`.
    ///
    /// An ordinary global, so `${PIPESTATUS[@]}`, `${PIPESTATUS[0]}`, and `${#PIPESTATUS[@]}` all
    /// work through the expansion machinery that already exists rather than through a special case.
    /// Written straight into the map instead of through [`Evaluator::assign`] because it *replaces*
    /// a bounded array of small integers on every pipeline rather than accumulating one; charging
    /// it against the value-byte ceiling would let a long loop exhaust that ceiling with a value
    /// the script never asked for.
    fn record_pipe_statuses(&mut self, stages: Vec<ExitCode>) {
        self.globals.insert(
            "PIPESTATUS".to_owned(),
            Value::Array(
                stages
                    .into_iter()
                    .map(|stage| Value::from(stage.get()))
                    .collect(),
            ),
        );
    }

    /// Runs `body` with `errexit` suspended when `suspended`, restoring the count afterwards.
    fn tested<T>(
        &mut self,
        suspended: bool,
        body: impl FnOnce(&mut Self) -> Result<T, FatalError>,
    ) -> Result<T, FatalError> {
        if suspended {
            self.testing_status += 1;
        }
        let outcome = body(self);
        if suspended {
            self.testing_status -= 1;
        }
        outcome
    }

    /// Reports the exit `errexit` demands for this status, if any.
    fn errexit_trip(&mut self, status: ExitCode) -> Option<Flow> {
        if !self.options.errexit || self.testing_status > 0 || status == ExitCode::SUCCESS {
            return None;
        }
        self.write_line(&format!(
            "dekopon-shell: command failed with status {status} and `set -e` is on"
        ));
        Some(Flow::Exit(status))
    }

    fn execute_pipeline(
        &mut self,
        pipeline: &Pipeline,
    ) -> Result<(ExitCode, Option<Flow>), FatalError> {
        self.budget.charge_step()?;
        // A function body inherits the value piped into the call, offered to the first command of
        // each pipeline in the body. It is shared rather than consumed: consuming it would let a
        // condition that never reads input (`if [ -n "$1" ]; then cat; fi`) swallow the value
        // before `cat` could see it, which is the same class of silent data loss as dropping it.
        let mut input: Option<Rc<Value>> =
            self.stdin.last().and_then(|source| source.value.clone());
        let mut last = CommandResult::status(ExitCode::SUCCESS);
        let commands = pipeline.commands.len();
        let mut stages = Vec::with_capacity(commands);

        for (index, command) in pipeline.commands.iter().enumerate() {
            let piped = index + 1 < commands;
            // Only a later stage's input actually came out of a pipe. The first stage's came from
            // the enclosing call or compound stage, and `read` has to consume *that* through the
            // shared cursor rather than through a private copy, or `while read line` would see the
            // first line forever.
            let from_pipe = index > 0;
            // A `!` makes the whole pipeline a tested status, and every stage but the last is one
            // anyway: bash exempts both from `errexit`, and so does this.
            match self.tested(pipeline.negated || piped, |evaluator| {
                evaluator.execute_command(command, input.take(), piped, from_pipe)
            })? {
                Executed::Flow(flow) => return Ok((self.last_status, Some(flow))),
                Executed::Result(result) => {
                    stages.push(result.status);
                    if piped {
                        // Only the terminal command's result is ever read, and the terminal
                        // command is by construction never piped — so an intermediate value moves
                        // into the next stage instead of being copied into it and then dropped.
                        // Without this `gh issue list | jq . | grep x` deep-copies the payload per
                        // stage.
                        last = CommandResult::status(result.status);
                        input = Some(Rc::new(result.value));
                    } else {
                        last = result;
                    }
                }
            }
        }

        // `pipefail` reports the rightmost stage that failed, so `gh issue view 12 | jq .` stops
        // hiding a capability that never ran behind a `jq` that was handed nothing and succeeded.
        let mut status = last.status;
        if self.options.pipefail
            && let Some(failed) = stages
                .iter()
                .rev()
                .find(|stage| **stage != ExitCode::SUCCESS)
        {
            status = *failed;
        }
        self.record_pipe_statuses(stages);
        if pipeline.negated {
            status = invert(status);
        }
        self.emit(last);
        Ok((status, None))
    }

    // -----------------------------------------------------------------------
    // Commands
    // -----------------------------------------------------------------------

    /// Runs one pipeline stage.
    fn execute_command(
        &mut self,
        command: &Command,
        input: Option<Rc<Value>>,
        capture_output: bool,
        from_pipe: bool,
    ) -> Result<Executed, FatalError> {
        match command {
            Command::Simple(command) => {
                self.execute_simple_command(command, input, capture_output, from_pipe)
            }
            Command::Compound {
                statement,
                redirects,
            } => self.execute_compound_command(statement, redirects, input, capture_output),
        }
    }

    /// Runs a compound statement as one pipeline stage.
    ///
    /// The stage's emissions are collected into one value whenever anything downstream will read
    /// them — a later pipe, a redirection, an enclosing `$( )`. Each statement inside emits
    /// separately, so without that `{ echo a; echo b; } | wc -l` would hand `wc` only the last one.
    fn execute_compound_command(
        &mut self,
        statement: &Statement,
        redirects: &[Redirect],
        input: Option<Rc<Value>>,
        capture_output: bool,
    ) -> Result<Executed, FatalError> {
        let (stdout, stderr) = match self.resolve_redirects(redirects) {
            Ok(sinks) => sinks,
            Err(failure) => {
                let status = self.absorb(failure)?;
                return Ok(Executed::Result(CommandResult::status(status)));
            }
        };
        let collect = capture_output || stdout != Sink::Value;

        let capturing = stderr != Sink::Diagnostics;
        if capturing {
            self.stderr_capture.push(StderrCapture::new(&self.limits));
        }
        self.stdin.push(StdinSource::new(input));
        if collect {
            self.captures.push(Vec::new());
        }

        let flow = self.execute_statement(statement);

        let captured = if collect {
            self.captures.pop().unwrap_or_default()
        } else {
            Vec::new()
        };
        self.stdin.pop();
        let mut diagnostics = capturing
            .then(|| self.stderr_capture.pop())
            .flatten()
            .map(StderrCapture::finish)
            .unwrap_or_default();

        let flow = flow?;
        let value = if collect {
            reduce_captured(captured)
        } else {
            Value::Null
        };
        let status = match flow {
            Flow::Normal => self.last_status,
            _ => {
                self.route_diagnostics(diagnostics, &stderr)?;
                return Ok(Executed::Flow(flow));
            }
        };

        let mut result = CommandResult {
            value,
            status,
            suppress_newline: false,
        };
        if stderr == Sink::Value {
            result.value = merge_diagnostics(result.value, diagnostics);
            diagnostics = Vec::new();
        }
        self.open_buffers(&[&stdout, &stderr]);
        self.route_diagnostics(diagnostics, &stderr)?;

        match stdout {
            Sink::Value => Ok(Executed::Result(result)),
            Sink::Discard => Ok(Executed::Result(CommandResult::status(result.status))),
            Sink::Diagnostics => {
                if !result.value.is_null() {
                    let text = display(&result.value);
                    self.write_line(&text);
                }
                Ok(Executed::Result(CommandResult::status(result.status)))
            }
            Sink::Buffer { name, .. } => {
                self.append_buffer(&name, result.value)?;
                Ok(Executed::Result(CommandResult::status(result.status)))
            }
        }
    }

    fn execute_simple_command(
        &mut self,
        command: &SimpleCommand,
        input: Option<Rc<Value>>,
        capture_output: bool,
        from_pipe: bool,
    ) -> Result<Executed, FatalError> {
        self.budget.charge_step()?;

        // Command words are expanded *before* any prefix assignment is applied, so `x=new echo $x`
        // prints the old value, and the binding is restored afterwards so it does not leak into the
        // rest of the script. Both halves are what `DEBUG=1 some-command` means in bash.
        let mut argv = Vec::new();
        for word in &command.words {
            match self.expand_word(word) {
                Ok(expanded) => argv.extend(expanded),
                Err(failure) => {
                    let status = self.absorb(failure)?;
                    return Ok(Executed::Result(CommandResult::status(status)));
                }
            }
        }

        let transient = !argv.is_empty();
        let mut restore = Vec::new();
        let mut assignment_status = ExitCode::SUCCESS;
        for assignment in &command.assignments {
            let value = match self.assignment_value(&assignment.value) {
                Ok(value) => value,
                Err(failure) => {
                    self.restore_all(restore);
                    let status = self.absorb(failure)?;
                    return Ok(Executed::Result(CommandResult::status(status)));
                }
            };
            assignment_status = self.last_substitution_status;
            if transient {
                restore.push((
                    assignment.name.clone(),
                    self.lookup(&assignment.name).cloned(),
                ));
            }
            if let Err(limit) = self.assign(&assignment.name, value) {
                self.restore_all(restore);
                return Err(limit.into());
            }
        }

        if argv.is_empty() {
            // An assignment-only command reports the status of its last command substitution,
            // so `x=$(false); echo $?` behaves the way bash trains a model to expect.
            let status = if command.assignments.is_empty() {
                ExitCode::SUCCESS
            } else {
                assignment_status
            };
            return Ok(Executed::Result(CommandResult::status(status)));
        }

        // A here-document supplies this command's input in place of anything piped into it: `<<EOF`
        // redirects the same stdin a pipe would have filled, and the redirection is what bash
        // applies last. The body arrives as one JSON string, because a block of literal text is
        // exactly what a string is in this value model — no byte stream is involved anywhere here,
        // so a command that wants structure still pipes the body through `jq`.
        let input = match &command.here_doc {
            None => input,
            Some(body) => match self.expand_quoted(&body.parts) {
                Ok(text) => {
                    let value = Value::String(text);
                    if let Err(limit) = self.budget.charge_value_bytes(value_bytes(&value)) {
                        self.restore_all(restore);
                        return Err(limit.into());
                    }
                    Some(Rc::new(value))
                }
                Err(failure) => {
                    self.restore_all(restore);
                    let status = self.absorb(failure)?;
                    return Ok(Executed::Result(CommandResult::status(status)));
                }
            },
        };

        // Redirections are resolved *before* the command runs, the way bash resolves them, because
        // a redirected stderr has to be in place while the command is producing diagnostics rather
        // than applied to a value afterwards.
        let (stdout, stderr) = match self.resolve_redirects(&command.redirects) {
            Ok(sinks) => sinks,
            Err(failure) => {
                self.restore_all(restore);
                let status = self.absorb(failure)?;
                return Ok(Executed::Result(CommandResult::status(status)));
            }
        };

        let capturing = stderr != Sink::Diagnostics;
        if capturing {
            self.stderr_capture.push(StderrCapture::new(&self.limits));
        }
        let executed = self.run_argv(&argv, input, capture_output, from_pipe);
        // Popped before the `?` below: a fatal error must not leave a capture installed for the
        // rest of the script, silently swallowing every later diagnostic.
        let mut diagnostics = capturing
            .then(|| self.stderr_capture.pop())
            .flatten()
            .map(StderrCapture::finish)
            .unwrap_or_default();
        self.restore_all(restore);
        let executed = executed?;
        let Executed::Result(mut result) = executed else {
            self.route_diagnostics(diagnostics, &stderr)?;
            return Ok(executed);
        };

        if stderr == Sink::Value {
            result.value = merge_diagnostics(result.value, diagnostics);
            diagnostics = Vec::new();
        }

        // Truncation belongs to the redirection, not to each write, exactly as a real shell
        // truncates once when it opens the file. Without this, `cmd > out 2>&1` would write the
        // diagnostics and then have the value overwrite them, or the reverse depending on order.
        self.open_buffers(&[&stdout, &stderr]);
        self.route_diagnostics(diagnostics, &stderr)?;

        match stdout {
            Sink::Value => Ok(Executed::Result(result)),
            Sink::Discard => Ok(Executed::Result(CommandResult::status(result.status))),
            Sink::Diagnostics => {
                if !result.value.is_null() {
                    let text = display(&result.value);
                    self.write_line(&text);
                }
                Ok(Executed::Result(CommandResult::status(result.status)))
            }
            Sink::Buffer { name, .. } => {
                self.append_buffer(&name, result.value)?;
                Ok(Executed::Result(CommandResult::status(result.status)))
            }
        }
    }

    /// Truncates every buffer a non-appending redirection names, once, before anything is written.
    ///
    /// A truncated buffer is left holding `null` rather than removed, so `cmd > out` makes `out`
    /// exist and readable even when the command produced nothing — the way redirecting into a file
    /// creates an empty one.
    fn open_buffers(&mut self, sinks: &[&Sink]) {
        for sink in sinks {
            if let Sink::Buffer {
                name,
                append: false,
            } = sink
            {
                self.buffers.insert(name.clone(), Value::Null);
            }
        }
    }

    /// Resolves a command's redirections into one destination per stream.
    ///
    /// Walked left to right so a duplication copies the sink its target holds *at that point*,
    /// which is how a real shell's `dup2` behaves. The parser refuses the one ordering where that
    /// distinction is invisible and wrong — a duplication whose target is redirected afterwards.
    fn resolve_redirects(
        &mut self,
        redirects: &[Redirect],
    ) -> Result<(Sink, Sink), CommandFailure> {
        let mut stdout = Sink::Value;
        let mut stderr = Sink::Diagnostics;
        for redirect in redirects {
            let sink = match &redirect.target {
                RedirectTarget::Stream(Stream::Stdout) => stdout.clone(),
                RedirectTarget::Stream(Stream::Stderr) => stderr.clone(),
                RedirectTarget::Stream(Stream::Both) => {
                    unreachable!("the lexer never produces `&` as a duplication target")
                }
                RedirectTarget::Buffer { append, target } => {
                    let expanded = self.expand_word(target)?;
                    let [name] = expanded.as_slice() else {
                        return Err(CommandFailure::usage(
                            "dekopon-shell: a redirection target must expand to exactly one buffer name",
                        ));
                    };
                    if name == DEV_NULL {
                        Sink::Discard
                    } else {
                        Sink::Buffer {
                            name: name.clone(),
                            append: *append,
                        }
                    }
                }
            };
            match redirect.source {
                Stream::Stdout => stdout = sink,
                Stream::Stderr => stderr = sink,
                Stream::Both => {
                    stdout = sink.clone();
                    stderr = sink;
                }
            }
        }
        Ok((stdout, stderr))
    }

    /// Sends one command's collected diagnostics to their redirected destination.
    fn route_diagnostics(
        &mut self,
        diagnostics: Vec<String>,
        sink: &Sink,
    ) -> Result<(), FatalError> {
        if diagnostics.is_empty() {
            return Ok(());
        }
        match sink {
            Sink::Discard => {}
            Sink::Diagnostics | Sink::Value => {
                // `Value` reaches here only for a command that produced no result to merge into,
                // which is a flow word; its diagnostics still belong somewhere visible.
                for line in diagnostics {
                    self.write_line(&line);
                }
            }
            Sink::Buffer { name, .. } => {
                let name = name.clone();
                self.append_buffer(&name, value::from_lines(diagnostics))?;
            }
        }
        Ok(())
    }

    /// Restores every binding a transient prefix assignment shadowed, in reverse order.
    fn restore_all(&mut self, restore: Vec<(String, Option<Value>)>) {
        for (name, previous) in restore.into_iter().rev() {
            self.restore(&name, previous);
        }
    }

    /// Adds one value to the named in-memory buffer store, folding repeats into an array.
    fn append_buffer(&mut self, name: &str, value: Value) -> Result<(), LimitExceeded> {
        // A command that produced nothing writes nothing, matching `emit`. Otherwise
        // `nosuchcmd > out 2>&1` would leave a stray `null` sitting in front of the one line that
        // explains what happened.
        if value.is_null() {
            return Ok(());
        }
        self.budget.charge_value_bytes(value_bytes(&value))?;
        match self.buffers.remove(name) {
            // `null` is what an opened-and-truncated buffer holds, so it reads as empty rather
            // than as a first element.
            None | Some(Value::Null) => {
                self.buffers.insert(name.to_owned(), value);
            }
            Some(Value::Array(mut existing)) => {
                existing.push(value);
                self.buffers.insert(name.to_owned(), Value::Array(existing));
            }
            Some(existing) => {
                self.buffers
                    .insert(name.to_owned(), Value::Array(vec![existing, value]));
            }
        }
        Ok(())
    }

    /// Executes one command word, wrapped in the span every command in a script produces.
    ///
    /// This is the single place a command word actually runs, so it is the single place worth
    /// instrumenting: one span here covers builtins, provider command words, shell functions,
    /// refused words, and unknown words alike, and covers builtins added later without another
    /// edit. The recursion `xargs` drives back into this function is deliberately *not*
    /// special-cased — one script word that maps a command over ten items really did run ten
    /// commands, and each of them gets its own span nested inside the `xargs` one, which is
    /// exactly the syscall-by-syscall reading this instrumentation exists to give.
    ///
    /// See [`telemetry`] for what these spans carry.
    fn run_argv(
        &mut self,
        argv: &[String],
        input: Option<Rc<Value>>,
        capture_output: bool,
        from_pipe: bool,
    ) -> Result<Executed, FatalError> {
        let command = argv[0].as_str();
        let arguments = &argv[1..];

        // Classification happens before execution so that the span and its opening event both
        // carry the resolution kind, and so a command that aborts the script is still described by
        // more than "something failed".
        let (kind, resolution) = if telemetry::is_control_word(command) {
            (CommandKind::Control, None)
        } else {
            let resolution = dispatch::resolve(command, &self.function_names, self.invoker);
            (CommandKind::of(&resolution), Some(resolution))
        };
        self.counters.charge(kind);
        let span = telemetry::command_span(command, kind, arguments.len());
        let _entered = span.enter();
        // The payload attributes cost a serialization each, so they are built only for a span
        // something will record.
        let traced = !span.is_disabled();
        if traced {
            telemetry::record_arguments(&span, arguments);
            if let Some(piped) = input.as_deref() {
                telemetry::record_stdin(&span, piped);
            }
        }

        let executed = self.dispatch_command(
            command,
            arguments,
            resolution,
            input,
            capture_output,
            from_pipe,
        );
        let (status, outcome) = match &executed {
            Ok(Executed::Result(result)) => {
                (result.status, telemetry::outcome_label(result.status))
            }
            // `break`, `return 1`, and `exit 3` are commands that succeeded at doing what they
            // were asked; the status they carry belongs to the script, and is reported as theirs.
            Ok(Executed::Flow(flow)) => {
                let status = match flow {
                    Flow::Return(status) | Flow::Exit(status) => *status,
                    Flow::Normal | Flow::Break(_) | Flow::Continue(_) => ExitCode::SUCCESS,
                };
                (status, telemetry::outcome_label(status))
            }
            Err(fatal) => (
                telemetry::fatal_exit_code(fatal),
                telemetry::fatal_outcome(fatal),
            ),
        };
        span.record("shell.command.exit_code", status.get());
        span.record("outcome", outcome);
        if traced && let Ok(Executed::Result(result)) = &executed {
            telemetry::record_output(&span, &result.value);
        }
        self.counters.record_status(status);
        executed
    }

    /// Runs one already-classified command word.
    fn dispatch_command(
        &mut self,
        command: &str,
        arguments: &[String],
        resolution: Option<Resolution>,
        input: Option<Rc<Value>>,
        capture_output: bool,
        from_pipe: bool,
    ) -> Result<Executed, FatalError> {
        let Some(resolution) = resolution else {
            if let Some(executed) = self.run_control_word(command, arguments, input, from_pipe)? {
                return Ok(executed);
            }
            // Unreachable while [`telemetry::CONTROL_WORDS`] and `run_control_word` agree, which
            // `control_words_and_their_dispatcher_agree` pins. Reporting "command not found" is
            // what a word added to only one of the two should do: fail closed and visibly, rather
            // than silently succeed with no effect.
            self.write_line(&format!("dekopon-shell: {command}: command not found"));
            return Ok(Executed::Result(CommandResult::status(ExitCode::NOT_FOUND)));
        };

        match resolution {
            Resolution::Rejected(reason) => Err(FatalError::Unsupported(reason.to_owned())),
            Resolution::Function => self.call_function(command, arguments, input, capture_output),
            Resolution::Builtin(BuiltinKind::Simple(builtin)) => {
                let outcome = {
                    let mut context = BuiltinContext {
                        invoker: self.invoker,
                        budget: &mut self.budget,
                        buffers: &mut self.buffers,
                    };
                    // The one place a piped value has to become owned. A pipeline stage's own
                    // output is held by nobody else and moves straight through; a function frame's
                    // stdin is shared with the frame, so only that case copies — and only for the
                    // commands that actually reach for input.
                    builtin.run(&mut context, arguments, own(input))
                };
                match outcome {
                    Ok(result) => Ok(Executed::Result(result)),
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        Ok(Executed::Result(CommandResult::status(status)))
                    }
                }
            }
            Resolution::Builtin(BuiltinKind::Xargs) => self.run_xargs(arguments, input),
            // The provider runs its own argv like a small command-line program. A proposal it
            // makes is charged, authorized, and traced like every capability call, and any secret
            // reference it names travels with it to the invoker. Running the word proposes; it
            // does not grant.
            Resolution::ProviderCommand => {
                // Encoded once, with the rule every emitted value follows — strings verbatim,
                // everything else as compact JSON — so a provider reads `echo hello | word -` and
                // `jq -n '{a:1}' | word -` exactly as the script would have printed them.
                let stdin = input.as_deref().map(display);
                // A guest run costs wall clock the same way a capability call does, and for the
                // same reason `invoke_capability_with_secret_use` re-reads the clock around one.
                self.budget.check_deadline()?;
                let run = self
                    .invoker
                    .run_command(command, arguments, stdin.as_deref());
                self.budget.check_deadline()?;
                let (capability, input, secret_use) = match run {
                    Some(CommandRun::Proposed {
                        capability,
                        input,
                        secret_use,
                    }) => (capability, input, secret_use),
                    Some(CommandRun::Failed { message }) => {
                        let status = self.absorb(CommandFailure::usage(message))?;
                        return Ok(Executed::Result(CommandResult::status(status)));
                    }
                    // Neither a proposal nor the provider's own answer: the same two shapes a
                    // capability call ends in when it errors or is refused, so the model reads
                    // them the same way — retry later, or stop — rather than as a bad argv.
                    Some(CommandRun::Errored { message }) => {
                        let status = self.absorb(CommandFailure::failed(format!(
                            "{command}: failed: {message}"
                        )))?;
                        return Ok(Executed::Result(CommandResult::status(status)));
                    }
                    Some(CommandRun::Denied { reason }) => {
                        let status = self.absorb(CommandFailure::Status {
                            message: format!("{command}: denied: {reason}"),
                            status: ExitCode::DENIED,
                        })?;
                        return Ok(Executed::Result(CommandResult::status(status)));
                    }
                    Some(CommandRun::Rendered {
                        stdout,
                        stderr,
                        status,
                    }) => return self.emit_rendered(stdout, stderr, status),
                    // Resolution said a provider owned this word, so nothing owning it now means
                    // the registry changed underneath the session. Fail closed and visibly.
                    None => {
                        self.write_line(&format!("dekopon-shell: {command}: command not found"));
                        return Ok(Executed::Result(CommandResult::status(ExitCode::NOT_FOUND)));
                    }
                };
                // The provider proposes a capability without knowing what this session was
                // granted — it holds no session state and could not consult a grant if it wanted
                // to. Naming the missing capability here is what keeps "not configured" from
                // reading as "does not exist", which is the message the `gh` builtin used to give
                // before this layer moved into the component.
                if !self.invoker.is_granted(&capability) {
                    self.write_line(&format!(
                        "dekopon-shell: {command}: requires capability {capability}, which is not \
                         granted in this session"
                    ));
                    return Ok(Executed::Result(CommandResult::status(ExitCode::NOT_FOUND)));
                }
                let outcome = {
                    let mut context = BuiltinContext {
                        invoker: self.invoker,
                        budget: &mut self.budget,
                        buffers: &mut self.buffers,
                    };
                    context.invoke_capability_with_secret_use(&capability, input, secret_use)
                };
                match outcome {
                    Ok(result) => Ok(Executed::Result(result)),
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        Ok(Executed::Result(CommandResult::status(status)))
                    }
                }
            }
            Resolution::NotFound => {
                self.write_line(&format!("dekopon-shell: {command}: command not found"));
                Ok(Executed::Result(CommandResult::status(ExitCode::NOT_FOUND)))
            }
        }
    }

    /// Handles the control words the evaluator owns rather than the builtin table.
    fn run_control_word(
        &mut self,
        command: &str,
        arguments: &[String],
        input: Option<Rc<Value>>,
        from_pipe: bool,
    ) -> Result<Option<Executed>, FatalError> {
        let executed = match command {
            "break" | "continue" => {
                let level = match parse_level(command, arguments) {
                    Ok(level) => level,
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        return Ok(Some(Executed::Result(CommandResult::status(status))));
                    }
                };
                Executed::Flow(if command == "break" {
                    Flow::Break(level)
                } else {
                    Flow::Continue(level)
                })
            }
            "set" => match self.apply_set_options(arguments) {
                Ok(()) => Executed::Result(CommandResult::status(ExitCode::SUCCESS)),
                Err(failure) => {
                    let status = self.absorb(failure)?;
                    Executed::Result(CommandResult::status(status))
                }
            },
            "return" => {
                if self.frames.is_empty() {
                    self.write_line("dekopon-shell: return: only valid inside a function");
                    return Ok(Some(Executed::Result(CommandResult::status(
                        ExitCode::SYNTAX,
                    ))));
                }
                let status = match parse_status(command, arguments, self.last_status) {
                    Ok(status) => status,
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        return Ok(Some(Executed::Result(CommandResult::status(status))));
                    }
                };
                Executed::Flow(Flow::Return(status))
            }
            "exit" => {
                let status = match parse_status(command, arguments, self.last_status) {
                    Ok(status) => status,
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        return Ok(Some(Executed::Result(CommandResult::status(status))));
                    }
                };
                Executed::Flow(Flow::Exit(status))
            }
            "read" => match self.run_read(arguments, input, from_pipe) {
                Ok(result) => Executed::Result(result),
                Err(failure) => {
                    let status = self.absorb(failure)?;
                    Executed::Result(CommandResult::status(status))
                }
            },
            "local" => {
                if self.frames.is_empty() {
                    self.write_line("dekopon-shell: local: only valid inside a function");
                    return Ok(Some(Executed::Result(CommandResult::status(
                        ExitCode::SYNTAX,
                    ))));
                }
                for argument in arguments {
                    match argument.split_once('=') {
                        Some((name, text)) => {
                            self.declare_local(name, value::scalar_from_token(text))?;
                        }
                        None => self.declare_local(argument, Value::String(String::new()))?,
                    }
                }
                Executed::Result(CommandResult::status(ExitCode::SUCCESS))
            }
            // `shift` belongs beside `local`: this shell already models `$1`, `$@`, and `$#`, so
            // its absence broke `while [ $# -gt 0 ]; do ...; shift; done` while looking fine.
            "shift" => {
                let Some(frame) = self.frames.last_mut() else {
                    self.write_line("dekopon-shell: shift: only valid inside a function");
                    return Ok(Some(Executed::Result(CommandResult::status(
                        ExitCode::SYNTAX,
                    ))));
                };
                let count = match parse_shift_count(arguments) {
                    Ok(count) => count,
                    Err(failure) => {
                        let status = self.absorb(failure)?;
                        return Ok(Some(Executed::Result(CommandResult::status(status))));
                    }
                };
                if count > frame.positional.len() {
                    // Shifting past the end is a failed `shift` in bash, not a truncation.
                    Executed::Result(CommandResult::status(ExitCode::FAILURE))
                } else {
                    frame.positional.drain(..count);
                    Executed::Result(CommandResult::status(ExitCode::SUCCESS))
                }
            }
            "unset" => {
                for name in arguments {
                    self.globals.remove(name);
                    for frame in &mut self.frames {
                        frame.locals.remove(name);
                    }
                }
                Executed::Result(CommandResult::status(ExitCode::SUCCESS))
            }
            ":" => Executed::Result(CommandResult::status(ExitCode::SUCCESS)),
            _ => return Ok(None),
        };
        Ok(Some(executed))
    }

    /// Calls one shell function.
    ///
    /// `input` is the value piped into the call, and `capture_output` says whether the caller
    /// consumes what the function produced. Both matter: without them a function is silently
    /// broken in a pipeline, leaking its output past the pipe and handing the next command a null.
    /// Output is captured only when it is consumed, so a function in terminal position keeps
    /// streaming into the bounded output buffer rather than accumulating in memory.
    fn call_function(
        &mut self,
        name: &str,
        arguments: &[String],
        input: Option<Rc<Value>>,
        capture_output: bool,
    ) -> Result<Executed, FatalError> {
        let Some(body) = self.functions.get(name).cloned() else {
            self.write_line(&format!("dekopon-shell: {name}: command not found"));
            return Ok(Executed::Result(CommandResult::status(ExitCode::NOT_FOUND)));
        };

        self.budget.charge_step()?;
        self.budget.enter_call()?;
        let positional = arguments
            .iter()
            .map(|argument| Value::String(argument.clone()))
            .collect::<Vec<_>>();
        for argument in &positional {
            self.budget.charge_value_bytes(value_bytes(argument))?;
        }
        self.frames.push(Frame {
            locals: BTreeMap::new(),
            positional,
        });
        self.stdin.push(StdinSource::new(input));
        if capture_output {
            self.captures.push(Vec::new());
        }

        let flow = self.execute_program(&body);
        let captured = if capture_output {
            self.captures.pop().unwrap_or_default()
        } else {
            Vec::new()
        };
        self.stdin.pop();
        self.frames.pop();
        self.budget.leave_call();

        let value = if capture_output {
            reduce_captured(captured)
        } else {
            Value::Null
        };
        Ok(match flow? {
            Flow::Return(status) => Executed::Result(CommandResult {
                value,
                status,
                suppress_newline: false,
            }),
            Flow::Exit(status) => Executed::Flow(Flow::Exit(status)),
            // `break`/`continue` that escape a function body do not unwind the caller's loop;
            // bash treats them as spent, and so does this evaluator.
            Flow::Normal | Flow::Break(_) | Flow::Continue(_) => Executed::Result(CommandResult {
                value,
                status: self.last_status,
                suppress_newline: false,
            }),
        })
    }

    fn run_xargs(
        &mut self,
        arguments: &[String],
        input: Option<Rc<Value>>,
    ) -> Result<Executed, FatalError> {
        let plan = match xargs::plan(arguments, input.as_deref()) {
            Ok(plan) => plan,
            Err(failure) => {
                let status = self.absorb(failure)?;
                return Ok(Executed::Result(CommandResult::status(status)));
            }
        };

        let mut outputs = Vec::new();
        let mut status = ExitCode::SUCCESS;
        for invocation in plan.invocations {
            self.budget.charge_step()?;
            match self.run_argv(&invocation, None, true, false)? {
                Executed::Flow(flow) => return Ok(Executed::Flow(flow)),
                Executed::Result(result) => {
                    if result.status != ExitCode::SUCCESS {
                        status = result.status;
                    }
                    if !result.value.is_null() {
                        outputs.push(result.value);
                    }
                }
            }
        }

        // Nothing produced is nothing emitted; an empty `[]` would be a phantom line of output.
        let value = if outputs.is_empty() {
            Value::Null
        } else {
            Value::Array(outputs)
        };
        Ok(Executed::Result(CommandResult {
            value,
            status,
            suppress_newline: false,
        }))
    }

    // -----------------------------------------------------------------------
    // Expansion
    // -----------------------------------------------------------------------

    /// Evaluates an assignment right-hand side.
    ///
    /// A whole-RHS `$(cmd)` or `$NAME` keeps its structured value instead of collapsing to text.
    /// This is the documented deviation from bash that makes `issue=$(gh issue view 12)` followed
    /// by `${issue[title]}` work, and it has to cover both spellings or `copy=$issue` would
    /// silently flatten what `issue` holds.
    fn assignment_value(&mut self, word: &Word) -> Result<Value, CommandFailure> {
        self.last_substitution_status = ExitCode::SUCCESS;
        if word.parts.is_empty() {
            return Ok(Value::String(String::new()));
        }
        if let [part] = word.parts.as_slice() {
            match part {
                WordPart::CommandSubstitution(program) => {
                    let (value, status) = self.run_substitution(program)?;
                    self.last_substitution_status = status;
                    return Ok(value);
                }
                // A whole-RHS parameter expansion keeps its value for the same reason a whole-RHS
                // substitution does: `b=$a` followed by `${b[key]}` is asking about the object `a`
                // holds, and stringifying it here would answer about that object's JSON text.
                WordPart::Parameter(parameter) => return self.parameter_value(parameter),
                _ => {}
            }
        }
        let expanded = self.expand_word(word)?;
        Ok(Value::String(expanded.join(" ")))
    }

    /// Expands one word into zero or more argv words.
    fn expand_word(&mut self, word: &Word) -> Result<Vec<String>, CommandFailure> {
        let mut fields = vec![String::new()];
        let mut produced = false;

        for part in &word.parts {
            match part {
                WordPart::Literal(text) | WordPart::SingleQuoted(text) => {
                    append(&mut fields, text);
                    produced = true;
                }
                WordPart::DoubleQuoted(parts) => {
                    // `"$@"` is the one place double quotes produce more than one word. It is the
                    // most-trained idiom in shell (`for x in "$@"`), so it follows bash exactly
                    // rather than collapsing to a space-joined string; `"$*"` is the joined form.
                    let expanded = self.expand_quoted_fields(parts)?;
                    let mut expanded = expanded.into_iter();
                    if let Some(first) = expanded.next() {
                        append(&mut fields, &first);
                        produced = true;
                    }
                    for extra in expanded {
                        fields.push(extra);
                    }
                }
                WordPart::Arithmetic(expression) => {
                    let number = self.evaluate_arithmetic(expression)?;
                    append(&mut fields, &render_number(number));
                    produced = true;
                }
                WordPart::Parameter(parameter) => {
                    let value = self.parameter_value(parameter)?;
                    produced |= spread(&mut fields, &value);
                }
                WordPart::CommandSubstitution(program) => {
                    let (value, _) = self.run_substitution(program)?;
                    produced |= spread(&mut fields, &value);
                }
            }
        }

        // An unquoted expansion that produced nothing yields no argv word at all, so
        // `echo $undefined` passes zero arguments rather than one empty one.
        if !produced && fields.len() == 1 && fields[0].is_empty() {
            return Ok(Vec::new());
        }
        Ok(fields)
    }

    /// Expands the interior of a double-quoted string into exactly one field.
    fn expand_quoted(&mut self, parts: &[WordPart]) -> Result<String, CommandFailure> {
        Ok(self.expand_quoted_fields(parts)?.join(" "))
    }

    /// Expands the interior of a double-quoted string, splitting only where `"$@"` demands it.
    ///
    /// Every part appends to the current field. `"$@"` is the sole exception: each parameter after
    /// the first opens a new field, so `"$@"` yields one word per parameter, `"a$@b"` glues the
    /// literals onto the outer two, and zero parameters yield zero words.
    fn expand_quoted_fields(&mut self, parts: &[WordPart]) -> Result<Vec<String>, CommandFailure> {
        let mut fields = vec![String::new()];
        for part in parts {
            match part {
                WordPart::Literal(literal) | WordPart::SingleQuoted(literal) => {
                    append(&mut fields, literal);
                }
                WordPart::DoubleQuoted(inner) => {
                    let inner = self.expand_quoted(inner)?;
                    append(&mut fields, &inner);
                }
                WordPart::Arithmetic(expression) => {
                    let number = self.evaluate_arithmetic(expression)?;
                    append(&mut fields, &render_number(number));
                }
                WordPart::Parameter(parameter) if splits_inside_quotes(parameter) => {
                    let value = self.parameter_value(parameter)?;
                    let elements = match value {
                        Value::Array(items) => items,
                        Value::Null => Vec::new(),
                        scalar => vec![scalar],
                    };
                    let mut elements = elements.iter().map(display);
                    let Some(first) = elements.next() else {
                        // A bare `"$@"` with no parameters is no word at all, so `f "$@"` with
                        // nothing to forward calls `f` with zero arguments rather than one empty
                        // one. Glued to other text it contributes nothing instead.
                        if parts.len() == 1 {
                            return Ok(Vec::new());
                        }
                        continue;
                    };
                    append(&mut fields, &first);
                    fields.extend(elements);
                }
                WordPart::Parameter(parameter) => {
                    let value = self.parameter_value(parameter)?;
                    append(&mut fields, &quoted_text(&value));
                }
                WordPart::CommandSubstitution(program) => {
                    let (value, _) = self.run_substitution(program)?;
                    append(&mut fields, &quoted_text(&value));
                }
            }
        }
        Ok(fields)
    }

    fn parameter_value(&mut self, parameter: &Parameter) -> Result<Value, CommandFailure> {
        Ok(match parameter {
            Parameter::Named {
                name,
                indices,
                modifier,
                length,
            } => {
                let (value, bound) = self.select_parameter(name, indices)?;
                // `set -u` only governs a plain reference. `${x:-d}` and its relatives exist
                // precisely to handle an absent value, so tripping on them would make the option
                // refuse the idiom written to satisfy it.
                if self.options.nounset && !bound && *modifier == Modifier::None {
                    return Err(CommandFailure::Fatal(FatalError::Assertion(format!(
                        "{name}: unbound variable, and `set -u` is on"
                    ))));
                }
                let value = self.apply_modifier(name, indices, modifier, value, bound)?;
                if *length {
                    parameter_length(&value)
                } else {
                    value
                }
            }
            Parameter::Positional(0) => Value::String("dekopon-shell".to_owned()),
            Parameter::Positional(position) => self
                .positional()
                .get(position - 1)
                .cloned()
                .unwrap_or(Value::Null),
            Parameter::AllPositional => Value::Array(self.positional().to_vec()),
            // `$*` is the always-joined counterpart of `$@`: one word, whatever the quoting.
            Parameter::AllPositionalJoined => Value::String(
                self.positional()
                    .iter()
                    .map(display)
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            Parameter::PositionalCount => Value::from(self.positional().len()),
            Parameter::LastStatus => Value::from(self.last_status.get()),
        })
    }

    /// Walks a parameter's indices, reporting the selection and whether it was bound at all.
    ///
    /// "Bound" is what separates `${NAME-word}` from `${NAME:-word}`: the first substitutes only
    /// for a name nothing ever assigned, the second also for one holding an empty value.
    fn select_parameter(
        &mut self,
        name: &str,
        indices: &[Index],
    ) -> Result<(Value, bool), CommandFailure> {
        let mut bound = self.lookup(name).is_some();
        let mut value = self.lookup(name).cloned().unwrap_or(Value::Null);
        for index in indices {
            match index {
                Index::At(word) => {
                    let expanded = self.expand_word(word)?;
                    let key = expanded.join(" ");
                    value = value::index(&value, &key);
                    bound = !value.is_null();
                }
                // `[@]` and `[*]` select the whole thing; what differs is how the *word* they sit
                // in splits, which `expand_word` and `expand_quoted_fields` decide.
                Index::All => {}
                Index::AllJoined => {
                    value = Value::String(value::to_lines(&value).join(" "));
                }
            }
        }
        Ok((value, bound))
    }

    /// Applies one `${NAME<op>word}` transformation.
    fn apply_modifier(
        &mut self,
        name: &str,
        indices: &[Index],
        modifier: &Modifier,
        value: Value,
        bound: bool,
    ) -> Result<Value, CommandFailure> {
        // `:` widens "absent" from "never assigned" to "assigned nothing useful", which is the
        // distinction bash draws and the one a script almost always wants.
        let absent = |colon: bool| {
            if colon {
                value.is_null() || display(&value).is_empty()
            } else {
                !bound
            }
        };
        Ok(match modifier {
            Modifier::None => value,
            Modifier::Default { colon, word } => {
                if absent(*colon) {
                    self.assignment_value(word)?
                } else {
                    value
                }
            }
            Modifier::Assign { colon, word } => {
                if !absent(*colon) {
                    return Ok(value);
                }
                if !indices.is_empty() {
                    return Err(CommandFailure::usage(format!(
                        "${{{name}[...]:=word}} cannot assign through an index; assign to {name} itself"
                    )));
                }
                let substitute = self.assignment_value(word)?;
                self.assign(name, substitute.clone())?;
                substitute
            }
            Modifier::Require { colon, word } => {
                if !absent(*colon) {
                    return Ok(value);
                }
                let message = match word {
                    Some(word) => self.expand_quoted(&word.parts)?,
                    None => "parameter is not set".to_owned(),
                };
                return Err(CommandFailure::Fatal(FatalError::Assertion(format!(
                    "{name}: {message}"
                ))));
            }
            Modifier::Alternate { colon, word } => {
                if absent(*colon) {
                    Value::Null
                } else {
                    self.assignment_value(word)?
                }
            }
            Modifier::StripPrefix(pattern) => {
                let pattern = self.literal_pattern(pattern)?;
                let text = display(&value);
                Value::String(
                    text.strip_prefix(&pattern)
                        .map_or(text.clone(), str::to_owned),
                )
            }
            Modifier::StripSuffix(pattern) => {
                let pattern = self.literal_pattern(pattern)?;
                let text = display(&value);
                Value::String(
                    text.strip_suffix(&pattern)
                        .map_or(text.clone(), str::to_owned),
                )
            }
            Modifier::Replace {
                all,
                pattern,
                replacement,
            } => {
                let pattern = self.literal_pattern(pattern)?;
                let replacement = self.expand_quoted(&replacement.parts)?;
                let text = display(&value);
                if pattern.is_empty() {
                    return Err(CommandFailure::usage(format!(
                        "${{{name}/...}} needs text to replace; an empty pattern matches everywhere"
                    )));
                }
                Value::String(if *all {
                    text.replace(&pattern, &replacement)
                } else {
                    text.replacen(&pattern, &replacement, 1)
                })
            }
        })
    }

    /// Expands one `${NAME#pattern}`-family pattern and refuses the metacharacters it cannot honor.
    ///
    /// Same rule as a `grep`, `sed`, or `case` pattern. A constant pattern was already checked by
    /// the parser, where quoting was still visible; only one assembled at run time is checked here.
    fn literal_pattern(&mut self, pattern: &Pattern) -> Result<String, CommandFailure> {
        match pattern {
            Pattern::Literal(word) => self.expand_quoted(&word.parts),
            Pattern::Expanded(word) => {
                let text = self.expand_quoted(&word.parts)?;
                if let Some((character, meaning)) = pattern_metacharacter(&text) {
                    return Err(CommandFailure::usage(expanded_parameter_pattern(
                        character, meaning,
                    )));
                }
                Ok(text)
            }
        }
    }

    /// Evaluates one `[[ ... ]]` expression.
    ///
    /// `&&` and `||` short-circuit, exactly as they do between commands, so
    /// `[[ -n $x && $x == ok ]]` never evaluates the comparison for an unset `x`.
    fn evaluate_conditional(
        &mut self,
        expression: &Conditional,
    ) -> Result<ExitCode, CommandFailure> {
        self.budget.charge_step()?;
        match expression {
            Conditional::Test(test) => self.evaluate_conditional_test(test),
            Conditional::Not(inner) => Ok(invert(self.evaluate_conditional(inner)?)),
            Conditional::And(left, right) => {
                let status = self.evaluate_conditional(left)?;
                if status == ExitCode::SUCCESS {
                    return self.evaluate_conditional(right);
                }
                Ok(status)
            }
            Conditional::Or(left, right) => {
                let status = self.evaluate_conditional(left)?;
                if status == ExitCode::SUCCESS {
                    return Ok(status);
                }
                self.evaluate_conditional(right)
            }
        }
    }

    /// Evaluates one `[[ ]]` primary.
    ///
    /// Each operand expands to exactly one word — that is the promise `[[ ]]` makes over `[ ]`, and
    /// it is why `[[ -n $x ]]` holds for a value with spaces where `[ -n $x ]` falls apart. The
    /// test itself is [`builtins::misc::evaluate_test`], the same code `test` and `[` run, so the
    /// two spellings can never disagree about what `-z` or `-lt` mean.
    fn evaluate_conditional_test(
        &mut self,
        test: &ConditionalTest,
    ) -> Result<ExitCode, CommandFailure> {
        let mut operands = Vec::with_capacity(test.words.len());
        for word in &test.words {
            operands.push(self.expand_quoted(&word.parts)?);
        }
        if test.check_right_pattern
            && let [_, _, right] = operands.as_slice()
            && let Some((character, meaning)) = pattern_metacharacter(right)
        {
            return Err(CommandFailure::usage(expanded_conditional_pattern(
                character, meaning,
            )));
        }
        Ok(builtins::misc::evaluate_test("[[", &operands)?.status)
    }

    /// Runs a command substitution, capturing what its pipelines produced.
    fn run_substitution(&mut self, program: &Program) -> Result<(Value, ExitCode), CommandFailure> {
        self.captures.push(Vec::new());
        let flow = self.execute_program(program);
        let captured = self.captures.pop().unwrap_or_default();
        let flow = flow.map_err(CommandFailure::Fatal)?;

        if let Flow::Exit(status) = flow {
            // There is no subshell to confine an `exit` to, so it ends the script.
            return Err(CommandFailure::Fatal(FatalError::Unsupported(format!(
                "exit {status} inside $( ) ends the whole script; this shell has no subshells"
            ))));
        }

        let status = self.last_status;
        let value = reduce_captured(captured);
        self.budget
            .charge_value_bytes(value_bytes(&value))
            .map_err(CommandFailure::from)?;
        // Every substitution records its status, not only a whole-RHS one: `x=a$(false)` must
        // still leave `$?` at 1, exactly as `url="https://$(get_host)/x"` must report a failed
        // lookup rather than reading as a success.
        self.last_substitution_status = status;
        Ok((value, status))
    }

    // -----------------------------------------------------------------------
    // Arithmetic
    // -----------------------------------------------------------------------

    /// Evaluates one arithmetic node.
    ///
    /// Every node charges a step. The parser caps how deep and how large an expression may be, so
    /// this recursion is bounded before it starts; the step charge is what keeps a large-but-legal
    /// expression inside the same budget the rest of the evaluator answers to.
    fn evaluate_arithmetic(&mut self, expression: &ArithExpr) -> Result<Number, CommandFailure> {
        self.budget.charge_step()?;
        Ok(match expression {
            ArithExpr::Integer(value) => Number::Integer(*value),
            ArithExpr::Float(value) => Number::Float(*value),
            ArithExpr::Variable(name) => {
                // `$(( $1 + 1 ))` reads a positional parameter; only `$N` can produce a
                // digit-only name here, because a bare digit lexes as a literal.
                let value = match name.parse::<usize>() {
                    Ok(position) => self.parameter_value(&Parameter::Positional(position))?,
                    Err(_) => self.lookup(name).cloned().unwrap_or(Value::Null),
                };
                to_number(&value)
            }
            ArithExpr::Unary(operator, operand) => {
                let operand = self.evaluate_arithmetic(operand)?;
                match operator {
                    ArithUnaryOp::Negate => match operand {
                        Number::Integer(value) => Number::Integer(value.wrapping_neg()),
                        Number::Float(value) => Number::Float(-value),
                    },
                    ArithUnaryOp::Not => Number::Integer(i64::from(!operand.is_truthy())),
                }
            }
            ArithExpr::Binary(operator, left, right) => {
                // `&&` and `||` short-circuit, so `$(( x != 0 && 10 / x > 1 ))` is safe.
                match operator {
                    ArithBinaryOp::And => {
                        let left = self.evaluate_arithmetic(left)?;
                        if !left.is_truthy() {
                            return Ok(Number::Integer(0));
                        }
                        let right = self.evaluate_arithmetic(right)?;
                        return Ok(Number::Integer(i64::from(right.is_truthy())));
                    }
                    ArithBinaryOp::Or => {
                        let left = self.evaluate_arithmetic(left)?;
                        if left.is_truthy() {
                            return Ok(Number::Integer(1));
                        }
                        let right = self.evaluate_arithmetic(right)?;
                        return Ok(Number::Integer(i64::from(right.is_truthy())));
                    }
                    _ => {}
                }

                let left = self.evaluate_arithmetic(left)?;
                let right = self.evaluate_arithmetic(right)?;
                arithmetic(*operator, left, right)?
            }
        })
    }
}

/// Reports whether a parameter keeps splitting into one word per element inside double quotes.
///
/// `"$@"` is the most-trained idiom in shell and `"${NAME[@]}"` is its named-variable counterpart:
/// both exist precisely so a list survives quoting intact. Every other expansion inside quotes is
/// one field.
fn splits_inside_quotes(parameter: &Parameter) -> bool {
    match parameter {
        Parameter::AllPositional => true,
        Parameter::Named {
            indices, length, ..
        } => !*length && matches!(indices.last(), Some(Index::All)),
        _ => false,
    }
}

/// Splits one `read` line into at most `count` fields on whitespace runs.
///
/// The remainder lands in the last field, as bash does, and leading whitespace is skipped. Local to
/// `read` rather than a return of IFS word splitting: nothing else in this shell splits, and there
/// is no `IFS` to configure.
fn split_read_fields(line: &str, count: usize) -> Vec<&str> {
    let mut fields = Vec::with_capacity(count);
    let mut rest = line.trim_start();
    while fields.len() + 1 < count && !rest.is_empty() {
        match rest.find(char::is_whitespace) {
            Some(offset) => {
                fields.push(&rest[..offset]);
                rest = rest[offset..].trim_start();
            }
            None => break,
        }
    }
    fields.push(rest);
    fields
}

/// Reports whether a word can name a shell variable.
fn is_variable_name(name: &str) -> bool {
    let mut characters = name.chars();
    characters
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
        && characters.all(|character| character.is_ascii_alphanumeric() || character == '_')
}

/// Composes the terminal failure for a `set` option this shell does not enforce.
fn unsupported_option(message: impl Into<String>) -> CommandFailure {
    CommandFailure::Fatal(FatalError::Unsupported(message.into()))
}

/// Reports what `${#NAME}` counts, per value kind.
///
/// A string counts characters, the way bash does. An array counts elements and an object counts
/// keys, which is what `${#NAME}` has to mean once values are real JSON rather than text; anything
/// else counts the characters of its display form.
fn parameter_length(value: &Value) -> Value {
    match value {
        Value::Null => Value::from(0),
        Value::String(text) => Value::from(text.chars().count()),
        Value::Array(items) => Value::from(items.len()),
        Value::Object(fields) => Value::from(fields.len()),
        other => Value::from(display(other).chars().count()),
    }
}

/// Folds a command's captured diagnostics into its value, for `2>&1`.
///
/// A command with nothing to say leaves its value untouched — including its type, so
/// `gh issue view 12 2>&1` still yields an object rather than that object's JSON text. Only when
/// there *are* diagnostics do the two channels have to become one, and they become one the way
/// every text-shaped builtin already crosses between a value and its lines.
fn merge_diagnostics(value: Value, diagnostics: Vec<String>) -> Value {
    if diagnostics.is_empty() {
        return value;
    }
    let mut lines = value::to_lines(&value);
    lines.extend(diagnostics);
    value::from_lines(lines)
}

/// Materializes a piped value for a command that consumes it by value.
///
/// Piped values travel as [`Rc`] so that offering one costs a refcount rather than a deep copy of
/// whatever a capability returned. This is where that ends: a stage's own output is held by nobody
/// else and moves through untouched, while a function frame's stdin is shared with the frame and
/// every later pipeline in its body, so only that case copies — and only for a command that
/// actually reaches for input.
fn own(input: Option<Rc<Value>>) -> Option<Value> {
    input.map(Rc::unwrap_or_clone)
}

/// Inverts a pipeline status for a leading `!`, collapsing every failure to plain success.
fn invert(status: ExitCode) -> ExitCode {
    if status == ExitCode::SUCCESS {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Reduces what a captured block emitted into one value.
///
/// One result keeps its structure so `x=$(cap ... )` stays JSON; several are joined as text
/// because that is what a caller reading multiple lines expects.
///
/// The join honors [`CommandResult::suppress_newline`] the same way [`Evaluator::emit`] does. A
/// capture is still a stream of writes: `v=$(printf '%s' a; printf '%s' b)` is `ab` in bash, and
/// inserting the newline the script explicitly suppressed silently corrupted every value a model
/// assembled piecewise — a URL, a JSON fragment — with no diagnostic anywhere.
fn reduce_captured(captured: Vec<CommandResult>) -> Value {
    match captured.len() {
        0 => Value::String(String::new()),
        1 => captured
            .into_iter()
            .next()
            .map_or(Value::Null, |result| result.value),
        _ => {
            let mut text = String::new();
            // Seeded as if the (absent) result before the first one suppressed its terminator, so
            // nothing is prefixed to the capture.
            let mut previous_suppressed = true;
            for result in &captured {
                if !previous_suppressed {
                    text.push('\n');
                }
                text.push_str(&display(&result.value));
                previous_suppressed = result.suppress_newline;
            }
            Value::String(text)
        }
    }
}

/// Estimates the bytes one value occupies, for the value-byte ceiling.
///
/// This is an approximation of heap cost, not a measurement: it counts payload bytes plus a small
/// fixed charge per node so that a deeply nested structure of empty pieces still costs something.
fn value_bytes(value: &Value) -> u64 {
    const NODE_OVERHEAD: u64 = 16;
    NODE_OVERHEAD
        + match value {
            Value::Null | Value::Bool(_) | Value::Number(_) => 0,
            Value::String(text) => text.len() as u64,
            Value::Array(items) => items.iter().map(value_bytes).sum(),
            Value::Object(fields) => fields
                .iter()
                .map(|(key, field)| key.len() as u64 + value_bytes(field))
                .sum(),
        }
}

#[allow(
    clippy::map_err_ignore,
    reason = "ParseIntError separates only empty, non-digit, and overflow for a `shift` operand \
              the message quotes back in full; all three mean the same thing to the script author"
)]
fn parse_shift_count(arguments: &[String]) -> Result<usize, CommandFailure> {
    match arguments {
        [] => Ok(1),
        [count] => count.parse::<usize>().map_err(|_| {
            CommandFailure::usage(format!("shift: {count:?} is not a parameter count"))
        }),
        _ => Err(CommandFailure::usage(
            "shift: accepts at most one parameter count",
        )),
    }
}

/// A `break N` that escapes the outermost loop it can reach becomes an ordinary exit from it.
fn unwind_break(level: u32) -> Flow {
    if level > 1 {
        Flow::Break(level - 1)
    } else {
        Flow::Normal
    }
}

fn parse_level(command: &str, arguments: &[String]) -> Result<u32, CommandFailure> {
    match arguments {
        [] => Ok(1),
        [level] => level
            .parse::<u32>()
            .ok()
            .filter(|level| *level > 0)
            .ok_or_else(|| {
                CommandFailure::usage(format!("{command}: {level:?} is not a positive loop level"))
            }),
        _ => Err(CommandFailure::usage(format!(
            "{command}: accepts at most one loop level"
        ))),
    }
}

#[allow(
    clippy::map_err_ignore,
    reason = "ParseIntError separates only empty, non-digit, and overflow for an `exit`/`return` \
              operand the message quotes back in full; an out-of-range status is not a different \
              user mistake from a non-numeric one here"
)]
fn parse_status(
    command: &str,
    arguments: &[String],
    fallback: ExitCode,
) -> Result<ExitCode, CommandFailure> {
    match arguments {
        [] => Ok(fallback),
        [status] => status
            .parse::<i64>()
            .map(ExitCode::from_script_exit)
            .map_err(|_| {
                CommandFailure::usage(format!("{command}: {status:?} is not a numeric status"))
            }),
        _ => Err(CommandFailure::usage(format!(
            "{command}: accepts at most one status"
        ))),
    }
}

/// Appends text to the last field.
fn append(fields: &mut Vec<String>, text: &str) {
    if let Some(last) = fields.last_mut() {
        last.push_str(text);
    } else {
        fields.push(text.to_owned());
    }
}

/// Spreads one expanded value across argv fields.
///
/// POSIX IFS word splitting is dropped. In its place: an unquoted expansion holding a JSON array
/// expands element by element into separate argv words, and any scalar expands to exactly one word.
fn spread(fields: &mut Vec<String>, value: &Value) -> bool {
    match value {
        Value::Array(items) => {
            if items.is_empty() {
                return false;
            }
            let mut items = items.iter();
            if let Some(first) = items.next() {
                append(fields, &display(first));
            }
            for item in items {
                fields.push(display(item));
            }
            true
        }
        Value::Null => false,
        scalar => {
            let text = display(scalar);
            let produced = !text.is_empty();
            append(fields, &text);
            produced
        }
    }
}

/// Renders a value inside double quotes, where arrays never split into separate words.
///
/// `"$@"` therefore joins with a space rather than producing one word per parameter. That is a
/// documented deviation from bash, chosen so that double quotes always mean "exactly one word".
fn quoted_text(value: &Value) -> String {
    match value {
        Value::Array(items) => items.iter().map(display).collect::<Vec<_>>().join(" "),
        other => display(other),
    }
}

/// An arithmetic value.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Number {
    Integer(i64),
    Float(f64),
}

impl Number {
    fn is_truthy(self) -> bool {
        match self {
            Self::Integer(value) => value != 0,
            Self::Float(value) => value != 0.0,
        }
    }

    fn as_f64(self) -> f64 {
        match self {
            Self::Integer(value) => value as f64,
            Self::Float(value) => value,
        }
    }
}

fn render_number(number: Number) -> String {
    match number {
        Number::Integer(value) => value.to_string(),
        Number::Float(value) => {
            if value.fract() == 0.0 && value.is_finite() && value.abs() < 1e15 {
                format!("{}", value as i64)
            } else {
                value.to_string()
            }
        }
    }
}

/// Coerces a value into an arithmetic operand, defaulting to zero like bash does.
fn to_number(value: &Value) -> Number {
    match value {
        Value::Number(number) => number.as_i64().map_or_else(
            || Number::Float(number.as_f64().unwrap_or_default()),
            Number::Integer,
        ),
        Value::Bool(flag) => Number::Integer(i64::from(*flag)),
        Value::String(text) => {
            let text = text.trim();
            text.parse::<i64>().map_or_else(
                |_| Number::Float(text.parse::<f64>().unwrap_or_default()),
                Number::Integer,
            )
        }
        _ => Number::Integer(0),
    }
}

fn arithmetic(
    operator: ArithBinaryOp,
    left: Number,
    right: Number,
) -> Result<Number, CommandFailure> {
    use ArithBinaryOp as Op;

    let comparison = |ordering: Option<Ordering>, expected: &[Ordering]| {
        Number::Integer(i64::from(
            ordering.is_some_and(|ordering| expected.contains(&ordering)),
        ))
    };
    let ordering = left.as_f64().partial_cmp(&right.as_f64());

    Ok(match operator {
        Op::Less => comparison(ordering, &[Ordering::Less]),
        Op::LessOrEqual => comparison(ordering, &[Ordering::Less, Ordering::Equal]),
        Op::Greater => comparison(ordering, &[Ordering::Greater]),
        Op::GreaterOrEqual => comparison(ordering, &[Ordering::Greater, Ordering::Equal]),
        Op::Equal => comparison(ordering, &[Ordering::Equal]),
        Op::NotEqual => comparison(ordering, &[Ordering::Less, Ordering::Greater]),
        Op::And | Op::Or => unreachable!("logical operators short-circuit before this point"),
        Op::Add | Op::Subtract | Op::Multiply | Op::Divide | Op::Remainder => match (left, right) {
            (Number::Integer(left), Number::Integer(right)) => match operator {
                Op::Add => Number::Integer(left.wrapping_add(right)),
                Op::Subtract => Number::Integer(left.wrapping_sub(right)),
                Op::Multiply => Number::Integer(left.wrapping_mul(right)),
                Op::Divide => {
                    if right == 0 {
                        return Err(CommandFailure::failed(
                            "dekopon-shell: arithmetic division by zero",
                        ));
                    }
                    Number::Integer(left.wrapping_div(right))
                }
                _ => {
                    if right == 0 {
                        return Err(CommandFailure::failed(
                            "dekopon-shell: arithmetic division by zero",
                        ));
                    }
                    Number::Integer(left.wrapping_rem(right))
                }
            },
            _ => {
                let (left, right) = (left.as_f64(), right.as_f64());
                match operator {
                    Op::Add => Number::Float(left + right),
                    Op::Subtract => Number::Float(left - right),
                    Op::Multiply => Number::Float(left * right),
                    Op::Divide => {
                        if right == 0.0 {
                            return Err(CommandFailure::failed(
                                "dekopon-shell: arithmetic division by zero",
                            ));
                        }
                        Number::Float(left / right)
                    }
                    _ => {
                        if right == 0.0 {
                            return Err(CommandFailure::failed(
                                "dekopon-shell: arithmetic division by zero",
                            ));
                        }
                        Number::Float(left % right)
                    }
                }
            }
        },
    })
}

#[cfg(test)]
mod tests;