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
//! Evaluator behavior tests, including the kept-versus-dropped grammar contract.

use std::{cell::RefCell, time::Duration};

use serde_json::{Value, json};

use crate::{
    CapabilityCallResult, CapabilityDescription, CapabilityInvoker, CommandRun, ExitCode,
    Interpreter, Limits, ScriptOutcome,
};

/// The one command word the fixture's provider contributes.
const PROBE: &str = "probe";

/// The help page `probe --help` renders, newline-terminated the way `clap` writes it.
const PROBE_HELP: &str = "Usage: probe <COMMAND>\n\nCommands:\n  upper  Uppercase text\n";

/// A fixture exposing a few capabilities with distinguishable outcomes, reachable only through its
/// one command word.
///
/// Nothing here loads a component: `probe` is a hand-written stand-in for a provider's own argv
/// parser. Most subcommands propose one capability the way a real provider's `run-command` would;
/// the rest stand for the other answers a run can end in. `cli-probe.upper` uppercases its `text`,
/// so a result can never be mistaken for the argv that produced it; `fixture.object` hands back
/// the object its flags describe, which is what the grammar tests use to put a structured value in
/// a pipe.
#[derive(Default)]
pub(super) struct Fixture {
    pub(super) calls: RefCell<Vec<(String, Value)>>,
}

impl CapabilityInvoker for Fixture {
    fn granted(&self) -> Vec<String> {
        vec![
            "cli-probe.upper".to_owned(),
            "fixture.object".to_owned(),
            "http-probe.fetch".to_owned(),
            "policy.denied".to_owned(),
            "provider.broken".to_owned(),
            "provider.refused".to_owned(),
        ]
    }

    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
        (capability == "cli-probe.upper").then(|| CapabilityDescription {
            capability: capability.to_owned(),
            description: "Uppercases its text".to_owned(),
        })
    }

    fn command_words(&self) -> Vec<String> {
        vec![PROBE.to_owned()]
    }

    fn has_command_word(&self, word: &str) -> bool {
        word == PROBE
    }

    /// A `clap`-shaped provider command: help and usage errors are rendered text at the status
    /// `clap` would choose, `-` reads stdin, and every other subcommand maps to one fixed answer.
    fn run_command(&self, word: &str, argv: &[String], stdin: Option<&str>) -> Option<CommandRun> {
        if word != PROBE {
            return None;
        }
        let argv = argv.iter().map(String::as_str).collect::<Vec<_>>();
        Some(match argv.as_slice() {
            ["--help"] => CommandRun::Rendered {
                stdout: PROBE_HELP.to_owned(),
                stderr: String::new(),
                status: 0,
            },
            ["upper", "--text", text] => proposal("cli-probe.upper", json!({ "text": text })),
            ["upper", "-"] => match stdin {
                Some(text) => proposal("cli-probe.upper", json!({ "text": text })),
                None => CommandRun::Failed {
                    message: "probe: no input was piped for -".to_owned(),
                },
            },
            ["object", flags @ ..] => match object_from_flags(flags) {
                Some(object) => proposal("fixture.object", object),
                None => CommandRun::Failed {
                    message: "probe: object takes --key value pairs".to_owned(),
                },
            },
            ["fetch"] => proposal("http-probe.fetch", json!({})),
            ["denied"] => proposal("policy.denied", json!({})),
            ["broken"] => proposal("provider.broken", json!({})),
            ["refused"] => proposal("provider.refused", json!({})),
            ["ungranted"] => proposal("nothing.granted", json!({})),
            ["decline"] => CommandRun::Failed {
                message: "probe: declined".to_owned(),
            },
            ["errored"] => CommandRun::Errored {
                message: "could not connect to broker socket".to_owned(),
            },
            ["cancelled"] => CommandRun::Denied {
                reason: "session-cancelled".to_owned(),
            },
            _ => CommandRun::Rendered {
                stdout: String::new(),
                stderr: format!(
                    "error: unrecognized subcommand '{}'\n\nUsage: probe <COMMAND>\n",
                    argv.first().copied().unwrap_or_default()
                ),
                status: 2,
            },
        })
    }

    fn invoke(
        &self,
        capability: &str,
        input: Value,
        secret_use: Option<dekopon_core::SecretUseProposal>,
    ) -> CapabilityCallResult {
        if secret_use.is_some() {
            return crate::secret_use_unsupported();
        }
        self.calls
            .borrow_mut()
            .push((capability.to_owned(), input.clone()));
        match capability {
            "cli-probe.upper" => match input.get("text").and_then(Value::as_str) {
                Some(text) => {
                    CapabilityCallResult::Succeeded(json!({ "text": text.to_uppercase() }))
                }
                None => CapabilityCallResult::Failed {
                    error: "input must be {\"text\": <string>}".to_owned(),
                    detail: None,
                },
            },
            "fixture.object" => CapabilityCallResult::Succeeded(input),
            "policy.denied" => CapabilityCallResult::Denied {
                reason: "exact policy refused this proposal".to_owned(),
            },
            "provider.broken" => CapabilityCallResult::Failed {
                error: "provider trapped".to_owned(),
                detail: None,
            },
            // What a typed provider failure looks like once the broker has classified it: the
            // class the exit status comes from, and the provider's own sentence beside it.
            "provider.refused" => CapabilityCallResult::Failed {
                error: "provider-failure".to_owned(),
                detail: Some(dekopon_core::ProviderFailureDetail::new(
                    "upstream-rejected",
                    "the image route refused the request with HTTP 400 (moderation_blocked)",
                )),
            },
            "http-probe.fetch" => CapabilityCallResult::Succeeded(json!({
                "status": 200,
                "bodyText": "alpha\nbeta\nalpha",
            })),
            _ => CapabilityCallResult::NotFound,
        }
    }
}

/// A proposal carrying no secret-use intent, which is every proposal this fixture makes.
fn proposal(capability: &str, input: Value) -> CommandRun {
    CommandRun::Proposed {
        capability: capability.to_owned(),
        input,
        secret_use: None,
    }
}

/// Builds the object `probe object --key value ...` describes.
///
/// A value that reads as JSON keeps its JSON type, so `--a 1` is a number; anything else is a
/// string. `None` when the argv is not whole `--key value` pairs.
fn object_from_flags(flags: &[&str]) -> Option<Value> {
    let mut object = serde_json::Map::new();
    for pair in flags.chunks(2) {
        let [flag, text] = pair else {
            return None;
        };
        let key = flag.strip_prefix("--")?;
        let value = serde_json::from_str::<Value>(text)
            .unwrap_or_else(|_| Value::String((*text).to_owned()));
        object.insert(key.to_owned(), value);
    }
    Some(Value::Object(object))
}

fn run(script: &str) -> ScriptOutcome {
    Interpreter::new(Limits::default()).run(script, &Fixture::default())
}

fn run_with(script: &str, limits: Limits) -> ScriptOutcome {
    Interpreter::new(limits).run(script, &Fixture::default())
}

fn output(script: &str) -> String {
    run(script).output
}

fn code(script: &str) -> u8 {
    run(script).exit_code.get()
}

// ---------------------------------------------------------------------------
// Kept grammar
// ---------------------------------------------------------------------------

#[test]
fn assigns_and_expands_variables() {
    assert_eq!(output("name=world\necho \"hello $name\""), "hello world");
    assert_eq!(output("x=1\ny=$x\necho ${y}"), "1");
    assert_eq!(output("echo \"[$missing]\""), "[]");
}

#[test]
fn quoting_matches_bash() {
    assert_eq!(output(r#"x=v; echo '$x $(echo no)'"#), "$x $(echo no)");
    assert_eq!(output(r#"x=v; echo "$x""#), "v");
    assert_eq!(output(r#"echo "a\"b""#), "a\"b");
}

#[test]
fn sequencing_and_short_circuiting_follow_exit_codes() {
    assert_eq!(output("true && echo yes"), "yes");
    assert_eq!(output("false && echo no"), "");
    assert_eq!(output("false || echo fallback"), "fallback");
    assert_eq!(output("true || echo skipped"), "");
    assert_eq!(output("echo a; echo b"), "a\nb");
}

#[test]
fn last_status_is_observable() {
    assert_eq!(output("true; echo $?"), "0");
    assert_eq!(output("false; echo $?"), "1");
    assert_eq!(
        output("nosuchcmd; echo $?"),
        "dekopon-shell: nosuchcmd: command not found\n127"
    );
}

#[test]
fn comments_are_ignored() {
    assert_eq!(
        output("# leading\necho hi # trailing\n# trailing only"),
        "hi"
    );
}

#[test]
fn if_elif_else_selects_one_branch() {
    let script = "x=2\nif [ $x -eq 1 ]; then echo one; elif [ $x -eq 2 ]; then echo two; else echo other; fi";
    assert_eq!(output(script), "two");
    assert_eq!(output("if false; then echo a; else echo b; fi"), "b");
}

#[test]
fn for_loops_iterate_over_words_and_arrays() {
    assert_eq!(output("for x in a b c; do echo $x; done"), "a\nb\nc");
    // An unquoted `$( )` producing a real JSON array expands element by element.
    assert_eq!(
        output("for x in $(probe object --a 1 --b 2 --c 3 | jq '[.a,.b,.c]'); do echo $x; done"),
        "1\n2\n3"
    );
}

#[test]
fn while_and_until_loops_terminate_on_their_condition() {
    assert_eq!(
        output("i=0\nwhile [ $i -lt 3 ]; do echo $i; i=$(( i + 1 )); done"),
        "0\n1\n2"
    );
    assert_eq!(
        output("i=0\nuntil [ $i -ge 2 ]; do echo $i; i=$(( i + 1 )); done"),
        "0\n1"
    );
}

#[test]
fn break_and_continue_respect_nesting_levels() {
    assert_eq!(
        output("for x in 1 2 3; do if [ $x -eq 2 ]; then continue; fi; echo $x; done"),
        "1\n3"
    );
    assert_eq!(
        output("for x in 1 2 3; do if [ $x -eq 2 ]; then break; fi; echo $x; done"),
        "1"
    );
    // `break 2` leaves both loops; only the outer loop's trailing marker should print.
    assert_eq!(
        output(
            "for a in 1 2; do for b in 1 2; do echo $a$b; if [ $b -eq 1 ]; then break 2; fi; done; echo inner-done; done\necho after"
        ),
        "11\nafter"
    );
    // `continue 2` restarts the outer loop instead of the inner one.
    assert_eq!(
        output(
            "for a in 1 2; do for b in 1 2; do echo $a$b; continue 2; done; echo unreachable; done"
        ),
        "11\n21"
    );
}

#[test]
fn functions_take_positional_parameters_and_return_status() {
    let script = "greet() { echo \"hi $1 and $2\"; }\ngreet ann bob";
    assert_eq!(output(script), "hi ann and bob");
    assert_eq!(output("count() { echo $#; }\ncount a b c"), "3");
    assert_eq!(output("all() { echo $@; }\nall a b"), "a b");
    assert_eq!(output("fail() { return 3; }\nfail; echo $?"), "3");
}

#[test]
fn a_negated_pipeline_inverts_its_status() {
    // Dispatching `!` as a command word reported "command not found" and inverted every branch.
    assert_eq!(output("if ! false; then echo neg; fi"), "neg");
    assert_eq!(output("if ! true; then echo no; else echo yes; fi"), "yes");
    assert_eq!(output("! false && echo reached"), "reached");
    assert_eq!(code("! true"), 1);
    assert_eq!(code("! false"), 0);
    // A `!` that is an argument rather than a pipeline prefix is untouched.
    assert_eq!(output("if [ ! -z x ]; then echo arg; fi"), "arg");
}

#[test]
fn functions_participate_in_pipelines_in_both_directions() {
    // A function used to leak its output past the pipe and hand the next command a null.
    assert_eq!(output("f() { echo hi; }\nf | wc -c"), "2");
    assert_eq!(output("g() { cat; }\necho payload | g"), "payload");
    // A guard that never reads the input must not swallow it before the command that does.
    assert_eq!(
        output("g() { if [ -n \"$1\" ]; then cat; fi; }\necho payload | g yes"),
        "payload"
    );
    assert_eq!(output("f() { echo one; echo two; }\nf | grep one"), "one");
    // In terminal position a function still streams straight to the output.
    assert_eq!(output("f() { echo one; echo two; }\nf"), "one\ntwo");
    // A function that produces nothing contributes no phantom line.
    assert_eq!(output("echo a\nq() { true; }\nq\necho b"), "a\nb");
}

#[test]
fn a_piped_value_survives_every_stage_and_every_statement_that_shares_it() {
    // The frame's stdin is shared, not consumed, so each pipeline in a body is offered the same
    // value however many statements precede it and whether or not they read it.
    assert_eq!(
        output("g() { cat; cat; }\necho payload | g"),
        "payload\npayload"
    );
    assert_eq!(
        output("g() { true; echo first; cat; }\necho payload | g"),
        "first\npayload"
    );
    // Structure survives being handed from stage to stage rather than copied into each one.
    assert_eq!(
        output(r#"probe object --a 1 --b two | jq '.b' | cat"#),
        "two"
    );
    assert_eq!(
        output(r#"g() { cat | jq '.a'; cat | jq '.b'; }; probe object --a 1 --b 2 | g"#),
        "1\n2"
    );
    // A here-document still replaces whatever a pipe would have supplied.
    assert_eq!(output("echo ignored | cat <<EOF\nbody\nEOF"), "body");
}

#[test]
fn prefix_assignments_are_transient_and_applied_after_expansion() {
    // `x=new echo "[$x]"` must print the *old* value and must not outlive the command.
    assert_eq!(
        output(r#"x=old; x=new echo "[$x]"; echo "after=[$x]""#),
        "[old]\nafter=[old]"
    );
    // A prefix assignment on a name that did not exist leaves no binding behind.
    assert_eq!(output(r#"DEBUG=1 true; echo "[$DEBUG]""#), "[]");
    // An assignment with no command word is an ordinary, lasting assignment.
    assert_eq!(output(r#"x=kept; echo "[$x]""#), "[kept]");
}

#[test]
fn shift_consumes_positional_parameters() {
    assert_eq!(output(r#"f() { shift; echo "$1"; }; f a b"#), "b");
    assert_eq!(output(r#"f() { shift 2; echo "$1 $#"; }; f a b c"#), "c 1");
    // Shifting past the end fails rather than silently truncating, as in bash.
    assert_eq!(output(r#"f() { shift 5; echo $?; }; f a"#), "1");
    assert_eq!(
        output(r#"f() { while [ $# -gt 0 ]; do echo $1; shift; done; }; f a b c"#),
        "a\nb\nc"
    );
}

#[test]
fn quoted_all_positional_splits_one_word_per_parameter() {
    // `for x in "$@"` is the most-trained argument idiom there is; joining it into one word made
    // the quoted form silently wrong and the unquoted form the only correct one.
    assert_eq!(
        output(r#"f() { for a in "$@"; do echo "[$a]"; done; }; f "one two" three"#),
        "[one two]\n[three]"
    );
    assert_eq!(
        output(r#"f() { count() { echo $#; }; count "$@"; }; f a b c"#),
        "3"
    );
    // Zero parameters forward as zero words, not one empty one.
    assert_eq!(
        output(r#"f() { count() { echo $#; }; count "$@"; }; f"#),
        "0"
    );
    // `$*` is the always-joined counterpart, and used to expand to the literal text `$*`.
    assert_eq!(output(r#"f() { echo "[$*]"; }; f a b"#), "[a b]");
    assert_eq!(
        output(r#"f() { count() { echo $#; }; count "$*"; }; f a b"#),
        "1"
    );
}

#[test]
fn diagnostics_inside_a_substitution_still_reach_the_output() {
    // Only the *value* of `$( )` is captured. Swallowing its errors too left a script with an
    // empty variable, no explanation, and a `$?` it may never look at.
    let outcome = run(r#"v=$(nosuchcmd); echo "v=[$v] status=$?""#);
    assert!(
        outcome.output.contains("nosuchcmd: command not found"),
        "{}",
        outcome.output
    );
    assert!(
        outcome.output.contains("v=[] status=127"),
        "{}",
        outcome.output
    );

    let outcome = run(r#"v=$(probe denied); echo "[$v]""#);
    assert!(
        outcome
            .output
            .contains("exact policy refused this proposal"),
        "{}",
        outcome.output
    );
}

#[test]
fn a_capture_drops_a_null_result_the_way_the_output_path_does() {
    // Outside a capture, a command that produced no value writes nothing. Inside one it used to
    // become an element of the captured stream, and a capture joins its elements with a newline —
    // so `true` contributed a blank line whose position depended only on where it sat. bash prints
    // `a` for both of these.
    assert_eq!(output(r#"x=$(true; echo a); echo "[$x]""#), "[a]");
    assert_eq!(output(r#"x=$(echo a; true); echo "[$x]""#), "[a]");
    // A command that selected nothing is the same case: `grep` with no match produces no value.
    assert_eq!(
        output(r#"x=$(echo hi | grep zz; echo a); echo "[$x]""#),
        "[a]"
    );
    // Real output is still joined line by line, and the status a null-valued command reported
    // still reaches `$?`, because it travels through `last_status` rather than the capture.
    assert_eq!(output(r#"x=$(echo a; echo b); echo "[$x]""#), "[a\nb]");
    assert_eq!(output("x=$(echo a; false); echo $?"), "1");
}

#[test]
fn an_interpolated_substitution_still_reports_its_status() {
    assert_eq!(output("x=a$(false); echo $?"), "1");
    assert_eq!(output("x=$(false); echo $?"), "1");
    assert_eq!(output("x=a$(true); echo $?"), "0");
}

#[test]
fn local_shadows_a_global_with_bash_dynamic_scoping() {
    let script = "\
x=global
inner() { echo $x; }
outer() { local x=shadowed; inner; }
outer
echo $x";
    // Dynamic scoping: `inner` sees `outer`'s local, and the global is intact afterwards.
    assert_eq!(output(script), "shadowed\nglobal");
}

#[test]
fn recursion_works_within_the_depth_cap() {
    let script = "\
countdown() {
  if [ $1 -le 0 ]; then return 0; fi
  echo $1
  countdown $(( $1 - 1 ))
}
countdown 3";
    assert_eq!(output(script), "3\n2\n1");
}

#[test]
fn arithmetic_expansion_covers_the_documented_operators() {
    assert_eq!(output("echo $(( 1 + 2 * 3 ))"), "7");
    assert_eq!(output("echo $(( (1 + 2) * 3 ))"), "9");
    assert_eq!(output("echo $(( 7 / 2 ))"), "3");
    assert_eq!(output("echo $(( 7 % 2 ))"), "1");
    assert_eq!(output("echo $(( 7.0 / 2 ))"), "3.5");
    assert_eq!(output("echo $(( 2 < 3 ))"), "1");
    assert_eq!(output("echo $(( 2 >= 3 ))"), "0");
    assert_eq!(output("echo $(( 1 == 1 ))"), "1");
    assert_eq!(output("echo $(( 1 != 1 ))"), "0");
    assert_eq!(output("echo $(( 1 && 0 ))"), "0");
    assert_eq!(output("echo $(( 1 || 0 ))"), "1");
    assert_eq!(output("n=5; echo $(( n * 2 ))"), "10");
    assert_eq!(output("n=5; echo $(( $n - 1 ))"), "4");
}

#[test]
fn division_by_zero_is_recoverable_not_fatal() {
    let outcome = run("echo $(( 1 / 0 ))\necho after");
    assert!(
        outcome.output.contains("division by zero"),
        "{}",
        outcome.output
    );
    assert!(outcome.output.contains("after"), "{}", outcome.output);
}

#[test]
fn command_substitution_preserves_structure_only_as_a_whole_rhs() {
    // Whole-RHS `$( )` keeps the structured value...
    assert_eq!(
        output(r#"r=$(probe object --status 200); echo ${r[status]}"#),
        "200"
    );
    // ...while an interpolated `$( )` coerces to display form, exactly like bash.
    assert_eq!(
        output(r#"r="x$(probe object --status 200)"; echo $r"#),
        r#"x{"status":200}"#
    );
}

#[test]
fn a_capture_honors_the_newline_a_command_suppressed() {
    // Assembling a value piecewise with `printf` is a common model idiom, and a capture that joins
    // every result with "\n" corrupts every one of them: broken URLs, broken JSON fragments, no
    // diagnostic. bash prints `ab` for both of these.
    assert_eq!(
        output(r#"v=$(printf '%s' a; printf '%s' b); echo "$v""#),
        "ab"
    );
    assert_eq!(output(r#"v=$(echo -n a; echo -n b); echo "$v""#), "ab");
    // A result that did not suppress its terminator still separates the next one.
    assert_eq!(
        output(r#"v=$(echo a; echo b); echo "$v" | wc -l"#),
        "2".to_owned()
    );
    assert_eq!(output(r#"v=$(printf '%s' a; echo b); echo "$v""#), "ab");
    assert_eq!(
        output(r#"v=$(echo a; printf '%s' b); echo "$v" | wc -l"#),
        "2".to_owned()
    );
}

#[test]
fn indexing_is_backed_by_real_json() {
    assert_eq!(
        output(r#"o=$(probe object --a 1 --b 2); echo ${o[b]}"#),
        "2"
    );
    assert_eq!(
        output(r#"a=$(probe object --x 10 | jq '[.x, 20]'); echo ${a[1]}"#),
        "20"
    );
    assert_eq!(
        output(r#"a=$(probe object --x 10 | jq '[.x]'); echo "[${a[9]}]""#),
        "[]"
    );
}

#[test]
fn unquoted_arrays_expand_element_by_element() {
    // POSIX IFS splitting is dropped; a JSON array is what produces multiple argv words.
    assert_eq!(
        output(r#"a=$(probe object --x x --y y | jq '[.x,.y]'); count() { echo $#; }; count $a"#),
        "2"
    );
    // A scalar containing spaces stays exactly one word.
    assert_eq!(
        output(r#"s="one two"; count() { echo $#; }; count $s"#),
        "1"
    );
}

#[test]
fn pipelines_deliver_structured_values() {
    assert_eq!(output(r#"probe object --a 1 | jq .a"#), "1");
    assert_eq!(output("echo 'a\nb\na' | sort | uniq | wc -l"), "2");
    assert_eq!(
        output("probe fetch | jq -r .bodyText | grep alpha | wc -l"),
        "2"
    );
}

#[test]
fn redirection_writes_and_cat_reads_named_buffers() {
    assert_eq!(output("echo hi > buf\ncat buf"), "hi");
    assert_eq!(output("echo a > buf\necho b >> buf\ncat buf | wc -l"), "2");
    assert_eq!(output("echo hi > buf"), "");
    let outcome = run("cat /etc/passwd");
    assert!(
        outcome.output.contains("no such buffer"),
        "{}",
        outcome.output
    );
}

#[test]
fn exit_sets_the_script_status_and_wraps_like_bash() {
    assert_eq!(code("exit 0"), 0);
    assert_eq!(code("exit 7"), 7);
    assert_eq!(code("exit 300"), 44);
    assert_eq!(output("echo a; exit 1; echo b"), "a");
    assert_eq!(code("echo a; exit 1; echo b"), 1);
}

#[test]
fn xargs_maps_a_command_over_a_list() {
    let fixture = Fixture::default();
    let outcome = Interpreter::new(Limits::default()).run(
        r#"probe object --a a --b b | jq '[.a,.b]' | xargs probe upper --text"#,
        &fixture,
    );
    // One call builds the list, then `xargs` drives one provider command per element, each of
    // which proposes its own capability call.
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
    assert_eq!(outcome.capability_calls, 3);
    assert_eq!(
        *fixture.calls.borrow(),
        vec![
            ("fixture.object".to_owned(), json!({"a": "a", "b": "b"})),
            ("cli-probe.upper".to_owned(), json!({"text": "a"})),
            ("cli-probe.upper".to_owned(), json!({"text": "b"})),
        ]
    );
    assert_eq!(outcome.output, r#"[{"text":"A"},{"text":"B"}]"#);
}

// ---------------------------------------------------------------------------
// Capability dispatch and exit codes
// ---------------------------------------------------------------------------

#[test]
fn a_capability_shaped_word_is_an_ordinary_unknown_command() {
    // A capability is reached through the command word of the provider that owns it. A word
    // shaped like a capability identifier is only a word — even one naming a capability this
    // session holds — so it takes the shell's ordinary "command not found" path and runs nothing.
    let fixture = Fixture::default();
    let outcome = Interpreter::new(Limits::default()).run(
        "wikipedia_page --title x; echo $?\ncli-probe.upper --text hi; echo $?",
        &fixture,
    );
    assert_eq!(
        outcome.output,
        "dekopon-shell: wikipedia_page: command not found\n127\n\
         dekopon-shell: cli-probe.upper: command not found\n127"
    );
    assert!(
        fixture.calls.borrow().is_empty(),
        "a capability-shaped word invoked a capability"
    );
    assert_eq!(outcome.capability_calls, 0);
}

/// The classification alone cannot say which refusal this was, so the provider's own code and
/// message are appended to it. Without them a model reads `failed: provider-failure` and invents a
/// reason for an upstream moderation refusal it was never told about.
#[test]
fn a_typed_provider_failure_renders_its_code_and_message_after_the_classification() {
    let outcome = Interpreter::new(Limits::default()).run("probe refused", &Fixture::default());

    assert_eq!(
        outcome.output,
        "provider.refused: failed: provider-failure: upstream-rejected: the image route refused \
         the request with HTTP 400 (moderation_blocked)"
    );
    assert_eq!(outcome.exit_code, ExitCode::FAILURE);
}

/// A failure no provider reported keeps the line it always had; nothing is appended to invent one.
#[test]
fn a_failure_without_a_provider_detail_renders_the_classification_alone() {
    let outcome = Interpreter::new(Limits::default()).run("probe broken", &Fixture::default());

    assert_eq!(outcome.output, "provider.broken: failed: provider trapped");
    assert_eq!(outcome.exit_code, ExitCode::FAILURE);
}

#[test]
fn capability_outcomes_map_onto_their_documented_exit_codes() {
    assert_eq!(code("probe upper --text a"), 0);
    assert_eq!(code("probe broken"), 1);
    assert_eq!(code("probe denied"), 126);
    assert_eq!(code("probe ungranted"), 127);
    assert_eq!(code("definitelynotacommand"), 127);
}

#[test]
fn cap_lists_and_describes_capabilities() {
    assert!(output("cap --list").contains("cli-probe.upper"));
    let described = output("cap --describe cli-probe.upper");
    assert!(described.contains("Uppercases its text"), "{described}");
    // Using a capability is its provider's `--help`, not a schema.
    assert!(!described.contains("inputSchema"), "{described}");
}

#[test]
fn a_function_shadows_a_builtin_only_when_declared_first() {
    assert_eq!(output("echo hi"), "hi");
    assert_eq!(output("echo() { true; }\necho hi"), "");
}

// ---------------------------------------------------------------------------
// Dropped grammar: every one of these must fail loudly, not silently
// ---------------------------------------------------------------------------

#[test]
fn globbing_is_dropped_and_stays_literal() {
    // There is no filesystem to glob against, so `*` is an ordinary character.
    assert_eq!(output("echo *"), "*");
    assert_eq!(output("echo a?b"), "a?b");
    assert_eq!(output("echo [abc]"), "[abc]");
    assert_eq!(code("echo *"), 0);
}

#[test]
fn brace_and_tilde_expansion_are_dropped_and_stay_literal() {
    assert_eq!(output("echo {a,b,c}"), "{a,b,c}");
    assert_eq!(output("echo ~"), "~");
    assert_eq!(output("echo ~/x"), "~/x");
}

#[test]
fn backgrounding_is_a_hard_parse_error() {
    let outcome = run("sleep 1 &\necho after");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("backgrounding"),
        "{}",
        outcome.output
    );
    // Nothing ran: a parse failure rejects the whole script.
    assert!(!outcome.output.contains("after"), "{}", outcome.output);
}

#[test]
fn eval_is_rejected_as_a_sandbox_escape() {
    let outcome = run("eval 'echo hi'");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("eval"), "{}", outcome.output);
    assert!(
        outcome.output.contains("self-modifying code"),
        "{}",
        outcome.output
    );
    assert!(!outcome.output.contains("hi"), "{}", outcome.output);
}

#[test]
fn ambient_authority_commands_are_rejected_by_name() {
    for (script, expected) in [
        ("exec echo hi", "exec"),
        ("source other.sh", "source"),
        (". other.sh", "source"),
        ("trap x INT", "trap"),
        ("wait", "wait"),
        ("jobs", "jobs"),
        ("kill 1", "kill"),
        ("declare -A m", "declare"),
        ("export X=1", "export"),
    ] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{script}");
        assert!(
            outcome.output.contains(expected),
            "{script}: {}",
            outcome.output
        );
    }
}

#[test]
fn subshells_here_strings_and_process_substitution_are_rejected() {
    for (script, expected) in [
        ("(echo hi)", "subshells"),
        ("cat <<<\"$x\"", "here-string"),
        ("diff <(echo a) b", "process substitution"),
        ("cat < file", "input redirection"),
        ("case $x in a) echo a;& b) echo b;; esac", "falls through"),
    ] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{script}");
        assert!(
            outcome.output.contains(expected),
            "{script}: {}",
            outcome.output
        );
    }
}

#[test]
fn case_runs_the_first_matching_clause_and_only_that_one() {
    let script = "\
for name in ready failed other; do\n\
  case $name in\n\
    ready) echo go ;;\n\
    failed|broken) echo stop ;;\n\
    *) echo unknown ;;\n\
  esac\n\
done";
    assert_eq!(output(script), "go\nstop\nunknown");

    // An alternative list matches on any of its patterns, and no clause below it runs.
    assert_eq!(
        output("case broken in\n ready) echo a ;;\n failed|broken) echo b ;;\n *) echo c ;;\nesac"),
        "b"
    );
}

#[test]
fn case_matches_the_expanded_subject_and_reports_success_when_nothing_matches() {
    assert_eq!(
        output("x=ready\ncase \"$x\" in ready) echo yes ;; esac"),
        "yes"
    );
    // bash reports success for a `case` no clause matched; "none of the above" is an answer.
    let outcome = run("case nothing in ready) echo yes ;; esac");
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
    assert_eq!(outcome.output, "");
}

#[test]
fn an_escaped_case_pattern_matches_one_literal_character_like_bash() {
    // `\*` is bash's spelling for a literal asterisk, exactly like `'*'`. Classifying it as the
    // `*)` default branch would silently route every subject through the escaped clause.
    let outcome = run("case hello in \\*) echo caught ;; esac");
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
    assert_eq!(outcome.output, "");

    assert_eq!(output("case '*' in \\*) echo star ;; esac"), "star");
    assert_eq!(output("case 'a*b' in a\\*b) echo mid ;; esac"), "mid");
    assert_eq!(output("case '?' in \\?) echo mark ;; esac"), "mark");
}

#[test]
fn case_composes_with_the_control_flow_around_it() {
    // `break` inside a `case` inside a loop unwinds the loop, exactly as in bash — the `case` is
    // not a scope that swallows it.
    assert_eq!(
        output("for n in 1 2 3; do case $n in 2) break ;; *) echo $n ;; esac; done"),
        "1"
    );
    assert_eq!(
        output("f() { case $1 in a) return 0 ;; *) return 1 ;; esac; }\nf a && echo matched"),
        "matched"
    );
}

#[test]
fn a_case_pattern_assembled_at_run_time_is_still_checked() {
    // The parser cannot see this pattern's text, so the check happens where the text appears.
    // Matching `*.json` literally would answer a question the script did not ask.
    let outcome = run("p='*.json'\ncase report.json in $p) echo matched ;; esac");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("expanded to text"),
        "{}",
        outcome.output
    );
    // It must not advise quoting. Quoting exempts a metacharacter only while the parser can still
    // see it; an expanded pattern has already lost its quotes, so `case '*b' in '*'$x)` is rejected
    // too — and remediation that provably does not work is worse than none.
    assert!(
        !outcome.output.contains("quote it as"),
        "{}",
        outcome.output
    );

    // A run-time pattern with no pattern syntax in it matches literally and is left alone.
    assert_eq!(
        output("p=ready\ncase ready in $p) echo matched ;; esac"),
        "matched"
    );
}

#[test]
fn case_charges_the_step_budget_like_every_other_construct() {
    // Each clause tested is a step, so a `case` inside a loop cannot outrun the budget that
    // bounds the rest of the interpreter.
    let outcome = run_with(
        "while true; do case x in a) : ;; b) : ;; *) : ;; esac; done",
        Limits {
            max_steps: 200,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("step budget"), "{}", outcome.output);
}

#[test]
fn a_here_document_becomes_the_commands_input_as_one_string() {
    // The newline that ended the last body line is dropped, so `cat <<EOF` prints what bash prints
    // rather than one extra blank line: a value in this shell is not newline-terminated.
    assert_eq!(output("cat <<EOF\nalpha\nbeta\nEOF"), "alpha\nbeta");

    // The body is a JSON *string*, deliberately: a block of literal text is a string in this value
    // model, and quietly parsing bodies that happen to look like JSON would make `cat <<EOF` mean
    // two different things depending on its contents. `fromjson` is the explicit way across.
    assert_eq!(
        output("jq -r 'fromjson.name' <<EOF\n{\"name\": \"dekopon\"}\nEOF"),
        "dekopon"
    );
    let unparsed = run("jq -r .name <<EOF\n{\"name\": \"dekopon\"}\nEOF");
    assert_eq!(unparsed.exit_code, ExitCode::FAILURE);
    assert!(
        unparsed.output.contains("cannot index"),
        "{}",
        unparsed.output
    );
}

#[test]
fn a_here_document_interpolates_unless_its_delimiter_is_quoted() {
    assert_eq!(output("id=7\ncat <<EOF\nid=$id\nEOF"), "id=7");
    assert_eq!(output("id=7\ncat <<'EOF'\nid=$id\nEOF"), "id=$id");
    // A command substitution inside a body runs, like any other double-quoted context.
    assert_eq!(output("cat <<EOF\nvalue=$(echo inner)\nEOF"), "value=inner");
}

#[test]
fn a_here_document_replaces_what_a_pipe_would_have_supplied() {
    // A redirection is applied after the pipe in bash, so the here-document wins.
    assert_eq!(
        output("echo piped | cat <<EOF\nredirected\nEOF"),
        "redirected"
    );
    // And the rest of the operator's line stays ordinary shell.
    assert_eq!(output("cat <<EOF | wc -l\na\nb\nEOF"), "2");
}

#[test]
fn a_here_document_body_charges_the_value_byte_ceiling() {
    // Nothing new may materialize bytes outside the ceiling that bounds this interpreter's memory.
    let body = "x".repeat(4096);
    let outcome = run_with(
        &format!("cat <<EOF\n{body}\nEOF"),
        Limits {
            max_value_bytes: 512,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("bytes of values"),
        "{}",
        outcome.output
    );
}

#[test]
fn the_clock_is_not_a_command_this_shell_has() {
    // There is no provider for "what time is it" and no command word to go through, so the word is
    // simply not a command here — indistinguishable from any other word nothing provides.
    let outcome = run("date");
    assert_eq!(outcome.exit_code, ExitCode::NOT_FOUND);
    assert!(
        outcome.output.contains("command not found"),
        "{}",
        outcome.output
    );
}

#[test]
fn array_expansion_is_backed_by_real_json() {
    // `${NAME[@]}` is not bash's sparse-array emulation; it selects the elements of a real JSON
    // array, which is what an unquoted `$NAME` holding one already spreads into.
    assert_eq!(
        output(
            r#"arr=$(probe object --a x --b y | jq '[.a,.b]')
for item in "${arr[@]}"; do echo "[$item]"; done"#
        ),
        "[x]\n[y]"
    );
    assert_eq!(
        output(
            r#"arr=$(probe object --a x --b y | jq '[.a,.b]')
echo "${arr[*]}""#
        ),
        "x y"
    );
    assert_eq!(
        output(
            r#"arr=$(probe object --a x --b y | jq '[.a,.b]')
echo ${#arr[@]}"#
        ),
        "2"
    );
    // A quoted `"${NAME[@]}"` holding one element stays one word, spaces and all.
    assert_eq!(
        output(
            r#"arr=$(probe object --a "one two" | jq '[.a]')
for item in "${arr[@]}"; do echo "[$item]"; done"#
        ),
        "[one two]"
    );
}

// ---------------------------------------------------------------------------
// `read`
// ---------------------------------------------------------------------------

#[test]
fn while_read_walks_every_line_and_then_stops() {
    // The idiom this exists for. `read` consumes through the enclosing stage's cursor, so each
    // iteration sees the next line and end of input is what ends the loop.
    assert_eq!(
        output(r#"probe fetch | jq -r .bodyText | while read line; do echo "[$line]"; done"#),
        "[alpha]\n[beta]\n[alpha]"
    );
    // And the loop keeps what it assigned, because nothing forked.
    assert_eq!(
        output(
            r#"count=0
probe fetch | jq -r .bodyText | while read line; do count=$(( count + 1 )); done
echo $count"#
        ),
        "3"
    );
}

#[test]
fn read_reports_end_of_input_as_a_status_not_a_diagnostic() {
    // A message here would be one per loop, every loop.
    let outcome = run("echo one | while read line; do echo $line; done");
    assert_eq!(outcome.output, "one");
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
    assert_eq!(code("echo '' | read x"), 1, "no lines is a failing read");
}

#[test]
fn read_binds_several_names_by_splitting_on_whitespace() {
    // A rule local to `read`, not a return of IFS word splitting: the remainder lands in the last
    // name, as bash does.
    assert_eq!(
        output(
            r#"echo "alpha beta gamma delta" | { read -r first second rest; echo "1=$first 2=$second rest=$rest"; }"#
        ),
        "1=alpha 2=beta rest=gamma delta"
    );
    assert_eq!(
        output(r#"echo "only" | { read -r a b; echo "[$a][$b]"; }"#),
        "[only][]"
    );
}

#[test]
fn a_piped_read_is_its_own_one_shot_source() {
    // `echo | read` consumes from the pipe, not from anything the enclosing scope holds.
    assert_eq!(output("echo hello | read x\necho $x"), "hello");
}

#[test]
fn read_refuses_what_it_does_not_implement() {
    for (script, expected) in [
        ("echo a | read", "needs at least one variable name"),
        ("echo a | read -d ,", "option \"-d\" is not supported"),
        ("echo a | read 1bad", "is not a valid variable name"),
    ] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{script}");
        assert!(
            outcome.output.contains(expected),
            "{script}: {}",
            outcome.output
        );
    }
}

// ---------------------------------------------------------------------------
// Shell options
// ---------------------------------------------------------------------------

#[test]
fn errexit_ends_the_script_at_the_first_untested_failure() {
    let outcome = run("set -e\necho before\nnosuchcmd\necho after");
    assert_eq!(outcome.exit_code.get(), 127);
    assert!(outcome.output.contains("before"), "{outcome:?}");
    assert!(!outcome.output.contains("after"), "{outcome:?}");
    assert!(outcome.output.contains("`set -e` is on"), "{outcome:?}");

    // Off by default, and `set +e` turns it back off.
    assert!(output("nosuchcmd\necho after").contains("after"));
    assert!(
        output("set -e\nset +e\nnosuchcmd\necho after").contains("after"),
        "`set +e` must restore the default"
    );
}

#[test]
fn errexit_leaves_a_tested_status_alone() {
    // Bash's three exemptions, each one a position where the script is already asking whether the
    // command failed. Tripping there would break the very idiom used to handle failure.
    for script in [
        "set -e\nif nosuchcmd; then echo yes; else echo handled; fi\necho after",
        "set -e\nnosuchcmd || echo handled\necho after",
        // `if a && b` nests two exemptions.
        "set -e\nif true && nosuchcmd; then echo handled; else echo handled; fi\necho after",
    ] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{script}");
        assert!(
            outcome.output.contains("handled"),
            "{script}: {}",
            outcome.output
        );
        assert!(
            outcome.output.contains("after"),
            "{script}: {}",
            outcome.output
        );
    }
    assert_eq!(code("set -e\n! nosuchcmd\necho after"), 0);
    assert_eq!(
        code("set -e\nwhile nosuchcmd; do echo body; done\necho after"),
        0
    );
    // The final operand of a chain is *not* exempt: nothing is asking about it.
    let outcome = run("set -e\ntrue && nosuchcmd\necho after");
    assert_eq!(outcome.exit_code.get(), 127);
    assert!(!outcome.output.contains("after"), "{outcome:?}");
}

#[test]
fn nounset_refuses_a_name_nothing_ever_set() {
    let outcome = run("set -u\necho \"[$missing]\"\necho after");
    assert_eq!(outcome.exit_code, ExitCode::FAILURE);
    assert!(
        outcome.output.contains("missing: unbound variable"),
        "{outcome:?}"
    );
    assert!(!outcome.output.contains("after"), "{outcome:?}");

    // The expansions written to handle an absent value must not be what trips it.
    assert_eq!(output("set -u\necho ${missing:-fallback}"), "fallback");
    assert_eq!(output("set -u\necho \"[${missing+set}]\""), "[]");
    assert_eq!(output("set -u\nx=\necho \"[$x]\""), "[]");
}

#[test]
fn pipefail_reports_the_rightmost_stage_that_failed() {
    // Without it, a command that never ran hides behind a `jq` that was handed nothing and
    // succeeded anyway — the exact shape a model writes and then misreads.
    assert_eq!(code("nosuchcmd | jq ."), 0);
    assert_eq!(code("set -o pipefail\nnosuchcmd | jq ."), 127);
    assert_eq!(code("set -o pipefail\necho hi | jq ."), 0);
    assert_eq!(
        code("set -o pipefail\nset +o pipefail\nnosuchcmd | jq ."),
        0
    );
}

#[test]
fn pipestatus_reports_every_stage() {
    assert!(output("nosuchcmd | jq .\necho ${PIPESTATUS[@]}").ends_with("127 0"));
    assert_eq!(output("echo hi\necho ${PIPESTATUS[0]}"), "hi\n0");
    assert_eq!(
        output("echo a | jq . | wc -l\necho ${#PIPESTATUS[@]}"),
        "1\n3"
    );
}

#[test]
fn set_refuses_every_option_it_does_not_enforce() {
    for (script, expected) in [
        ("set", "listing or setting positional parameters"),
        ("set -x", "option -x is not supported"),
        ("set -o", "-o needs an option name"),
        ("set -o noclobber", "-o noclobber is not supported"),
        ("set --", "sets positional parameters"),
        ("set nope", "is not an option"),
    ] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{script}");
        assert!(
            outcome.output.contains(expected),
            "{script}: {}",
            outcome.output
        );
    }
    // The long spellings of the three that are real do work.
    assert_eq!(code("set -o errexit\nnosuchcmd"), 127);
    assert_eq!(code("set -o nounset\necho $missing"), 1);
}

// ---------------------------------------------------------------------------
// `[[ ... ]]`
// ---------------------------------------------------------------------------

#[test]
fn double_brackets_run_the_same_tests_single_ones_do() {
    // Same code underneath, so the two spellings can never disagree about an operator.
    for (double, single) in [
        ("[[ -n x ]]", "[ -n x ]"),
        ("[[ -z \"\" ]]", "[ -z \"\" ]"),
        ("[[ a = a ]]", "[ a = a ]"),
        ("[[ a != b ]]", "[ a != b ]"),
        ("[[ 2 -lt 10 ]]", "[ 2 -lt 10 ]"),
        ("[[ ! -n \"\" ]]", "[ ! -n \"\" ]"),
    ] {
        assert_eq!(code(double), code(single), "{double} vs {single}");
        assert_eq!(code(double), 0, "{double}");
    }
    assert_eq!(code("[[ -n \"\" ]]"), 1);
}

#[test]
fn double_brackets_add_the_connectives_single_ones_lack() {
    assert_eq!(output("[[ -n a && -n b ]] && echo both"), "both");
    assert_eq!(output("[[ -z a || -n b ]] && echo either"), "either");
    assert_eq!(
        output("[[ ! ( -n a && -z b ) ]] && echo grouped"),
        "grouped"
    );
    assert_eq!(
        output("x=5\n[[ $x -gt 1 && $x -lt 10 ]] && echo between"),
        "between"
    );
    // `&&` short-circuits, so the right side is never evaluated for an unset name.
    assert_eq!(
        output("[[ -n \"$missing\" && $missing -eq 1 ]] || echo skipped"),
        "skipped"
    );
    // And it composes into the constructs that take a condition.
    assert_eq!(output("if [[ -n x ]]; then echo yes; fi"), "yes");
    assert_eq!(
        output("i=0\nwhile [[ $i -lt 2 ]]; do echo $i; i=$(( i + 1 )); done"),
        "0\n1"
    );
}

#[test]
fn an_unquoted_expansion_inside_double_brackets_is_one_word() {
    // The promise `[[ ]]` makes over `[ ]`: a value that spreads into several words elsewhere is
    // still one operand here.
    assert_eq!(
        output(
            r#"v=$(probe object --a "one two" | jq '[.a]')
[[ -n $v ]] && echo held"#
        ),
        "held"
    );
}

#[test]
fn comparison_operands_inside_double_brackets_stay_literal() {
    // In bash the right operand of `==` is a glob. Comparing it literally would answer this
    // wrongly and silently, so the metacharacter is named instead.
    let outcome = run("f=report.json\n[[ $f == *.json ]] && echo matched");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("glob in bash"), "{outcome:?}");
    assert!(!outcome.output.contains("matched"), "{outcome:?}");

    // Quoting is the way through while the parser can still see it.
    assert_eq!(output("f='*'\n[[ $f == '*' ]] && echo literal"), "literal");
    // One assembled at run time is caught when it expands.
    let outcome = run("p='*.json'\nf=report.json\n[[ $f == $p ]] && echo matched");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("quoting cannot exempt"),
        "{outcome:?}"
    );

    // Regex matching names itself rather than being read as a string comparison.
    let outcome = run("[[ abc =~ a.c ]]");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("regex matching"), "{outcome:?}");
}

#[test]
fn a_malformed_double_bracket_condition_names_what_is_wrong() {
    assert!(run("[[ -n x ").output.contains("expected `]]`"));
    assert!(run("[[ ]]").output.contains("expected a condition"));
    assert!(
        run("[[ a b c d ]]")
            .output
            .contains("at most three operands")
    );
    assert!(run("[[ ( -n x ]]").output.contains("expected `)`"));
    // File tests stay refused, with the same message `test` gives.
    assert!(run("[[ -f x ]]").output.contains("no filesystem"));
}

// ---------------------------------------------------------------------------
// Compound commands as pipeline stages
// ---------------------------------------------------------------------------

#[test]
fn a_compound_command_can_be_a_pipeline_stage() {
    // The shape this whole change exists for. `cat` inside the loop body reads the value piped
    // into the loop, which is the same rule a function body already followed.
    assert_eq!(
        output(
            r#"probe object --a 1 | while [ -n "$(cat | jq -r .a)" ]; do echo saw; break; done"#
        ),
        "saw"
    );
    assert_eq!(
        output(
            "probe object --a 1 | if [ $(cat | jq -r .a) -eq 1 ]; then echo yes; else echo no; fi"
        ),
        "yes"
    );
    assert_eq!(
        output(
            "probe object --a 1 --b 2 | case $(cat | jq -r .a) in 1) echo one ;; *) echo other ;; esac"
        ),
        "one"
    );
}

#[test]
fn a_piped_compound_stage_keeps_the_variables_it_assigns() {
    // bash runs this in a subshell and throws the assignment away, which is the single most
    // notorious trap in the language. There are no subshells here, so it simply works — and a
    // model writing the obvious thing gets the obvious result.
    assert_eq!(
        output(
            r#"total=0
probe object --a 7 | while [ $total -eq 0 ]; do total=$(cat | jq -r .a); done
echo $total"#
        ),
        "7"
    );
}

#[test]
fn a_compound_stage_feeding_a_pipe_collects_everything_it_emitted() {
    // Each statement inside emits separately, so without collecting them the next stage would see
    // only the last one.
    assert_eq!(output("{ echo a; echo b; } | wc -l"), "2");
    assert_eq!(output("for x in 1 2 3; do echo $x; done | wc -l"), "3");
    assert_eq!(output("{ echo a; echo b; } > buf\ncat buf | wc -l"), "2");
}

#[test]
fn a_brace_group_runs_in_the_current_scope_and_is_one_branch() {
    // The idiom braces exist for.
    let outcome = run("nosuchcmd || { echo handled; exit 3; }\necho unreachable");
    assert_eq!(outcome.exit_code.get(), 3);
    assert!(outcome.output.contains("handled"), "{outcome:?}");
    assert!(!outcome.output.contains("unreachable"), "{outcome:?}");

    // No subshell, so an assignment inside is still an assignment outside.
    assert_eq!(output("{ x=inside; }\necho $x"), "inside");
    // A group reports the status of its last command, like bash.
    assert_eq!(output("{ true; false; } && echo yes || echo no"), "no");
}

#[test]
fn an_empty_or_unterminated_group_is_a_parse_error_naming_itself() {
    assert!(run("{ }").output.contains("empty `{ }` group"));
    assert!(run("{ echo hi").output.contains("expected `}`"));
}

#[test]
fn a_compound_stage_carries_its_own_redirections() {
    let outcome = run("{ nosuchone; nosuchtwo; } 2> log\necho ---\ncat log | wc -l");
    let (before, after) = outcome.output.split_once("---").expect("the marker");
    assert!(!before.contains("command not found"), "{before:?}");
    assert_eq!(after.trim(), "2");
}

// ---------------------------------------------------------------------------
// Parameter expansion
// ---------------------------------------------------------------------------

#[test]
fn default_and_alternate_expansions_follow_bash_including_the_colon() {
    assert_eq!(output("echo ${missing:-fallback}"), "fallback");
    assert_eq!(output("x=set\necho ${x:-fallback}"), "set");
    // The colon is the whole distinction: `:-` also substitutes for a name holding nothing,
    // `-` only for a name nothing ever assigned.
    assert_eq!(output("x=\necho ${x:-fallback}"), "fallback");
    assert_eq!(output("x=\necho \"[${x-fallback}]\""), "[]");

    assert_eq!(output("x=set\necho ${x:+present}"), "present");
    assert_eq!(output("echo \"[${missing:+present}]\""), "[]");

    // A default may itself be an expansion, and a bare substitution keeps its structure.
    assert_eq!(output("y=inner\necho ${x:-$y}"), "inner");
    assert_eq!(
        output("v=${x:-$(probe object --a 1)}\necho ${v[a]}"),
        "1",
        "a bare substitution default keeps its structure"
    );
}

#[test]
fn a_whole_right_hand_side_expansion_keeps_the_value_it_names() {
    // `copy=$obj` has to keep the object, or the very indexing this value model exists for stops
    // surviving one assignment.
    assert_eq!(
        output("obj=$(probe object --a 1)\ncopy=$obj\necho ${copy[a]}"),
        "1"
    );
    // Glued to anything else it is text again, as it must be.
    assert_eq!(
        output("obj=$(probe object --a 1)\njoined=x$obj\necho $joined"),
        r#"x{"a":1}"#
    );
}

#[test]
fn assign_expansion_binds_the_name_it_substituted_for() {
    assert_eq!(output("echo ${x:=first}\necho $x"), "first\nfirst");
    assert_eq!(output("x=kept\necho ${x:=other}\necho $x"), "kept\nkept");
    // Assigning *through* an index has nowhere to write, so it says so rather than dropping the
    // write on the floor.
    let outcome = run("obj=$(probe object --a 1)\necho ${obj[b]:=x}");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("cannot assign through an index"));
}

#[test]
fn a_required_expansion_ends_the_script_rather_than_carrying_on_empty() {
    // The point of `${x:?}` is to stop. Reporting a status and continuing with an empty string
    // would leave a script believing it had the value it just asserted it needed.
    let outcome = run("echo ${token:?no credential in scope}\necho after");
    assert_eq!(outcome.exit_code, ExitCode::FAILURE);
    assert!(
        outcome.output.contains("token: no credential in scope"),
        "{outcome:?}"
    );
    assert!(!outcome.output.contains("after"), "{outcome:?}");

    assert_eq!(output("token=ok\necho ${token:?missing}"), "ok");
    // Without a message of its own it still names the parameter.
    assert!(
        run("echo ${token:?}")
            .output
            .contains("token: parameter is not set")
    );
}

#[test]
fn length_counts_what_the_value_actually_is() {
    assert_eq!(output("x=hello\necho ${#x}"), "5");
    assert_eq!(output("echo ${#missing}"), "0");
    // Real JSON, so an array counts elements and an object counts keys — a string's character
    // count would be an answer about its JSON text rather than about the value.
    assert_eq!(output("obj=$(probe object --a 1 --b 2)\necho ${#obj}"), "2");
    // Characters, not bytes.
    assert_eq!(output("x=héllo\necho ${#x}"), "5");
}

#[test]
fn prefix_suffix_and_replacement_operate_on_literal_text() {
    assert_eq!(output("p=owner/repo\necho ${p#owner/}"), "repo");
    assert_eq!(output("p=owner/repo\necho ${p%/repo}"), "owner");
    // A pattern that does not match leaves the value alone, as bash does.
    assert_eq!(output("p=owner/repo\necho ${p#nope}"), "owner/repo");
    // The doubled forms are the same request: a literal pattern matches in exactly one way.
    assert_eq!(output("p=owner/repo\necho ${p##owner/}"), "repo");
    assert_eq!(output("p=owner/repo\necho ${p%%/repo}"), "owner");

    assert_eq!(output("p=a-b-c\necho ${p/-/+}"), "a+b-c");
    assert_eq!(output("p=a-b-c\necho ${p//-/+}"), "a+b+c");
    assert_eq!(output("p=a-b\necho ${p//-}"), "ab");
}

#[test]
fn a_metacharacter_in_an_expansion_pattern_is_rejected_rather_than_matched_literally() {
    // Same rule as a `grep`, `sed`, or `case` pattern, and for the same reason: a partial
    // wildcard is exactly what a literal matcher answers wrongly and silently.
    for script in ["p=a/b\necho ${p##*/}", "p=a.json\necho ${p%.*}"] {
        let outcome = run(script);
        assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{script}");
        assert!(outcome.output.contains("literal text"), "{script}");
    }
    // One assembled at run time is caught when it expands, where quoting can no longer help.
    let outcome = run("star='*'\np=a.json\necho ${p%$star}");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("quoting cannot exempt"),
        "{outcome:?}"
    );
    // Quoting is the way through, as everywhere else.
    assert_eq!(output("p='*.json'\necho ${p#'*'}"), ".json");
}

#[test]
fn nested_parameter_expansions_have_a_ceiling_rather_than_a_stack_overflow() {
    let deep = format!("echo {}x{}", "${a:-".repeat(200), "}".repeat(200));
    let outcome = run(&deep);
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(outcome.output.contains("nested deeper"), "{outcome:?}");
}

// ---------------------------------------------------------------------------
// The two streams
// ---------------------------------------------------------------------------

#[test]
fn a_redirected_stderr_leaves_the_combined_output() {
    // The diagnostic is real — the exit code proves the command failed — but the script asked for
    // it to go somewhere else, and it went there.
    let outcome = run("nosuchcmd 2>/dev/null\necho done");
    assert_eq!(outcome.output, "done");
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);

    assert_eq!(code("nosuchcmd 2>/dev/null"), 127);
}

#[test]
fn stderr_redirects_into_a_named_buffer_that_cat_reads_back() {
    let outcome = run("nosuchcmd 2> log\necho ---\ncat log");
    assert!(!outcome.output.starts_with("dekopon-shell:"), "{outcome:?}");
    let (before, after) = outcome.output.split_once("---").expect("the marker");
    assert!(!before.contains("command not found"), "{before:?}");
    assert!(after.contains("command not found"), "{after:?}");
}

#[test]
fn a_value_sent_to_stderr_escapes_a_command_substitution() {
    // `echo oops >&2` is how a script reports a problem without polluting what it returns. The
    // line still reaches the reader; it just stops being the substitution's value.
    let outcome = run(r#"x=$(echo oops >&2; echo kept)
echo "[$x]""#);
    assert!(outcome.output.contains("oops"), "{outcome:?}");
    assert!(outcome.output.contains("[kept]"), "{outcome:?}");
}

#[test]
fn two_to_one_merges_diagnostics_into_the_value_a_substitution_captures() {
    // The idiom this exists for: capture *why* something failed, not just that it did.
    let outcome = run(r#"x=$(nosuchcmd 2>&1)
echo "[$x]""#);
    assert!(outcome.output.contains("command not found]"), "{outcome:?}");
}

#[test]
fn two_to_one_leaves_a_quiet_command_s_value_and_its_type_alone() {
    // Merging is what a *diagnostic* forces; with none there is nothing to merge, and an object
    // must not be flattened into its own JSON text just because `2>&1` was written.
    assert_eq!(output("echo hi 2>&1"), "hi");
    assert_eq!(
        output("probe object --a 1 2>&1 | jq -r .a"),
        "1",
        "a quiet provider command keeps its object"
    );
}

#[test]
fn both_streams_can_land_in_one_buffer() {
    let outcome = run("nosuchcmd > out 2>&1\ncat out");
    assert!(outcome.output.contains("command not found"), "{outcome:?}");

    let outcome = run("echo hi &> all\ncat all");
    assert_eq!(outcome.output, "hi");
}

#[test]
fn dev_null_discards_on_write_and_reads_empty() {
    assert_eq!(output("echo hi > /dev/null\necho after"), "after");
    assert_eq!(output("cat /dev/null"), "");
    // And it needs no prior write, unlike every other buffer name.
    assert!(output("cat nosuchbuffer").contains("no such buffer"));
}

#[test]
fn a_redirection_covers_the_whole_body_of_the_function_it_is_written_on() {
    let outcome = run(
        "noisy() { nosuchone; nosuchtwo; echo value; }\nnoisy 2> log\necho ---\ncat log | wc -l",
    );
    let (before, after) = outcome.output.split_once("---").expect("the marker");
    assert!(!before.contains("command not found"), "{before:?}");
    assert_eq!(after.trim(), "2", "both diagnostics were collected");
}

#[test]
fn a_fatal_diagnostic_is_never_swallowed_by_a_redirection() {
    // The script is ending and the capture is about to be abandoned. If `2>` could eat this line,
    // a model would see an empty result with no explanation at all.
    let outcome = run_with(
        "loop() { loop; }\nloop 2>/dev/null",
        Limits {
            max_recursion_depth: 4,
            ..Limits::default()
        },
    );
    assert!(outcome.output.contains("nested deeper"), "{outcome:?}");
}

#[test]
fn a_redirection_target_still_has_to_be_one_word() {
    // An unquoted expansion holding a JSON array is what produces several words here; there is no
    // IFS to split a string on.
    let outcome = run("x=$(probe object --a one --b two | jq '[.a,.b]')\necho hi > $x");
    assert_ne!(outcome.exit_code, ExitCode::SUCCESS);
    assert!(
        outcome.output.contains("exactly one buffer name"),
        "{outcome:?}"
    );
}

#[test]
fn shell_shapes_this_interpreter_cannot_honor_are_rejected_by_their_own_name() {
    // Each of these used to succeed quietly, or fail while naming the wrong feature. The message
    // has to identify what the script actually wrote, or it sends a reader to the wrong fix.
    for (script, expected) in [
        // Backticks: the second-most-common substitution form in real bash.
        ("echo `echo hi`", "backtick command substitution"),
        ("x=`date`", "backtick command substitution"),
        // Descriptors beyond the two streams that exist.
        ("echo hi 3>/dev/null", "only descriptors 1"),
        ("cat 0< buf", "input duplication"),
        // A shell option this shell does not enforce is refused by name rather than accepted and
        // ignored, which is the failure that kept `set` out entirely before.
        ("set -x\necho after", "option -x is not supported"),
        (
            "set -o noclobber\necho after",
            "-o noclobber is not supported",
        ),
        // Paren-shaped constructs are four different features, not one subshell.
        ("i=0; ((i++))", "arithmetic command"),
        ("arr=(a b c)", "bash array literals"),
        ("for ((i=0; i<3; i++)); do echo $i; done", "C-style"),
        ("(echo hi)", "subshells"),
        // Arithmetic operators name themselves rather than a stray character.
        ("echo $((2 ** 3))", "`**` is not supported"),
        ("echo $((i++))", "`++` is not supported"),
        ("echo $((i += 2))", "compound assignment"),
        ("echo $(( 1 > 0 ? 5 : 6 ))", "ternary"),
        ("echo $(( 1 & 2 ))", "bitwise"),
    ] {
        let outcome = run(script);
        assert_ne!(outcome.exit_code, ExitCode::SUCCESS, "{script}");
        assert!(
            outcome.output.contains(expected),
            "{script}: {}",
            outcome.output
        );
        assert!(!outcome.output.contains("after"), "{script}: ran anyway");
    }
}

#[test]
fn a_non_ascii_character_in_arithmetic_is_named_as_itself() {
    // Casting the raw byte reported 'Ã', the first UTF-8 byte of 'é' — a character the script
    // never wrote, in a project whose diagnostics are the product.
    let outcome = run("echo $(( 1 é 2 ))");
    assert!(outcome.output.contains("'é'"), "{}", outcome.output);
}

#[test]
fn a_text_builtin_that_selected_nothing_emits_nothing() {
    // An empty result used to render as a blank line, which also spent a line of the ceiling.
    assert_eq!(
        output("echo start; echo a | grep zzz; echo end"),
        "start\nend"
    );
    assert_eq!(
        output("echo start; echo a | grep zzz | wc -l; echo end"),
        "start\n0\nend"
    );
}

// ---------------------------------------------------------------------------
// Sandbox limits
// ---------------------------------------------------------------------------

#[test]
fn the_step_budget_stops_an_unbounded_loop() {
    let outcome = run_with(
        "while true; do x=1; done",
        Limits {
            max_steps: 500,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("step budget exhausted"),
        "{}",
        outcome.output
    );
    assert!(outcome.steps <= 501);
}

#[test]
fn the_recursion_cap_stops_runaway_shell_functions() {
    let outcome = run_with(
        "recurse() { recurse; }\nrecurse",
        Limits {
            max_recursion_depth: 16,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("nested deeper"),
        "{}",
        outcome.output
    );
}

#[test]
fn the_capability_call_cap_is_independent_of_the_step_budget() {
    let outcome = run_with(
        "for i in 1 2 3 4 5; do probe upper --text $i; done",
        Limits {
            max_capability_calls: 2,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert_eq!(outcome.capability_calls, 2);
    assert!(
        outcome.output.contains("more than 2 capability calls"),
        "{}",
        outcome.output
    );
}

#[test]
fn deeply_nested_input_is_a_syntax_error_rather_than_a_dead_process() {
    // Every recursive production runs on the native stack before any budget exists, so an
    // unbounded one aborts the process with SIGABRT — no exit code, no outcome, no audit line.
    // `Interpreter::run` documents that a script failure is a script *outcome*; these prove it.
    for script in [
        // `$(( ( ( ... ) ) ))`: ArithParser::parse_primary re-enters the precedence chain.
        format!("echo $(( {}1{} ))", "(".repeat(4_000), ")".repeat(4_000)),
        // `$( $( ... ) )`: convert_part re-enters the whole parser.
        format!("echo {}echo hi{}", "$(".repeat(2_000), ")".repeat(2_000)),
        // `if ... then`: parse_if re-enters parse_program.
        format!(
            "{}echo x{}",
            "if true; then ".repeat(2_000),
            "; fi".repeat(2_000)
        ),
        // The same nesting reached through an index expression.
        format!(
            "echo ${{name[{}echo 1{}]}}",
            "$(".repeat(1_000),
            ")".repeat(1_000)
        ),
    ] {
        let outcome = run(&script);
        assert_eq!(
            outcome.exit_code,
            ExitCode::SYNTAX,
            "{}",
            &script[..script.len().min(60)]
        );
        assert!(
            outcome.output.contains("syntax error"),
            "{}",
            outcome.output
        );
    }
    // Ordinary nesting is untouched by the ceiling.
    assert_eq!(output("echo $(( ((((1 + 1)))) ))"), "2");
    assert_eq!(output("echo $(echo $(echo $(echo deep)))"), "deep");
}

#[test]
fn the_value_byte_ceiling_stops_runaway_string_growth() {
    // Doubling a string is one cheap step and twice the memory, so every ceiling that counts
    // operations leaves memory unbounded: 26 of these lines reach a gigabyte in 250 steps.
    let outcome = run_with(
        "x=aaaaaaaaaaaaaaaa\ni=0\nwhile [ $i -lt 30 ]; do x=\"$x$x\"; i=$(( i + 1 )); done\necho done",
        Limits {
            max_value_bytes: 64 * 1024,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("bytes of values"),
        "{}",
        outcome.output
    );
    assert!(!outcome.output.contains("done"), "{}", outcome.output);

    // A named buffer written in a loop is the same amplification through a different door.
    let outcome = run_with(
        "x=aaaaaaaaaaaaaaaa\ni=0\nwhile [ $i -lt 30 ]; do x=\"$x$x\"; echo $x > buf; i=$(( i + 1 )); done",
        Limits {
            max_value_bytes: 64 * 1024,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);

    // A realistic script stays far inside the default ceiling.
    assert_eq!(
        run("x=hello; y=\"$x $x\"; echo $y").exit_code,
        ExitCode::SUCCESS
    );
}

#[test]
fn the_deadline_bounds_slow_capability_calls_not_only_long_scripts() {
    /// An invoker whose calls cost wall clock rather than steps, like a real provider.
    struct Slow;

    impl CapabilityInvoker for Slow {
        fn granted(&self) -> Vec<String> {
            vec!["slow.call".to_owned()]
        }

        fn has_command_word(&self, word: &str) -> bool {
            word == "slow"
        }

        fn run_command(
            &self,
            word: &str,
            _argv: &[String],
            _stdin: Option<&str>,
        ) -> Option<CommandRun> {
            (word == "slow").then(|| proposal("slow.call", json!({})))
        }

        fn invoke(
            &self,
            _capability: &str,
            input: Value,
            _secret_use: Option<dekopon_core::SecretUseProposal>,
        ) -> CapabilityCallResult {
            std::thread::sleep(Duration::from_millis(20));
            CapabilityCallResult::Succeeded(input)
        }
    }

    // A few steps per command line times the 32-call default budget stays under 128 steps, so a
    // clock sampled every 128th step was structurally unreachable for the workload that most needs
    // it: a straight-line script of slow calls used to overrun its deadline and report success.
    let script = "slow call\n".repeat(32);
    let outcome = Interpreter::new(Limits {
        timeout: Duration::from_millis(60),
        ..Limits::default()
    })
    .run(&script, &Slow);
    assert_eq!(outcome.exit_code, ExitCode::TIMEOUT, "{}", outcome.output);
    assert!(
        outcome.capability_calls < 32,
        "{}",
        outcome.capability_calls
    );
    assert!(outcome.steps < 128, "{}", outcome.steps);
}

#[test]
fn the_wall_clock_deadline_reports_exit_code_124() {
    let outcome = run_with(
        "sleep 30",
        Limits {
            timeout: Duration::from_millis(20),
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::TIMEOUT);
    assert!(outcome.output.contains("deadline"), "{}", outcome.output);
}

#[test]
fn output_ceilings_truncate_keeping_head_and_tail() {
    let outcome = run_with(
        "i=0\nwhile [ $i -lt 60 ]; do echo line-$i; i=$(( i + 1 )); done",
        Limits {
            max_output_lines: 10,
            ..Limits::default()
        },
    );
    assert!(outcome.truncated);
    assert!(outcome.output.starts_with("line-0\n"), "{}", outcome.output);
    assert!(outcome.output.ends_with("line-59"), "{}", outcome.output);
    assert!(
        outcome.output.contains("Output truncated"),
        "{}",
        outcome.output
    );
    // A truncated script still completes; truncation is not a failure.
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
}

#[test]
fn a_single_oversized_line_cannot_bypass_the_byte_ceiling() {
    let outcome = run_with(
        "echo start\nx=$(echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\necho \"$x$x$x$x\"",
        Limits {
            max_output_bytes: 64,
            max_output_lines: 100_000,
            ..Limits::default()
        },
    );
    assert!(outcome.truncated);
    assert!(outcome.output.len() < 400, "{}", outcome.output);
}

// ---------------------------------------------------------------------------
// Provider command words
// ---------------------------------------------------------------------------

#[test]
fn a_provider_command_help_page_is_stdout_exit_0_and_capturable() {
    let fixture = Fixture::default();
    let outcome = Interpreter::new(Limits::default()).run("probe --help", &fixture);
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);
    // One trailing newline folds into the value model; printing adds it back exactly once.
    assert_eq!(
        outcome.output,
        "Usage: probe <COMMAND>\n\nCommands:\n  upper  Uppercase text"
    );
    assert_eq!(outcome.capability_calls, 0);
    assert!(
        fixture.calls.borrow().is_empty(),
        "help invoked a capability"
    );

    let captured = run("h=$(probe --help); echo \"[$?]\"; echo \"$h\"");
    assert_eq!(
        captured.output,
        "[0]\nUsage: probe <COMMAND>\n\nCommands:\n  upper  Uppercase text"
    );
    assert_eq!(captured.capability_calls, 0);
}

#[test]
fn a_provider_command_usage_error_is_a_diagnostic_with_exit_2() {
    let outcome = run("x=$(probe bogus); echo \"[$x] $?\"");
    assert_eq!(
        outcome.output,
        "error: unrecognized subcommand 'bogus'\n\nUsage: probe <COMMAND>\n[] 2"
    );
    assert_eq!(outcome.capability_calls, 0);
    // Diagnostics stay on the diagnostic stream, so `2>` redirects them like any other.
    assert_eq!(
        output("probe bogus 2> log; echo \"status $?\"; cat log"),
        "status 2\nerror: unrecognized subcommand 'bogus'\n\nUsage: probe <COMMAND>"
    );
}

#[test]
fn a_provider_command_reads_piped_text_verbatim_and_values_as_json() {
    let fixture = Fixture::default();
    let outcome = Interpreter::new(Limits::default()).run(
        "echo hello | probe upper -\nprobe object --a 1 | probe upper -\nprobe upper --text flag",
        &fixture,
    );
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
    assert_eq!(
        *fixture.calls.borrow(),
        vec![
            ("cli-probe.upper".to_owned(), json!({"text": "hello"})),
            // The producer of the object, then the object as the provider saw it: compact JSON.
            ("fixture.object".to_owned(), json!({"a": 1})),
            ("cli-probe.upper".to_owned(), json!({"text": "{\"a\":1}"})),
            ("cli-probe.upper".to_owned(), json!({"text": "flag"})),
        ]
    );
    assert_eq!(outcome.capability_calls, 4);
    // Nothing piped is `None`, not an empty string: the provider can tell the two apart.
    assert_eq!(
        output("probe upper -; echo $?"),
        "probe: no input was piped for -\n2"
    );
}

#[test]
fn a_provider_command_proposal_still_needs_the_grant() {
    let fixture = Fixture::default();
    let outcome = Interpreter::new(Limits::default()).run("probe ungranted", &fixture);
    assert_eq!(outcome.exit_code, ExitCode::NOT_FOUND);
    assert_eq!(
        outcome.output,
        "dekopon-shell: probe: requires capability nothing.granted, which is not granted in this \
         session"
    );
    assert!(
        fixture.calls.borrow().is_empty(),
        "an ungranted proposal ran"
    );
    assert_eq!(outcome.capability_calls, 0);
}

#[test]
fn a_provider_command_decline_is_a_usage_error() {
    let outcome = run("probe decline");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert_eq!(outcome.output, "probe: declined");
    assert_eq!(outcome.capability_calls, 0);
}

/// A run that never reached the provider's answer takes the exit codes a capability call takes
/// for the same two facts, so the model reads "retry later" or "stop" rather than "fix the argv".
#[test]
fn a_command_run_that_errored_or_was_refused_is_not_a_usage_error() {
    let errored = run("probe errored; echo $?");
    assert_eq!(
        errored.output,
        "probe: failed: could not connect to broker socket\n1"
    );
    assert_eq!(errored.capability_calls, 0);

    let refused = run("probe cancelled; echo $?");
    assert_eq!(refused.output, "probe: denied: session-cancelled\n126");
    assert_eq!(refused.capability_calls, 0);
}

#[test]
fn a_rendered_page_charges_no_capability_call() {
    let outcome = run_with(
        "probe --help > page\nprobe --help > page\nprobe upper --text once\necho $?",
        Limits {
            max_capability_calls: 1,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
    assert_eq!(outcome.output, "{\"text\":\"ONCE\"}\n0");
    assert_eq!(outcome.capability_calls, 1);
}

#[test]
fn rendered_output_obeys_the_output_ceiling() {
    let outcome = run_with(
        "probe --help",
        Limits {
            max_output_bytes: 16,
            max_output_lines: 100_000,
            ..Limits::default()
        },
    );
    assert!(outcome.truncated, "{}", outcome.output);
    assert!(
        outcome.output.contains("Output truncated"),
        "{}",
        outcome.output
    );
    // Rendered bytes also count as materialized value bytes, like anything a script holds.
    let outcome = run_with(
        "probe --help",
        Limits {
            max_value_bytes: 16,
            ..Limits::default()
        },
    );
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX, "{}", outcome.output);
    assert!(
        outcome.output.contains("bytes of values"),
        "{}",
        outcome.output
    );
}

#[test]
fn the_process_environment_never_leaks_into_a_script() {
    // `PATH` is genuinely set in this test process, so reading it back as empty proves isolation
    // rather than merely proving that some arbitrary name is unset. (`std::env::set_var` is unsafe
    // under edition 2024 and this crate forbids `unsafe`; the runner's black-box CLI test sets a
    // real custom variable on a child process to cover that angle too.)
    assert!(
        std::env::var_os("PATH").is_some(),
        "this test is only meaningful when PATH is set in the host process"
    );
    let outcome = run(r#"echo "[$PATH]"; echo "[$HOME]"; echo "[$OPENAI_API_KEY]""#);
    assert_eq!(outcome.output, "[]\n[]\n[]");
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS);

    // Only the script's own assignments seed the namespace.
    assert_eq!(run(r#"PATH=mine; echo "[$PATH]""#).output, "[mine]");
}

#[test]
fn a_normal_multi_step_script_fits_comfortably_in_the_defaults() {
    // A realistic 5-to-10-step plan with nested loops must not trip any default ceiling.
    let script = "\
summarize() {
  local total=0
  for item in $@; do
    total=$(( total + item ))
  done
  echo $total
}

results=''
for group in 1 2 3; do
  inner=0
  while [ $inner -lt 3 ]; do
    r=$(probe object --group $group --inner $inner)
    echo ${r[group]}-${r[inner]}
    inner=$(( inner + 1 ))
  done
done
summarize 1 2 3 4
cap --list | jq length";
    let outcome = run(script);
    assert_eq!(outcome.exit_code, ExitCode::SUCCESS, "{}", outcome.output);
    assert!(!outcome.truncated, "{}", outcome.output);
    assert_eq!(outcome.capability_calls, 9);
    assert!(outcome.output.contains("1-0"), "{}", outcome.output);
    assert!(outcome.output.contains("3-2"), "{}", outcome.output);
    assert!(outcome.output.contains("10"), "{}", outcome.output);
    // The fixture grants six capabilities.
    assert!(
        outcome.output.trim_end().ends_with('6'),
        "{}",
        outcome.output
    );
}

#[test]
fn a_syntax_error_reports_exit_code_two_without_running_anything() {
    let outcome = run("echo before\nif true; then echo hi");
    assert_eq!(outcome.exit_code, ExitCode::SYNTAX);
    assert!(
        outcome.output.contains("syntax error"),
        "{}",
        outcome.output
    );
    assert!(!outcome.output.contains("before"), "{}", outcome.output);
}