bashkit 0.20.1

Awesomely fast virtual sandbox with bash and file system
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
//! Top-level integration tests for the jq builtin.
//!
//! Submodules also have their own unit tests (args parsing, format,
//! errors, conversion). This module tests the wired-up behavior end-to-end
//! through `Jq::execute` — covering positive, negative, and security cases.

use super::*;
use crate::builtins::{Context, test_stream};
use crate::error::Error;
use crate::fs::{FileSystem, InMemoryFs};
use crate::interpreter::ExecResult;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

async fn run_jq(filter: &str, input: &str) -> Result<String> {
    run_jq_with_args(&[filter], input).await
}

async fn run_jq_with_args(args: &[&str], input: &str) -> Result<String> {
    let result = run_jq_result_with_args(args, input).await?;
    Ok(result.stdout.to_string())
}

async fn run_jq_result(filter: &str, input: &str) -> Result<ExecResult> {
    run_jq_result_with_args(&[filter], input).await
}

async fn run_jq_result_with_args(args: &[&str], input: &str) -> Result<ExecResult> {
    let jq = Jq;
    let fs = Arc::new(InMemoryFs::new());
    let mut vars = HashMap::new();
    let mut cwd = PathBuf::from("/");
    let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();

    let ctx = Context {
        args: &args,
        env: &HashMap::new(),
        variables: &mut vars,
        cwd: &mut cwd,
        fs,
        stdin: Some(test_stream(input)),
        #[cfg(feature = "http_client")]
        http_client: None,
        #[cfg(feature = "git")]
        git_client: None,
        #[cfg(feature = "ssh")]
        ssh_client: None,
        shell: None,
    };

    jq.execute(ctx).await
}

async fn run_jq_with_files(
    args: &[&str],
    files: &[(&str, &str)],
) -> std::result::Result<ExecResult, Error> {
    let jq = Jq;
    let fs = Arc::new(InMemoryFs::new());
    for (path, content) in files {
        let p = std::path::Path::new(path);
        if let Some(parent) = p.parent()
            && parent != std::path::Path::new("/")
        {
            fs.mkdir(parent, true).await.unwrap();
        }
        fs.write_file(p, content.as_bytes()).await.unwrap();
    }
    let mut vars = HashMap::new();
    let mut cwd = PathBuf::from("/");
    let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();

    let ctx = Context {
        args: &args,
        env: &HashMap::new(),
        variables: &mut vars,
        cwd: &mut cwd,
        fs,
        stdin: None,
        #[cfg(feature = "http_client")]
        http_client: None,
        #[cfg(feature = "git")]
        git_client: None,
        #[cfg(feature = "ssh")]
        ssh_client: None,
        shell: None,
    };

    jq.execute(ctx).await
}

// =========================================================================
// Identity / basic filter tests
// =========================================================================

#[tokio::test]
async fn identity_pretty_prints_object() {
    let result = run_jq(".", r#"{"name":"test"}"#).await.unwrap();
    assert_eq!(result.trim(), "{\n  \"name\": \"test\"\n}");
}

#[tokio::test]
async fn field_access() {
    let result = run_jq(".name", r#"{"name":"foo","id":42}"#).await.unwrap();
    assert_eq!(result.trim(), r#""foo""#);
}

#[tokio::test]
async fn array_index() {
    let result = run_jq(".[1]", r#"["a","b","c"]"#).await.unwrap();
    assert_eq!(result.trim(), r#""b""#);
}

#[tokio::test]
async fn nested_field() {
    let result = run_jq(".user.name", r#"{"user":{"name":"alice"}}"#)
        .await
        .unwrap();
    assert_eq!(result.trim(), r#""alice""#);
}

#[tokio::test]
async fn keys_pretty_prints_array() {
    let result = run_jq("keys", r#"{"b":1,"a":2}"#).await.unwrap();
    assert_eq!(result.trim(), "[\n  \"a\",\n  \"b\"\n]");
}

// jq deliberately accepts literal U+0000..U+001F bytes inside input strings.
// This compatibility exception belongs only to jq's input boundary; output is
// always valid JSON with the controls escaped.
#[tokio::test]
async fn literal_controls_inside_strings_are_escaped() {
    let controls: String = (0u8..=0x1f).map(char::from).collect();
    let input = format!("\"before{controls}after\"");
    let result = run_jq_with_args(&["-c", "."], &input).await.unwrap();
    assert_eq!(
        result,
        format!(
            "{}\n",
            serde_json::to_string(&format!("before{controls}after")).unwrap()
        )
    );
}

#[tokio::test]
async fn literal_controls_preserve_adjacent_existing_escapes() {
    let input = "\"left\\n\t\\t\rright\"";
    let result = run_jq_with_args(&["-c", "explode"], input).await.unwrap();
    assert_eq!(result, "[108,101,102,116,10,9,9,13,114,105,103,104,116]\n");
}

#[tokio::test]
async fn literal_controls_work_across_concatenated_values() {
    let result = run_jq_with_args(&["-c", "."], "\"a\nb\"{\"c\":\"d\te\"}")
        .await
        .unwrap();
    assert_eq!(result, "\"a\\nb\"\n{\"c\":\"d\\te\"}\n");
}

#[tokio::test]
async fn literal_controls_work_in_ndjson_after_escaped_quote() {
    let result = run_jq_with_args(&["-c", "."], "\"a\\\"\tb\"\n\"c\rd\"\n")
        .await
        .unwrap();
    assert_eq!(result, "\"a\\\"\\tb\"\n\"c\\rd\"\n");
}

#[tokio::test]
async fn structural_whitespace_remains_structural() {
    let result = run_jq_with_args(&["-c", "."], "\t1\r\n 2\n").await.unwrap();
    assert_eq!(result, "1\n2\n");
}

#[tokio::test]
async fn non_whitespace_control_outside_string_is_rejected() {
    let result = run_jq_result(".", "1\u{0000}2").await.unwrap();
    assert_eq!(result.exit_code, 5);
    assert!(
        result.stderr.contains("invalid JSON"),
        "stderr={}",
        result.stderr
    );
}

#[tokio::test]
async fn unterminated_string_with_control_is_rejected_deterministically() {
    let first = run_jq_result(".", "\"unterminated\n").await.unwrap();
    let second = run_jq_result(".", "\"unterminated\n").await.unwrap();
    assert_eq!(first.exit_code, 5);
    assert_eq!(first.stderr, second.stderr);
    assert!(first.stderr.contains("unterminated string"));
    crate::builtins::debug_leak_check::assert_no_leak(
        &first,
        "unterminated jq input string",
        JQ_BANNED,
    );
}

#[tokio::test]
async fn literal_controls_work_for_file_and_slurpfile_inputs() {
    let direct = run_jq_with_files(&["-c", ".", "/input.json"], &[("/input.json", "\"a\nb\"")])
        .await
        .unwrap();
    assert_eq!(direct.stdout, "\"a\\nb\"\n");

    let slurped = run_jq_with_files(
        &["-nc", "--slurpfile", "data", "/input.json", "$data"],
        &[("/input.json", "\"a\nb\"\"c\td\"")],
    )
    .await
    .unwrap();
    assert_eq!(slurped.stdout, "[\"a\\nb\",\"c\\td\"]\n");
}

#[tokio::test]
async fn jq_argument_json_boundaries_remain_strict() {
    let argjson = run_jq_result_with_args(&["--argjson", "x", "\"a\nb\"", "-n", "$x"], "")
        .await
        .unwrap();
    assert_eq!(argjson.exit_code, 2);

    let jsonargs = run_jq_result_with_args(&["-n", ".", "--jsonargs", "\"a\nb\""], "")
        .await
        .unwrap();
    assert_eq!(jsonargs.exit_code, 2);
}

/// TM-DOS-093: an unbounded generator must not grow output without limit or
/// hang the host. jaq's iterator is synchronous so the execution timeout
/// cannot preempt it; the output-byte cap (here the 1 MB default, since the
/// test harness supplies no shell/limits) must abort with a clean error.
#[tokio::test]
async fn unbounded_generator_is_capped() {
    let result = run_jq_result_with_args(&["-n", "repeat(1)"], "")
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0, "runaway generator should fail");
    assert!(
        result.stderr.contains("output limit exceeded"),
        "expected output-limit error, got stderr={:?} stdout_len={}", // debug-ok: test assertion
        result.stderr,
        result.stdout.len()
    );
    assert!(
        result.stdout.len() <= 1_048_576 + 64,
        "output must be bounded by the cap, got {} bytes",
        result.stdout.len()
    );
}

#[tokio::test]
async fn length_returns_number() {
    let result = run_jq("length", r#"[1,2,3,4,5]"#).await.unwrap();
    assert_eq!(result.trim(), "5");
}

// =========================================================================
// Tier 1: --indent N
// =========================================================================

#[tokio::test]
async fn indent_4_uses_4_spaces() {
    let result = run_jq_with_args(&["--indent", "4", "."], r#"{"a":1,"b":[1,2]}"#)
        .await
        .unwrap();
    // Each nested line should use 4 spaces.
    assert!(result.contains("\n    \"a\": 1"), "stdout: {result}");
    assert!(result.contains("\n        1"), "nested array: {result}");
}

#[tokio::test]
async fn indent_0_renders_newlines_without_indent() {
    // jq >= 1.8: --indent 0 keeps the newlines and drops the spaces. Only -c
    // is compact.
    let result = run_jq_with_args(&["--indent", "0", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result, "{\n\"a\": 1\n}\n");
}

#[tokio::test]
async fn output_shape_flags_are_last_wins() {
    // -c, --tab and --indent N set the same thing, so the last one wins.
    let cases: [(&[&str], &str); 6] = [
        (&["-c", "--indent", "0", "."], "{\n\"a\": [\n1,\n2\n]\n}\n"),
        (&["--indent", "0", "-c", "."], "{\"a\":[1,2]}\n"),
        (
            &["-c", "--indent", "4", "."],
            "{\n    \"a\": [\n        1,\n        2\n    ]\n}\n",
        ),
        (&["--indent", "4", "-c", "."], "{\"a\":[1,2]}\n"),
        (&["--tab", "-c", "."], "{\"a\":[1,2]}\n"),
        (
            &["-c", "--tab", "."],
            "{\n\t\"a\": [\n\t\t1,\n\t\t2\n\t]\n}\n",
        ),
    ];
    for (args, expected) in cases {
        let result = run_jq_with_args(args, r#"{"a":[1,2]}"#).await.unwrap();
        assert_eq!(result, expected, "args: jq {}", args.join(" "));
    }
}

#[tokio::test]
async fn later_indent_overrides_tab() {
    // --tab used to stick regardless of a later --indent N.
    let result = run_jq_with_args(&["--tab", "--indent", "4", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result, "{\n    \"a\": 1\n}\n");
}

#[tokio::test]
async fn indent_too_large_rejected() {
    let result = run_jq_result_with_args(&["--indent", "8", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("--indent must be"));
}

#[tokio::test]
async fn indent_non_numeric_rejected() {
    let result = run_jq_result_with_args(&["--indent", "abc", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("expected a number"));
}

#[tokio::test]
async fn tab_uses_tab_characters() {
    let result = run_jq_with_args(&["--tab", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert!(result.contains("\n\t\"a\": 1"), "stdout: {result}");
}

// =========================================================================
// Tier 1: -e exit codes (1 vs 4 vs 5)
// =========================================================================

#[tokio::test]
async fn exit_status_false_returns_1() {
    let result = run_jq_result_with_args(&["-e", "."], "false")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 1);
}

#[tokio::test]
async fn exit_status_null_returns_1() {
    let result = run_jq_result_with_args(&["-e", "."], "null").await.unwrap();
    assert_eq!(result.exit_code, 1);
}

#[tokio::test]
async fn exit_status_no_output_returns_4() {
    // `empty` produces no output values at all — real jq returns 4 with -e.
    let result = run_jq_result_with_args(&["-e", "empty"], "1")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 4);
}

#[tokio::test]
async fn exit_status_truthy_returns_0() {
    let result = run_jq_result_with_args(&["-e", "."], "42").await.unwrap();
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn exit_status_last_value_wins() {
    // jq -e: the last output decides (here false -> 1).
    let result = run_jq_result_with_args(&["-e", ".[]"], "[null, 1, false]")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 1);
    let result = run_jq_result_with_args(&["-e", ".[]"], "[null, false, 1]")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
}

// =========================================================================
// Tier 1: unknown flags rejected
// =========================================================================

#[tokio::test]
async fn unknown_long_flag_errors() {
    let result = run_jq_result_with_args(&["--xyzzy", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("Unknown option --xyzzy"));
}

#[tokio::test]
async fn unknown_short_flag_errors() {
    let result = run_jq_result_with_args(&["-Z", "."], r#"{"a":1}"#)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("Unknown option -Z"));
}

// =========================================================================
// Tier 1: scan / @tsv / @csv compat
// =========================================================================

#[tokio::test]
async fn scan_default_global_no_double_g() {
    // Real jq's scan(re) is global by default. Compat-def must not produce
    // "gg" when user passes "g" explicitly (was a regex-compile bug).
    let result = run_jq(r#"scan("\\d"; "g")"#, r#""1 2 3""#).await.unwrap();
    let lines: Vec<&str> = result.trim().split('\n').collect();
    assert_eq!(lines.len(), 3, "expected 3 matches: {result}");
}

#[tokio::test]
async fn tsv_rejects_arrays() {
    let result = run_jq_result(r#"[[1,2], "x"] | @tsv"#, "null")
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(
        result.stderr.contains("not valid in a tsv row"),
        "stderr: {}",
        result.stderr
    );
}

#[tokio::test]
async fn tsv_rejects_objects() {
    let result = run_jq_result(r#"[{"a":1}] | @tsv"#, "null").await.unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.contains("not valid in a tsv row"));
}

#[tokio::test]
async fn csv_rejects_arrays() {
    let result = run_jq_result(r#"[[1,2]] | @csv"#, "null").await.unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.contains("not valid in a csv row"));
}

#[tokio::test]
async fn tsv_accepts_scalars() {
    let result = run_jq(r#"["a", 1, true, null] | @tsv"#, "null")
        .await
        .unwrap();
    assert_eq!(result.trim(), r#""a\t1\ttrue\t""#);
}

#[tokio::test]
async fn csv_accepts_scalars() {
    // -r so the @csv string output is unquoted, making contains-checks readable.
    let result = run_jq_with_args(&["-r", r#"["a", 1, true, null] | @csv"#], "null")
        .await
        .unwrap();
    assert_eq!(result.trim(), r#""a",1,true,"#);
}

// =========================================================================
// Tier 2: --slurpfile / --rawfile
// =========================================================================

#[tokio::test]
async fn slurpfile_binds_array_of_values() {
    let result = run_jq_with_files(
        &["--slurpfile", "data", "/x.json", "-n", r#"$data | length"#],
        &[("/x.json", "1\n2\n3")],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), "3");
}

#[tokio::test]
async fn slurpfile_binds_single_value() {
    let result = run_jq_with_files(
        &["--slurpfile", "obj", "/x.json", "-n", r#"$obj[0].name"#],
        &[("/x.json", r#"{"name":"alice"}"#)],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), r#""alice""#);
}

#[tokio::test]
async fn slurpfile_rejects_invalid_json() {
    let result = run_jq_with_files(
        &["--slurpfile", "x", "/bad.json", "-n", r#"$x"#],
        &[("/bad.json", "not json {")],
    )
    .await
    .unwrap();
    assert_ne!(result.exit_code, 0);
}

#[tokio::test]
async fn slurpfile_missing_file_errors() {
    let result = run_jq_with_files(&["--slurpfile", "x", "/missing.json", "-n", r#"$x"#], &[])
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.contains("/missing.json"));
}

#[tokio::test]
async fn rawfile_binds_string_contents() {
    let result = run_jq_with_files(
        &["--rawfile", "txt", "/note.txt", "-n", r#"$txt"#],
        &[("/note.txt", "hello\nworld")],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    // Output is JSON-quoted.
    assert_eq!(result.stdout.trim(), r#""hello\nworld""#);
}

#[tokio::test]
async fn rawfile_with_raw_output_emits_unquoted() {
    let result = run_jq_with_files(
        &["--rawfile", "txt", "/note.txt", "-rn", r#"$txt"#],
        &[("/note.txt", "hello")],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), "hello");
}

#[tokio::test]
async fn repeated_rawfile_bindings_are_byte_capped() {
    let payload = "x".repeat(1024 * 1024);
    let mut args = Vec::new();
    for i in 0..32 {
        args.push("--rawfile".to_string());
        args.push(format!("x{i}"));
        args.push("/big.txt".to_string());
    }
    args.push("-n".to_string());
    args.push(".".to_string());
    let refs: Vec<&str> = args.iter().map(String::as_str).collect();

    let result = run_jq_with_files(&refs, &[("/big.txt", &payload)])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("file bindings exceed"));
}

// =========================================================================
// Tier 2: --args / --jsonargs / $ARGS
// =========================================================================

#[tokio::test]
async fn args_positional_are_strings() {
    let result = run_jq_with_args(&["-n", "$ARGS.positional", "--args", "a", "b", "c"], "")
        .await
        .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!(["a", "b", "c"]));
}

#[tokio::test]
async fn jsonargs_positional_are_parsed_json() {
    let result = run_jq_with_args(
        &[
            "-n",
            "$ARGS.positional",
            "--jsonargs",
            "1",
            "true",
            r#"{"a":1}"#,
        ],
        "",
    )
    .await
    .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!([1, true, {"a": 1}]));
}

#[tokio::test]
async fn args_named_populated_from_arg() {
    let result = run_jq_with_args(
        &[
            "--arg",
            "name",
            "world",
            "--arg",
            "x",
            "1",
            "-n",
            "$ARGS.named",
        ],
        "",
    )
    .await
    .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!({"name": "world", "x": "1"}));
}

#[tokio::test]
async fn args_named_combines_with_argjson() {
    let result = run_jq_with_args(
        &[
            "--arg",
            "name",
            "world",
            "--argjson",
            "count",
            "5",
            "-n",
            "$ARGS.named",
        ],
        "",
    )
    .await
    .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!({"name": "world", "count": 5}));
}

#[tokio::test]
async fn jsonargs_invalid_json_rejected() {
    let result = run_jq_result_with_args(&["-n", "$ARGS.positional", "--jsonargs", "not json"], "")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
}

// =========================================================================
// Tier 2: number-format parity (1.0 stays 1.0)
// =========================================================================

#[tokio::test]
async fn float_zero_decimal_preserved_compact() {
    let result = run_jq_with_args(&["-c", "."], "1.0").await.unwrap();
    assert_eq!(result.trim(), "1.0");
}

#[tokio::test]
async fn float_zero_decimal_preserved_pretty() {
    let result = run_jq(".", "1.0").await.unwrap();
    assert_eq!(result.trim(), "1.0");
}

#[tokio::test]
async fn float_in_array_preserved() {
    let result = run_jq_with_args(&["-c", "."], "[1.0, 2.5, 3]")
        .await
        .unwrap();
    assert_eq!(result.trim(), "[1.0,2.5,3]");
}

#[tokio::test]
async fn integer_stays_integer() {
    let result = run_jq(".", "42").await.unwrap();
    assert_eq!(result.trim(), "42");
}

// =========================================================================
// Tier 2: input_filename / input_line_number
// =========================================================================

#[tokio::test]
async fn input_filename_null_for_stdin() {
    let result = run_jq("input_filename", "1").await.unwrap();
    assert_eq!(result.trim(), "null");
}

#[tokio::test]
async fn input_filename_returns_path_when_file_given() {
    let result = run_jq_with_files(&["input_filename", "/data.json"], &[("/data.json", "1")])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), r#""/data.json""#);
}

#[tokio::test]
async fn input_line_number_counts_lines_read() {
    // jq reads a line at a time: the last value has no newline after it,
    // so it still reports line 2 (matches jq 1.7).
    let result = run_jq("input_line_number", "1\n2\n3").await.unwrap();
    let lines: Vec<&str> = result.trim().split('\n').collect();
    assert_eq!(lines, vec!["1", "2", "2"]);
    let result = run_jq("input_line_number", "1\n2\n\n3").await.unwrap();
    let lines: Vec<&str> = result.trim().split('\n').collect();
    assert_eq!(lines, vec!["1", "2", "3"]);
}

#[tokio::test]
async fn input_line_number_zero_for_null_input() {
    let result = run_jq_with_args(&["-n", "input_line_number"], "")
        .await
        .unwrap();
    assert_eq!(result.trim(), "0");
}

#[tokio::test]
async fn input_filename_with_alternative_compiles() {
    // Reproduces the LLM idiom from the original bug report.
    let result = run_jq_result(r#"input_filename // "stdin""#, "1")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), r#""stdin""#);
}

// =========================================================================
// File input behavior
// =========================================================================

#[tokio::test]
async fn read_single_file() {
    let result = run_jq_with_files(&[".", "/data.json"], &[("/data.json", r#"{"a":1}"#)])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.trim(), "{\n  \"a\": 1\n}");
}

#[tokio::test]
async fn read_multiple_files() {
    let result = run_jq_with_files(
        &[".", "/a.json", "/b.json"],
        &[("/a.json", r#"{"x":1}"#), ("/b.json", r#"{"y":2}"#)],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    assert!(result.stdout.contains("\"x\": 1"));
    assert!(result.stdout.contains("\"y\": 2"));
}

#[tokio::test]
async fn slurp_combines_multiple_files() {
    let result = run_jq_with_files(
        &["-s", ".", "/a.json", "/b.json"],
        &[("/a.json", r#"{"x":1}"#), ("/b.json", r#"{"y":2}"#)],
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0);
    let parsed: serde_json::Value = serde_json::from_str(result.stdout.trim()).unwrap();
    assert!(parsed.is_array());
    assert_eq!(parsed.as_array().unwrap().len(), 2);
}

#[tokio::test]
async fn missing_file_errors() {
    let result = run_jq_with_files(&[".", "/missing.json"], &[])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 2);
    assert_eq!(
        result.stderr,
        "jq: error: Could not open file /missing.json: No such file or directory\n"
    );
}

// =========================================================================
// Help / version
// =========================================================================

#[tokio::test]
async fn help_long() {
    let result = run_jq_with_args(&["--help"], "").await.unwrap();
    assert!(result.contains("Usage:"));
    assert!(result.contains("--slurpfile"));
    assert!(result.contains("--indent"));
}

#[tokio::test]
async fn help_short() {
    let result = run_jq_with_args(&["-h"], "").await.unwrap();
    assert!(result.contains("Usage:"));
}

#[tokio::test]
async fn version_long() {
    let result = run_jq_with_args(&["--version"], "").await.unwrap();
    assert!(result.starts_with("jq-"));
}

#[tokio::test]
async fn version_short() {
    let result = run_jq_with_args(&["-V"], "").await.unwrap();
    assert!(result.starts_with("jq-"));
}

// =========================================================================
// Raw input / slurp combinations
// =========================================================================

#[tokio::test]
async fn raw_input_per_line() {
    let result = run_jq_with_args(&["-R", "."], "hello\nworld\n")
        .await
        .unwrap();
    assert_eq!(result.trim(), "\"hello\"\n\"world\"");
}

#[tokio::test]
async fn raw_input_slurp_single_string() {
    let result = run_jq_with_args(&["-Rs", "."], "hello\nworld\n")
        .await
        .unwrap();
    assert_eq!(result.trim(), "\"hello\\nworld\\n\"");
}

#[tokio::test]
async fn raw_input_slurp_empty_stdin_emits_empty_string() {
    let result = run_jq_with_args(&["-Rs", "."], "").await.unwrap();
    assert_eq!(result.trim(), "\"\"");
}

// =========================================================================
// fancy-regex backed natives — lookahead/lookbehind/backrefs/atomic groups
// (real jq uses Oniguruma; jaq's regex crate rejects these patterns)
// =========================================================================

#[tokio::test]
async fn regex_lookahead_compiles_and_matches() {
    // Positive lookahead: match "foo" only when followed by "bar"
    let result = run_jq(r#"test("foo(?=bar)")"#, r#""foobar""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_lookahead_negative_does_not_match() {
    let result = run_jq(r#"test("foo(?=bar)")"#, r#""foobaz""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "false");
}

#[tokio::test]
async fn regex_negative_lookahead() {
    let result = run_jq(r#"test("foo(?!bar)")"#, r#""foobaz""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_lookbehind_compiles_and_matches() {
    // Lookbehind: match "bar" only when preceded by "foo"
    let result = run_jq(r#"test("(?<=foo)bar")"#, r#""foobar""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_negative_lookbehind() {
    let result = run_jq(r#"test("(?<!foo)bar")"#, r#""xxbar""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_backreference() {
    // Backref \1: match repeated word
    let result = run_jq(r#"test("(\\w+) \\1")"#, r#""hello hello""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_backreference_no_match() {
    let result = run_jq(r#"test("(\\w+) \\1")"#, r#""hello world""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "false");
}

#[tokio::test]
async fn regex_atomic_group_compiles() {
    // Atomic group (?>...): no backtracking
    let result = run_jq(r#"test("(?>abc|abd)d")"#, r#""abcd""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_match_with_lookbehind_has_correct_offset() {
    // Lookbehind is zero-width: match offset is at "bar", not "foo"
    let result = run_jq(r#"match("(?<=foo)bar") | .offset"#, r#""foobar""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "3");
}

#[tokio::test]
async fn regex_capture_groups_with_lookahead_named() {
    // Named capture group with lookahead
    let result = run_jq(r#"capture("(?<word>\\w+)(?=,)")"#, r#""apple,banana""#)
        .await
        .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed["word"], serde_json::json!("apple"));
}

#[tokio::test]
async fn regex_basic_pattern_still_works() {
    // Regression — basic patterns must keep working under fancy-regex.
    let result = run_jq(r#"test("\\d+")"#, r#""abc123""#).await.unwrap();
    assert_eq!(result.trim(), "true");
}

#[tokio::test]
async fn regex_scan_returns_all_matches() {
    let result = run_jq(r#"[scan("\\d+")]"#, r#""a1 b22 c333""#)
        .await
        .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!(["1", "22", "333"]));
}

#[tokio::test]
async fn regex_scan_with_lookahead() {
    // scan with lookahead — extract digits before letters only
    let result = run_jq(r#"[scan("\\d+(?=[a-z])")]"#, r#""1a 2 3b 4""#)
        .await
        .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    assert_eq!(parsed, serde_json::json!(["1", "3"]));
}

#[tokio::test]
async fn regex_match_on_unicode_offset_in_chars() {
    // Offset must be in CHARS not bytes (matches jq docs).
    // "héllo" — byte 3 = char 2 (start of second 'l').
    let result = run_jq(r#"match("ll") | .offset"#, r#""héllo""#)
        .await
        .unwrap();
    assert_eq!(result.trim(), "2");
}

#[tokio::test]
async fn regex_invalid_pattern_yields_short_error() {
    let result = run_jq_result(r#"test("(unbalanced")"#, r#""x""#)
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.starts_with("jq: error (at <stdin>:0): "));
    assert!(result.stderr.len() < 300);
    // Must not leak fancy-regex internal Debug shapes
    assert!(!result.stderr.contains("ParseError"));
    assert!(!result.stderr.contains("CompileError"));
}

#[tokio::test]
async fn setpath_binds_dynamic_path_to_original_input() {
    let result = run_jq(r#"setpath(.path; 1)"#, r#"{"path":["a"]}"#)
        .await
        .unwrap();
    assert_eq!(
        result.trim(),
        "{\n  \"path\": [\n    \"a\"\n  ],\n  \"a\": 1\n}"
    );
}

#[tokio::test]
async fn setpath_binds_dynamic_value_to_original_input() {
    let result = run_jq(r#"setpath(["a"]; .path[0])"#, r#"{"path":["expected"]}"#)
        .await
        .unwrap();
    assert_eq!(
        result.trim(),
        "{\n  \"path\": [\n    \"expected\"\n  ],\n  \"a\": \"expected\"\n}"
    );
}

#[tokio::test]
async fn regex_invalid_flag_yields_short_error() {
    let result = run_jq_result(r#"match("x"; "z")"#, r#""x""#).await.unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.contains("invalid regex flag"));
}

#[tokio::test]
async fn regex_swap_greed_flag_silently_accepted() {
    // 'l' (swap greed) is not exposed by fancy-regex; we silently accept
    // for jq-flag-string parity. The pattern still compiles.
    let result = run_jq(r#"test("a+"; "l")"#, r#""aaa""#).await.unwrap();
    assert_eq!(result.trim(), "true");
}

// =========================================================================
// Error formatting (TM-INF-022 regression — must be jq-shaped, not Debug)
// =========================================================================

#[tokio::test]
async fn unknown_filter_error_is_jq_shaped() {
    let result = run_jq_result("totally_made_up_filter", "1").await.unwrap();
    assert_ne!(result.exit_code, 0);
    assert_eq!(
        result.stderr,
        "jq: error: totally_made_up_filter/0 is not defined\n"
    );
}

#[tokio::test]
async fn compile_error_does_not_leak_internals() {
    let result = run_jq_result("totally_made_up_filter", "1").await.unwrap();
    assert!(!result.stderr.contains("File {"));
    assert!(!result.stderr.contains("Filter("));
    assert!(!result.stderr.contains("setpath"));
    assert!(!result.stderr.contains("__bashkit_env__"));
    assert!(!result.stderr.contains("__bashkit_filename__"));
    assert!(!result.stderr.contains("__bashkit_lineno__"));
}

#[tokio::test]
async fn parse_error_short() {
    let result = run_jq_result("[", "1").await.unwrap();
    assert_ne!(result.exit_code, 0);
    assert!(result.stderr.starts_with("jq: error: "));
    assert!(result.stderr.len() < 300);
}

#[tokio::test]
async fn runtime_error_summarizes_index_operands() {
    let result = run_jq_result(".product_name", r#"[{"product_name":"x"}]"#)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 5);
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot index array with string \"product_name\"\n"
    );
}

#[tokio::test]
async fn runtime_error_iterate_over_null() {
    let result = run_jq_result(".[]", "null").await.unwrap();
    assert_eq!(result.exit_code, 5);
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot iterate over null (null)\n"
    );
}

// =========================================================================
// Security: env isolation (TM-INF-013)
// =========================================================================

#[tokio::test]
async fn env_access_returns_shell_var() {
    let jq = Jq;
    let fs = Arc::new(InMemoryFs::new());
    let mut vars = HashMap::new();
    let mut cwd = PathBuf::from("/");
    let mut env = HashMap::new();
    env.insert("TESTVAR".to_string(), "hello".to_string());
    let args = vec!["-n".to_string(), "env.TESTVAR".to_string()];

    let ctx = Context {
        args: &args,
        env: &env,
        variables: &mut vars,
        cwd: &mut cwd,
        fs,
        stdin: None,
        #[cfg(feature = "http_client")]
        http_client: None,
        #[cfg(feature = "git")]
        git_client: None,
        #[cfg(feature = "ssh")]
        ssh_client: None,
        shell: None,
    };

    let result = jq.execute(ctx).await.unwrap();
    assert_eq!(result.stdout.trim(), "\"hello\"");
}

#[tokio::test]
async fn dollar_env_returns_shell_env() {
    let jq = Jq;
    let fs = Arc::new(InMemoryFs::new());
    let mut vars = HashMap::new();
    let mut cwd = PathBuf::from("/");
    let mut env = HashMap::new();
    env.insert("MY_VAR".to_string(), "hello".to_string());
    let args = vec!["$ENV.MY_VAR".to_string()];

    let ctx = Context {
        args: &args,
        env: &env,
        variables: &mut vars,
        cwd: &mut cwd,
        fs,
        stdin: Some(test_stream("null")),
        #[cfg(feature = "http_client")]
        http_client: None,
        #[cfg(feature = "git")]
        git_client: None,
        #[cfg(feature = "ssh")]
        ssh_client: None,
        shell: None,
    };

    let result = jq.execute(ctx).await.unwrap();
    assert_eq!(result.stdout.trim(), r#""hello""#);
}

#[tokio::test]
async fn env_does_not_pollute_process_env() {
    // TM-INF-013: shell variables passed via ctx.env must NOT leak into
    // the host process environment.
    let unique_key = "BASHKIT_TEST_JQ_NO_POLLUTE_PARITY";
    assert!(std::env::var(unique_key).is_err());

    let jq = Jq;
    let fs = Arc::new(InMemoryFs::new());
    let mut vars = HashMap::new();
    let mut cwd = PathBuf::from("/");
    let mut env = HashMap::new();
    env.insert(unique_key.to_string(), "leaked".to_string());
    let args = vec!["-n".to_string(), format!("env.{unique_key}")];

    let ctx = Context {
        args: &args,
        env: &env,
        variables: &mut vars,
        cwd: &mut cwd,
        fs,
        stdin: None,
        #[cfg(feature = "http_client")]
        http_client: None,
        #[cfg(feature = "git")]
        git_client: None,
        #[cfg(feature = "ssh")]
        ssh_client: None,
        shell: None,
    };

    let result = jq.execute(ctx).await.unwrap();
    assert_eq!(result.stdout.trim(), "\"leaked\"");
    assert!(std::env::var(unique_key).is_err());
}

// =========================================================================
// Security: depth limits (TM-DOS-027)
// =========================================================================

#[tokio::test]
async fn finite_user_recursion_stays_available() {
    let result = run_jq_result(
        "def f($n): if $n == 0 then 42 else f($n - 1) end; f(32)",
        "null",
    )
    .await
    .unwrap();
    assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
    assert_eq!(result.stdout.trim(), "42");
}

#[tokio::test]
async fn deep_array_input_rejected() {
    let depth = 150;
    let input = format!("{}1{}", "[".repeat(depth), "]".repeat(depth));
    let result = run_jq_result(".", &input).await.unwrap();
    assert!(result.exit_code != 0);
    assert!(
        result.stderr.contains("nesting too deep") || result.stderr.contains("recursion limit"),
        "stderr: {}",
        result.stderr
    );
}

#[tokio::test]
async fn deep_object_input_rejected() {
    let depth = 150;
    let mut input = String::from("1");
    for _ in 0..depth {
        input = format!(r#"{{"a":{input}}}"#);
    }
    let result = run_jq_result(".", &input).await.unwrap();
    assert!(result.exit_code != 0);
}

#[tokio::test]
async fn moderate_nesting_works() {
    let result = run_jq(".", "[[[[1]]]]").await.unwrap();
    assert!(result.contains('1'));
}

#[tokio::test]
async fn argjson_rejects_deep_nesting() {
    let deep = format!("{}0{}", "[".repeat(150), "]".repeat(150));
    let result = run_jq_result_with_args(&["--argjson", "x", &deep, "-n", "$x"], "")
        .await
        .unwrap();
    assert!(result.exit_code != 0);
}

// =========================================================================
// Negative tests
// =========================================================================

#[tokio::test]
async fn invalid_json_input() {
    let result = run_jq_result(".", "not valid json").await.unwrap();
    assert!(result.exit_code != 0);
    assert!(result.stderr.contains("jq:"));
}

#[tokio::test]
async fn invalid_filter_syntax() {
    let result = run_jq_result(".[", r#"{"a":1}"#).await.unwrap();
    assert!(result.exit_code != 0);
    assert!(result.stderr.contains("jq:"));
}

#[tokio::test]
async fn empty_stdin_no_null_input_returns_empty() {
    let result = run_jq(".", "").await.unwrap();
    assert_eq!(result, "");
}

#[tokio::test]
async fn whitespace_only_stdin_returns_empty() {
    let result = run_jq(".", "   \n\t  ").await.unwrap();
    assert_eq!(result, "");
}

#[tokio::test]
async fn ndjson_multi_value_processed() {
    let result = run_jq(".a", "{\"a\":1}\n{\"a\":2}").await.unwrap();
    assert_eq!(result.trim(), "1\n2");
}

// =========================================================================
// jq 1.8 builtins — abs, trim, ltrim, rtrim, if-without-else, paths(filter)
// =========================================================================

#[tokio::test]
async fn abs_negative_to_positive() {
    assert_eq!(run_jq("abs", "-42").await.unwrap().trim(), "42");
    assert_eq!(run_jq("abs", "-0.5").await.unwrap().trim(), "0.5");
}

#[tokio::test]
async fn trim_strips_whitespace() {
    assert_eq!(
        run_jq("trim", r#""  hello  ""#).await.unwrap().trim(),
        r#""hello""#
    );
}

#[tokio::test]
async fn ltrim_only_left() {
    assert_eq!(
        run_jq("ltrim", r#""  hello  ""#).await.unwrap().trim(),
        r#""hello  ""#
    );
}

#[tokio::test]
async fn rtrim_only_right() {
    assert_eq!(
        run_jq("rtrim", r#""  hello  ""#).await.unwrap().trim(),
        r#""  hello""#
    );
}

#[tokio::test]
async fn if_without_else_uses_identity() {
    assert_eq!(
        run_jq("if . > 0 then . * 2 end", "5").await.unwrap().trim(),
        "10"
    );
    assert_eq!(
        run_jq("if . > 0 then . * 2 end", "-1")
            .await
            .unwrap()
            .trim(),
        "-1"
    );
}

#[tokio::test]
async fn paths_with_filter() {
    let result = run_jq("[paths(numbers)]", r#"{"a":1,"b":{"c":2},"d":"x"}"#)
        .await
        .unwrap();
    let parsed: serde_json::Value = serde_json::from_str(result.trim()).unwrap();
    let arr = parsed.as_array().unwrap();
    assert!(arr.iter().any(|v| v == &serde_json::json!(["a"])));
    assert!(arr.iter().any(|v| v == &serde_json::json!(["b", "c"])));
}

#[tokio::test]
async fn getpath_returns_value() {
    assert_eq!(
        run_jq(r#"getpath(["a","b"])"#, r#"{"a":{"b":42}}"#)
            .await
            .unwrap()
            .trim(),
        "42"
    );
}

// =========================================================================
// input / inputs across NDJSON
// =========================================================================

#[tokio::test]
async fn input_reads_next_value() {
    let result = run_jq_with_args(&["input"], "1\n2").await.unwrap();
    assert_eq!(result.trim(), "2");
}

#[tokio::test]
async fn inputs_collects_remaining() {
    let result = run_jq_with_args(&["-c", "[inputs]"], "1\n2\n3")
        .await
        .unwrap();
    assert_eq!(result.trim(), "[2,3]");
}

// =========================================================================
// TM-INF-022: per-tool no-leak guard against malformed inputs
// =========================================================================

const JQ_BANNED: &[&str] = &[
    "__bashkit_env__",
    "__bashkit_filename__",
    "__bashkit_lineno__",
    "JQ_COMPAT_DEFS",
    "def setpath",
    "def leaf_paths",
    "def _bk_joinstr",
    "def @tsv:",
    "def @csv:",
    "def env:",
    "def input_filename:",
    "def input_line_number:",
    "Filter(0)",
    "Filter(1)",
    "Filter(2)",
    "Var,",
    "Mod,",
];

macro_rules! jq_no_leak {
    ($name:ident, $script:expr) => {
        #[tokio::test]
        async fn $name() {
            let r = crate::builtins::debug_leak_check::run($script).await;
            crate::builtins::debug_leak_check::assert_no_leak(&r, stringify!($name), JQ_BANNED);
        }
    };
}

jq_no_leak!(
    no_leak_undefined_filter_zero_arity,
    "echo 1 | jq totally_made_up"
);
jq_no_leak!(
    no_leak_undefined_filter_with_arity,
    "echo 1 | jq 'totally_made_up(1; 2)'"
);
jq_no_leak!(no_leak_undefined_variable, "echo 1 | jq '$nope'");
jq_no_leak!(no_leak_undefined_format, "echo '[1]' | jq '@xyzzy'");

jq_no_leak!(no_leak_unbalanced_bracket, "echo 1 | jq '['");
jq_no_leak!(no_leak_unbalanced_paren, "echo 1 | jq '('");
jq_no_leak!(no_leak_stray_pipe, "echo 1 | jq '|'");
jq_no_leak!(no_leak_unterminated_string, r#"echo 1 | jq '"abc'"#);
jq_no_leak!(no_leak_if_without_then, "echo 1 | jq 'if . then'");
jq_no_leak!(no_leak_reduce_without_as, "echo 1 | jq 'reduce . '");
jq_no_leak!(no_leak_def_without_body, "echo 1 | jq 'def f:'");

jq_no_leak!(no_leak_malformed_json_input, "echo 'not json {' | jq '.'");

#[tokio::test]
async fn no_leak_deeply_nested_input() {
    let script = format!("echo '{}{}' | jq '.'", "[".repeat(200), "]".repeat(200));
    let r = crate::builtins::debug_leak_check::run(&script).await;
    crate::builtins::debug_leak_check::assert_no_leak(&r, "no_leak_deeply_nested_input", JQ_BANNED);
}

jq_no_leak!(
    no_leak_index_array_with_string,
    r#"echo '[1,2]' | jq '.foo'"#
);
jq_no_leak!(no_leak_iterate_over_null, r#"echo 'null' | jq '.[]'"#);
jq_no_leak!(no_leak_add_array_and_number, r#"echo '[1,2]' | jq '. + 1'"#);
// `join` fails inside the compat prelude, so its diagnostics are the ones
// most likely to carry prelude source out to the caller.
jq_no_leak!(
    no_leak_join_non_addable_separator,
    r#"echo '["a","b"]' | jq 'join(1)'"#
);
jq_no_leak!(
    no_leak_join_nested_array,
    r#"echo '[[1]]' | jq 'join(",")'"#
);
jq_no_leak!(no_leak_join_over_string, r#"echo '"abc"' | jq 'join(",")'"#);

// New: malformed $ARGS / file flags
jq_no_leak!(no_leak_invalid_jsonargs, "jq -n . --jsonargs 'not json'");
jq_no_leak!(no_leak_invalid_argjson, "jq --argjson x 'not json' -n '$x'");
jq_no_leak!(no_leak_indent_too_large, "echo '{}' | jq --indent 99 '.'");
jq_no_leak!(no_leak_indent_negative, "echo '{}' | jq --indent -1 '.'");
jq_no_leak!(
    no_leak_slurpfile_missing,
    "jq --slurpfile x /no-such-file.json -n '$x'"
);

// Positive regression for the bug-report filter
#[tokio::test]
async fn harness_tsv_filter_compiles_and_runs() {
    let filter = r#"
        if (.data | length) == 0 then
          "No harnesses found."
        else
          (.data[] | [(.id // ""), (.name // ""), (.description // ""), (.parent_harness_id // ""), ((.capabilities // []) | length | tostring), (.created_at // "")] | @tsv)
        end
    "#;
    let input = r#"{"data":[{"id":"h1","name":"alpha","description":"d","parent_harness_id":null,"capabilities":["a","b"],"created_at":"2024-01-01"}]}"#;
    let result = run_jq_result(filter, input).await.unwrap();
    assert_eq!(result.exit_code, 0, "stderr: {}", result.stderr);
    assert_eq!(result.stdout.trim(), r#""h1\talpha\td\t\t2\t2024-01-01""#);
}

// Combined short flag regressions
#[tokio::test]
async fn combined_short_flags_rn() {
    let result = run_jq_with_args(&["-rn", "1+1"], "").await.unwrap();
    assert_eq!(result.trim(), "2");
}

#[tokio::test]
async fn combined_short_flags_sc_add() {
    let result = run_jq_with_args(&["-sc", "add"], "1\n2\n3\n")
        .await
        .unwrap();
    assert_eq!(result.trim(), "6");
}

#[tokio::test]
async fn combined_short_flags_snr() {
    let result = run_jq_with_args(&["-snr", r#""hello""#], "").await.unwrap();
    assert_eq!(result.trim(), "hello");
}

#[tokio::test]
async fn double_dash_separator() {
    let result = run_jq_with_args(&["-n", "--", "1+1"], "").await.unwrap();
    assert_eq!(result.trim(), "2");
}

// =========================================================================
// Security: jq filters must not terminate the host process (#1571)
// =========================================================================

// The tests reaching their assertions at all proves the host wasn't killed:
// `halt` ends the jq command with its code, never the process.
#[tokio::test]
async fn halt_ends_the_command_not_the_host() {
    let result = run_jq_result_with_args(&["-n", "1, halt, 2"], "")
        .await
        .unwrap();
    assert_eq!(result.stdout, "1\n");
    assert_eq!(result.exit_code, 0);
    let result = run_jq_result_with_args(&["-n", "halt(7)"], "")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 7);
}

#[tokio::test]
async fn halt_stops_remaining_inputs() {
    let result = run_jq_result_with_args(&["-c", "if . == 2 then halt else . end"], "1 2 3")
        .await
        .unwrap();
    assert_eq!(result.stdout, "1\n");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn halt_error_prints_message_and_exits() {
    let result = run_jq_result("halt_error", r#""boom\n""#).await.unwrap();
    assert_eq!(result.stderr, "boom\n");
    assert_eq!(result.exit_code, 5);
    let result = run_jq_result("halt_error(3)", r#"{"a":1}"#).await.unwrap();
    assert_eq!(result.stderr, "{\"a\":1}\n");
    assert_eq!(result.exit_code, 3);
    let result = run_jq_result("try halt_error catch 9", "null")
        .await
        .unwrap();
    assert_eq!(result.stdout, "");
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn debug_and_stderr_write_to_jq_stderr() {
    let result = run_jq_result_with_args(&["-c", "debug, debug(\"m\"), stderr"], "[1]")
        .await
        .unwrap();
    assert_eq!(result.stdout, "[1]\n[1]\n[1]\n");
    assert_eq!(result.stderr, "[\"DEBUG:\",[1]]\n[\"DEBUG:\",\"m\"]\n[1]");
}

#[tokio::test]
async fn debug_output_is_capped() {
    let result = run_jq_result_with_args(&["-n", "[range(200000)] | debug | length"], "")
        .await
        .unwrap();
    assert_eq!(result.stdout, "200000\n");
    assert!(result.stderr.len() <= super::messages::MAX_MESSAGE_BYTES);
}

// =========================================================================
// Differential tests vs real jq binary (when present in $PATH)
// =========================================================================

mod differential {
    //! These tests compare bashkit's jq output against the real `jq`
    //! binary when it's available. Skipped silently if no `jq` is found.
    //! They guard against regressions in jq compatibility for the most
    //! common LLM-emitted filter shapes.

    use super::*;

    fn real_jq_available() -> bool {
        real_jq_version().is_some()
    }

    /// `(major, minor)` of the host `jq`, or `None` when there is no usable
    /// one. `jq --version` prints `jq-1.8.1`, older builds `jq-1.7`.
    fn real_jq_version() -> Option<(u32, u32)> {
        let out = std::process::Command::new("jq")
            .arg("--version")
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let text = String::from_utf8_lossy(&out.stdout);
        let version = text.trim().strip_prefix("jq-")?;
        let mut parts = version.split('.');
        let major = parts.next()?.parse().ok()?;
        // `jq-1.7` has no minor component; treat the missing one as 0.
        let minor = parts.next().unwrap_or("0").parse().unwrap_or(0);
        Some((major, minor))
    }

    /// Like [`assert_matches`], for a case whose expected output only holds
    /// from a given jq upwards. An older host oracle skips just that case
    /// rather than reddening the suite, the same bargain
    /// `minimum_bash_major` strikes for the competitor corpus.
    ///
    /// The one case that needs it today is `--indent 0`: jq 1.7 and earlier
    /// let it imply `-c`, jq 1.8 emits newlines without indentation
    /// (jqlang/jq#3232). CI pins the oracle (`scripts/install-jq-ci.sh`), so
    /// this only ever skips on a developer machine with an older jq.
    async fn assert_matches_from_jq(min: (u32, u32), args: &[&str], input: &str) {
        match real_jq_version() {
            Some(found) if found >= min => assert_matches(args, input).await,
            Some((major, minor)) => eprintln!(
                "host jq {major}.{minor} predates {}.{}; skipping `jq {}`",
                min.0,
                min.1,
                args.join(" ")
            ),
            None => eprintln!("real jq not present; skipping differential test"),
        }
    }

    fn run_real_jq(args: &[&str], input: &str) -> Option<(String, i32)> {
        use std::io::Write;
        use std::process::{Command, Stdio};
        let mut child = Command::new("jq")
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .ok()?;
        // Ignore write errors: jq may exit before reading stdin (e.g. on
        // unknown flags), causing a broken pipe. Drop stdin to signal EOF.
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(input.as_bytes());
        }
        let out = child.wait_with_output().ok()?;
        let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
        Some((stdout, out.status.code().unwrap_or(-1)))
    }

    /// Compare bashkit and real-jq output for the same args+input.
    /// Stdout must match byte-for-byte; exit codes must match.
    async fn assert_matches(args: &[&str], input: &str) {
        if !real_jq_available() {
            eprintln!("real jq not present; skipping differential test");
            return;
        }
        let (real_out, real_code) = run_real_jq(args, input).expect("real jq run should succeed");
        let bashkit = run_jq_result_with_args(args, input).await.unwrap();
        let args_label = args.join(" ");
        assert_eq!(
            bashkit.stdout, real_out,
            "stdout mismatch for {args_label}\nbashkit:\n{}\nreal jq:\n{}",
            bashkit.stdout, real_out
        );
        assert_eq!(
            bashkit.exit_code, real_code,
            "exit-code mismatch for {args_label}: bashkit={}, real={}",
            bashkit.exit_code, real_code
        );
    }

    /// Prefer a direct raw-input comparison. Older jq builds reject controls
    /// at the lexer, so fall back to equivalent escaped JSON on those versions
    /// while retaining real jq as the filter/output oracle.
    async fn assert_control_matches(args: &[&str], raw_input: &str, escaped_input: &str) {
        if !real_jq_available() {
            eprintln!("real jq not present; skipping differential test");
            return;
        }
        let direct = run_real_jq(args, raw_input).unwrap();
        let (real_out, real_code) = if direct.1 == 0 {
            direct
        } else {
            run_real_jq(args, escaped_input).unwrap()
        };
        let bashkit = run_jq_result_with_args(args, raw_input).await.unwrap();
        assert_eq!(bashkit.stdout, real_out);
        assert_eq!(bashkit.exit_code, real_code);
    }

    #[tokio::test]
    async fn diff_literal_newline_tab_and_cr() {
        for (raw, escaped) in [
            ("\"a\nb\"", "\"a\\nb\""),
            ("\"a\tb\"", "\"a\\tb\""),
            ("\"a\rb\"", "\"a\\rb\""),
        ] {
            assert_control_matches(&["-c", "."], raw, escaped).await;
        }
    }

    #[tokio::test]
    async fn diff_all_literal_controls() {
        let controls: String = (0u8..=0x1f).map(char::from).collect();
        let raw = format!("\"{controls}\"");
        let escaped = serde_json::to_string(&controls).unwrap();
        assert_control_matches(&["-c", "."], &raw, &escaped).await;
    }

    #[tokio::test]
    async fn diff_controls_adjacent_to_escapes_and_concatenated_values() {
        assert_control_matches(
            &["-c", "."],
            "\"a\\n\tb\"\"c\r\\td\"",
            "\"a\\n\\tb\"\"c\\r\\td\"",
        )
        .await;
    }

    #[tokio::test]
    async fn diff_control_normalization_boundary_size() {
        let content = "x".repeat(16 * 1024);
        let raw = format!("\"{content}\n\"");
        let escaped = format!("\"{content}\\n\"");
        assert_control_matches(&["-c", "length"], &raw, &escaped).await;
    }

    #[tokio::test]
    async fn diff_malformed_quote_and_control_outside_string() {
        assert_matches(&["-c", "."], "\"unterminated\n").await;
        assert_matches(&["-c", "."], "1\u{0001}2").await;
    }

    #[tokio::test]
    async fn diff_identity_object() {
        assert_matches(&["."], r#"{"a":1,"b":[1,2]}"#).await;
    }

    #[tokio::test]
    async fn diff_compact_array() {
        assert_matches(&["-c", "."], r#"[1,2,3]"#).await;
    }

    #[tokio::test]
    async fn diff_indent_4() {
        assert_matches(&["--indent", "4", "."], r#"{"a":1,"b":2}"#).await;
    }

    #[tokio::test]
    async fn diff_indent_0() {
        assert_matches_from_jq((1, 8), &["--indent", "0", "."], r#"{"a":1}"#).await;
    }

    #[tokio::test]
    async fn diff_indent_0_nested() {
        assert_matches_from_jq(
            (1, 8),
            &["--indent", "0", "."],
            r#"{"a":[1,2],"b":{"c":3}}"#,
        )
        .await;
    }

    /// `-c`, `--tab` and `--indent N` all set the same thing, so the last one
    /// on the command line wins. Each pair below disagrees with its reverse.
    /// jq has behaved this way since at least 1.7; only what `--indent 0`
    /// itself means changed in 1.8, which is why one case is gated.
    #[tokio::test]
    async fn diff_output_shape_flags_are_last_wins() {
        let input = r#"{"a":[1,2]}"#;
        for args in [
            ["-c", "--indent", "4", "."].as_slice(),
            ["--indent", "4", "-c", "."].as_slice(),
            ["--indent", "0", "-c", "."].as_slice(),
            ["-c", "--tab", "."].as_slice(),
            ["--tab", "-c", "."].as_slice(),
            ["--tab", "--indent", "4", "."].as_slice(),
            ["--indent", "4", "--tab", "."].as_slice(),
            ["--indent", "0", "--indent", "4", "."].as_slice(),
        ] {
            assert_matches(args, input).await;
        }
        assert_matches_from_jq((1, 8), &["-c", "--indent", "0", "."], input).await;
    }

    #[tokio::test]
    async fn diff_sort_keys() {
        assert_matches(&["-S", "."], r#"{"b":1,"a":2,"c":3}"#).await;
    }

    #[tokio::test]
    async fn diff_raw_output_string() {
        assert_matches(&["-r", ".name"], r#"{"name":"alice"}"#).await;
    }

    #[tokio::test]
    async fn diff_keys() {
        assert_matches(&["keys"], r#"{"b":1,"a":2}"#).await;
    }

    #[tokio::test]
    async fn diff_length_array() {
        assert_matches(&["length"], r#"[1,2,3,4,5]"#).await;
    }

    #[tokio::test]
    async fn diff_array_iter() {
        assert_matches(&[".[]"], r#"[1,2,3]"#).await;
    }

    #[tokio::test]
    async fn diff_select_filter() {
        assert_matches(&[".[] | select(. > 1)"], r#"[1,2,3]"#).await;
    }

    #[tokio::test]
    async fn diff_pipe_chain() {
        assert_matches(&[".items | map(.id)"], r#"{"items":[{"id":1},{"id":2}]}"#).await;
    }

    #[tokio::test]
    async fn diff_float_zero_decimal() {
        assert_matches(&["-c", "."], "1.0").await;
    }

    #[tokio::test]
    async fn diff_args_positional() {
        assert_matches(&["-n", "$ARGS.positional", "--args", "a", "b"], "").await;
    }

    #[tokio::test]
    async fn diff_argjson_named() {
        assert_matches(&["--argjson", "n", "5", "-n", "$ARGS.named"], "").await;
    }

    #[tokio::test]
    async fn diff_exit_status_truthy() {
        let (_, code) = run_real_jq(&["-e", "."], "42").unwrap_or((String::new(), -1));
        let bk = run_jq_result_with_args(&["-e", "."], "42").await.unwrap();
        if real_jq_available() {
            assert_eq!(bk.exit_code, code);
        }
    }

    #[tokio::test]
    async fn diff_exit_status_null() {
        if !real_jq_available() {
            return;
        }
        let (_, code) = run_real_jq(&["-e", "."], "null").unwrap_or((String::new(), -1));
        let bk = run_jq_result_with_args(&["-e", "."], "null").await.unwrap();
        assert_eq!(bk.exit_code, code);
    }

    #[tokio::test]
    async fn diff_exit_status_no_output() {
        if !real_jq_available() {
            return;
        }
        let (_, code) = run_real_jq(&["-e", "empty"], "1").unwrap_or((String::new(), -1));
        let bk = run_jq_result_with_args(&["-e", "empty"], "1")
            .await
            .unwrap();
        assert_eq!(bk.exit_code, code);
    }

    #[tokio::test]
    async fn diff_unknown_flag_exit_code() {
        if !real_jq_available() {
            return;
        }
        let (_, code) = run_real_jq(&["--xyzzy", "."], "1").unwrap_or((String::new(), -1));
        let bk = run_jq_result_with_args(&["--xyzzy", "."], "1")
            .await
            .unwrap();
        assert_eq!(
            bk.exit_code, code,
            "real jq exit={code}, bashkit={}",
            bk.exit_code
        );
    }

    // ----- Regex parity (fancy-regex vs Oniguruma) -----

    #[tokio::test]
    async fn diff_regex_basic_test() {
        assert_matches(&[r#"test("\\d+")"#], r#""abc123""#).await;
    }

    #[tokio::test]
    async fn diff_regex_lookahead_test() {
        assert_matches(&[r#"test("foo(?=bar)")"#], r#""foobar""#).await;
    }

    #[tokio::test]
    async fn diff_regex_lookbehind_test() {
        assert_matches(&[r#"test("(?<=foo)bar")"#], r#""foobar""#).await;
    }

    #[tokio::test]
    async fn diff_regex_backref_test() {
        assert_matches(&[r#"test("(\\w+) \\1")"#], r#""hello hello""#).await;
    }

    #[tokio::test]
    async fn diff_regex_match_offset() {
        assert_matches(&[r#"match("ll") | .offset"#], r#""hello""#).await;
    }

    #[tokio::test]
    async fn diff_regex_match_unicode_offset() {
        // Real jq reports char (not byte) offset; bashkit must match.
        assert_matches(&[r#"match("ll") | .offset"#], r#""héllo""#).await;
    }

    #[tokio::test]
    async fn diff_regex_scan_digits() {
        assert_matches(&[r#"[scan("\\d+")]"#], r#""a1 b22 c333""#).await;
    }

    #[tokio::test]
    async fn diff_regex_capture_named() {
        assert_matches(&[r#"capture("(?<word>\\w+),")"#], r#""apple,banana""#).await;
    }
}

#[tokio::test]
async fn filter_from_file_treats_positionals_as_inputs() {
    let files = [
        ("/f.jq", "# doubled\n.a | map(. * 2)\n"),
        ("/in.json", r#"{"a":[1,2]}"#),
    ];
    let result = run_jq_with_files(&["-c", "-f", "/f.jq", "/in.json"], &files)
        .await
        .expect("jq -f runs");
    assert_eq!(result.stdout, "[2,4]\n");
    let result = run_jq_with_files(&["-cf", "/missing.jq", "/in.json"], &files)
        .await
        .expect("jq -f runs");
    assert_eq!(result.exit_code, 2);
    assert!(result.stderr.contains("Could not open /missing.jq"));
}

// =========================================================================
// Input stream: -n with input/inputs, per-file names, errors per input
// (behavior checked against jq 1.7)
// =========================================================================

#[tokio::test]
async fn null_input_leaves_stream_to_input_and_inputs() {
    assert_eq!(
        run_jq_with_args(&["-n", "input"], "41 42").await.unwrap(),
        "41\n"
    );
    assert_eq!(
        run_jq_with_args(&["-nc", "[inputs]"], "1 \"a\" [2]")
            .await
            .unwrap(),
        "[1,\"a\",[2]]\n"
    );
    assert_eq!(
        run_jq_with_args(&["-nc", "[limit(2; inputs)], input"], "1 2 3 4")
            .await
            .unwrap(),
        "[1,2]\n3\n"
    );
    assert_eq!(
        run_jq_with_args(&["-n", "reduce inputs as $x (0; . + $x)"], "1 2 39")
            .await
            .unwrap(),
        "42\n"
    );
}

/// jq 1.7: with `-n`, stdin is only parsed when `input`/`inputs` reach it,
/// so invalid JSON on stdin is ignored by a filter that never reads it.
#[tokio::test]
async fn null_input_ignores_unread_invalid_stdin() {
    let result = run_jq_result_with_args(&["-n", "1"], "not json")
        .await
        .unwrap();
    assert_eq!(result.stdout, "1\n");
    assert_eq!(result.stderr, "");
    assert_eq!(result.exit_code, 0);

    // Values before the bad text are still readable.
    let result = run_jq_result_with_args(&["-n", "input"], "1 x")
        .await
        .unwrap();
    assert_eq!(result.stdout, "1\n");
    assert_eq!(result.stderr, "");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn null_input_reports_invalid_stdin_once_reached() {
    let result = run_jq_result_with_args(&["-nc", "[inputs]"], "1 x")
        .await
        .unwrap();
    assert!(result.stderr.starts_with("jq: "), "{}", result.stderr);
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn slurp_of_empty_input_is_empty_array() {
    assert_eq!(run_jq_with_args(&["-s", "."], "").await.unwrap(), "[]\n");
    assert_eq!(run_jq_with_args(&["."], "").await.unwrap(), "");
}

#[tokio::test]
async fn input_fails_when_stream_is_exhausted() {
    let result = run_jq_result_with_args(&["-c", "[., input]"], "1 2 3")
        .await
        .unwrap();
    assert_eq!(result.stdout, "[1,2]\n");
    assert_eq!(result.stderr, "jq: error (at <stdin>:0): No more inputs\n");
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn input_filename_follows_each_file() {
    let result = run_jq_with_files(
        &["-c", "[., input_filename]", "/a.json", "/b.json"],
        &[("/a.json", "{\"f\":\"a\"}"), ("/b.json", "1 2")],
    )
    .await
    .unwrap();
    assert_eq!(
        result.stdout,
        "[{\"f\":\"a\"},\"/a.json\"]\n[1,\"/b.json\"]\n[2,\"/b.json\"]\n"
    );
}

#[tokio::test]
async fn missing_file_among_others_is_skipped_with_exit_2() {
    let result = run_jq_with_files(
        &["-c", ".", "/a.json", "/nope.json"],
        &[("/a.json", "{\"ok\":true}")],
    )
    .await
    .unwrap();
    assert_eq!(result.stdout, "{\"ok\":true}\n");
    assert_eq!(
        result.stderr,
        "jq: error: Could not open file /nope.json: No such file or directory\n"
    );
    assert_eq!(result.exit_code, 2);
}

#[tokio::test]
async fn runtime_error_moves_on_to_next_input() {
    let result = run_jq_result_with_args(
        &["-c", ".a | ascii_downcase"],
        "{\"a\":\"X\"} 1 {\"a\":\"Y\"}",
    )
    .await
    .unwrap();
    assert_eq!(result.stdout, "\"x\"\n\"y\"\n");
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot index number with string \"a\"\n"
    );
    // The last input succeeded.
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn runtime_error_location_names_file_and_line() {
    let result = run_jq_with_files(
        &[".[] | .n | ascii_downcase", "/d.json"],
        &[("/d.json", "[\n  {\"n\": \"A\"},\n  {\"n\": 5}\n]\n")],
    )
    .await
    .unwrap();
    assert_eq!(result.stdout, "\"a\"\n");
    assert!(
        result.stderr.starts_with("jq: error (at /d.json:4): "),
        "stderr={}",
        result.stderr
    );
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn error_with_string_prints_message_unquoted() {
    let result = run_jq_result_with_args(&["-n", "error(\"boom\")"], "")
        .await
        .unwrap();
    assert_eq!(result.stderr, "jq: error (at <unknown>): boom\n");
    let result = run_jq_result_with_args(&["-n", "error({a:1})"], "")
        .await
        .unwrap();
    assert_eq!(
        result.stderr,
        "jq: error (at <unknown>) (not a string): {\"a\":1}\n"
    );
}

#[tokio::test]
async fn values_before_a_parse_error_are_processed() {
    let result = run_jq_result_with_args(&["-c", "."], "{\"a\":1}\n{a:2}")
        .await
        .unwrap();
    assert_eq!(result.stdout, "{\"a\":1}\n");
    assert!(
        result.stderr.contains("invalid JSON"),
        "stderr={}",
        result.stderr
    );
    assert_eq!(result.exit_code, 5);
    // A literal glued to junk is one bad token: nothing is emitted.
    let result = run_jq_result_with_args(&["-c", "."], "1\u{0001}2")
        .await
        .unwrap();
    assert_eq!(result.stdout, "");
    assert_eq!(result.exit_code, 5);
}

// =========================================================================
// Numbers and value errors (behavior checked against jq 1.7)
// =========================================================================

#[tokio::test]
async fn computed_floats_print_like_jq() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "[pow(2;10), (17/5|floor), (1.5*2), 1e17*1, 0.00001*1, (0.1+0.2), (2.5*2.5)]",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(out, "[1024,3,3,1e+17,1e-05,0.30000000000000004,6.25]\n");
}

#[tokio::test]
async fn input_number_literals_keep_their_form_until_computed() {
    let out = run_jq_with_args(&["-c", "[.[], (.[0] + 1)]"], "[1.0, 2.50]")
        .await
        .unwrap();
    assert_eq!(out, "[1.0,2.5,2]\n");
}

#[tokio::test]
async fn nan_and_infinities_render_like_jq() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "[nan, infinite, -infinite, (nan|isnan), (infinite|isinfinite)]",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "[null,1.7976931348623157e+308,-1.7976931348623157e+308,true,true]\n"
    );
}

#[tokio::test]
async fn math_errors_use_jq_wording() {
    let out = run_jq_with_args(
        &[
            "-c",
            "[(try (\"a\"+1) catch .), (try ({\"aaaaaaa\":\"bbbbbbbbbbb\"}+1) catch .), (try ([1]*{}) catch .), (try (1/0) catch .), (try (5%0) catch .)]",
        ],
        "null",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        concat!(
            "[\"string (\\\"a\\\") and number (1) cannot be added\",",
            "\"object ({\\\"aaaaaaa\\\":...) and number (1) cannot be added\",",
            "\"array ([1]) and object ({}) cannot be multiplied\",",
            "\"number (1) and number (0) cannot be divided because the divisor is zero\",",
            "\"number (5) and number (0) cannot be divided (remainder) because the divisor is zero\"]\n"
        )
    );
}

#[tokio::test]
async fn math_error_on_huge_operands_stays_bounded() {
    let out = run_jq_with_args(&["-c", "try ([range(0;200000)] + 1) catch ."], "null")
        .await
        .unwrap();
    assert!(
        out.len() < 1024,
        "math error on huge operand leaked {} bytes",
        out.len()
    );
    assert!(out.contains("..."), "huge operand preview should truncate");
    // Fresh-context follow-up (each helper builds a new shell); true
    // same-session recovery is covered by `shell_recovers_after_huge_operand_math_error`.
    let recovered = run_jq_with_args(&["-c", "1 + 2"], "null").await.unwrap();
    assert_eq!(recovered, "3\n");
}

#[tokio::test]
async fn division_by_zero_is_a_runtime_error() {
    let result = run_jq_result_with_args(&["-c", "1 / .x"], "{\"x\": 2} {\"x\": 0} {\"x\": 4}")
        .await
        .unwrap();
    assert_eq!(result.stdout, "0.5\n0.25\n");
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): number (1) and number (0) cannot be divided because the divisor is zero\n"
    );
}

#[tokio::test]
async fn remainder_truncates_operands() {
    let out = run_jq_with_args(&["-nc", "[5 % 3, -5 % 3, 5 % -3, 5.9 % 3, 1e20 % 7]"], "")
        .await
        .unwrap();
    assert_eq!(out, "[2,-2,2,2,0]\n");
}

#[tokio::test]
async fn index_rules_follow_jq() {
    let out = run_jq_with_args(
        &["-c", ".[-1], .[-10], .[1.7], (try .[\"a\"] catch .)"],
        "[1, 2, 3]",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "3\nnull\n2\n\"Cannot index array with string \\\"a\\\"\"\n"
    );
    let result = run_jq_result_with_args(&["getpath([\"a\",0])"], "{\"a\":{\"b\":1}}")
        .await
        .unwrap();
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot index object with number\n"
    );
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn gamma_is_log_gamma() {
    let out = run_jq_with_args(&["-nc", "[8 | gamma, significand, logb]"], "")
        .await
        .unwrap();
    assert_eq!(out, "[8.525161361065413,1,3]\n");
}

#[tokio::test]
async fn update_through_null_creates_containers() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "(.a.b.c = 1), (.[2] = 1), (.[1:3] = [\"x\"]), (.a |= empty), \
             ([1] | .[3] = 9), ([1] | .[1.7] = 2), ([1] | .[5] |= empty)",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "{\"a\":{\"b\":{\"c\":1}}}\n[null,null,1]\n[\"x\"]\nnull\n[1,null,null,9]\n[1,2]\n[1]\n"
    );
}

#[tokio::test]
async fn update_index_errors_follow_jq() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "(try (.[-1] = 1) catch .), (try ({} | .[1] = 2) catch .), \
             (try (.[1e9] = 1) catch .), (try (.[] = 1) catch .)",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "\"Out of bounds negative array index\"\n\"Cannot index object with number\"\n\
         \"Array index too large\"\n\"Cannot iterate over null (null)\"\n"
    );
}

#[tokio::test]
async fn string_builtins_follow_jq() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "([1, null, \"a\", true] | join(\"-\")), ([null] | join(\",\")), \
             (try ([[1]] | join(\",\")) catch .), (1 | ltrimstr(\"a\")), \
             (\"ab\" | rtrimstr(1)), (\"a1b2\" | [scan(\"([a-z])([0-9])\")]), \
             (\"ab\" | capture(\"(?<x>a)(?<y>z)?\")), \"\\u007f\"",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "\"1--a-true\"\n\"\"\n\"string (\\\"\\\") and array ([1]) cannot be added\"\n1\n\"ab\"\n\
         [[\"a\",\"1\"],[\"b\",\"2\"]]\n{\"x\":\"a\",\"y\":null}\n\"\\u007f\"\n"
    );
}

/// `join` is defined in the compat prelude rather than vendored, so its
/// parity with real jq is only as good as that definition. Every case here
/// was captured from jq 1.7, including the wording and operand order of the
/// two error messages: the separator is only ever added once the array holds
/// a second element, so `["a"] | join(1)` succeeds while `["a","b"] | join(1)`
/// reports the accumulated string first.
#[tokio::test]
async fn join_follows_jq() {
    let cases = [
        (r#"[1, null, "a", true] | join("-")"#, "\"1--a-true\""),
        (r#"[null] | join(",")"#, "\"\""),
        (r#"[] | join(",")"#, "\"\""),
        (r#"{} | join(",")"#, "\"\""),
        (r#"[false] | join(",")"#, "\"false\""),
        (r#"["a"] | join(1)"#, "\"a\""),
        (r#"["a","b","c"] | join("")"#, "\"abc\""),
        (r#"["a","b"] | join("<>")"#, "\"a<>b\""),
        (
            r#"["\u00e9","\u00fc"] | join("\u2014")"#,
            "\"\u{e9}\u{2014}\u{fc}\"",
        ),
        (r#"{"a":"x","b":"y"} | join("-")"#, "\"x-y\""),
        (
            r#"try ([[1]] | join(",")) catch ."#,
            r#""string (\"\") and array ([1]) cannot be added""#,
        ),
        (
            r#"try (["a","b"] | join(1)) catch ."#,
            r#""string (\"a\") and number (1) cannot be added""#,
        ),
        (
            r#"try ([1,2] | join(2)) catch ."#,
            r#""string (\"1\") and number (2) cannot be added""#,
        ),
        (
            r#"try ("abc" | join(",")) catch ."#,
            r#""Cannot iterate over string (\"abc\")""#,
        ),
    ];
    for (filter, want) in cases {
        let out = run_jq_with_args(&["-nc", filter], "").await.unwrap();
        assert_eq!(out, format!("{want}\n"), "{filter}");
    }
}

#[tokio::test]
async fn unmatched_group_is_reported_like_jq() {
    let out = run_jq_with_args(&["-c", "[match(\"(a)(z)?\").captures[]]"], "\"ab\"")
        .await
        .unwrap();
    assert_eq!(
        out,
        "[{\"offset\":0,\"length\":1,\"string\":\"a\",\"name\":null},\
         {\"offset\":-1,\"string\":null,\"length\":0,\"name\":null}]\n"
    );
}

#[tokio::test]
async fn from_entries_and_object_keys_follow_jq() {
    let out = run_jq_with_args(
        &["-c", "from_entries"],
        r#"[{"key":"a","value":1},{"name":"c","value":3},{"Name":"N","value":4},{"key":"d"},{"name":"f","Value":6}]"#,
    )
    .await
    .unwrap();
    assert_eq!(out, "{\"a\":1,\"c\":3,\"N\":4,\"d\":null,\"f\":6}\n");
    let result = run_jq_result_with_args(&["-c", "from_entries"], r#"[{"key":null,"value":4}]"#)
        .await
        .unwrap();
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot use null (null) as object key\n"
    );
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn tostream_round_trips() {
    let out = run_jq_with_args(
        &[
            "-c",
            "[tostream], fromstream(tostream), [1 | truncate_stream([[0], 1], [[1, 0], 2], [[1, 0]], [[1]])], IN(.[]; 1)",
        ],
        r#"[1,{"a":2},[]]"#,
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "[[[0],1],[[1,\"a\"],2],[[1,\"a\"]],[[2],[]],[[2]]]\n[1,{\"a\":2},[]]\n[[[0],2],[[0]]]\ntrue\n"
    );
}

#[test]
fn run_loop_never_calls_unwrap_valr() {
    // THREAT[TM-INF-023]: `jaq_core::unwrap_valr` exits the process on halt.
    assert!(!include_str!("mod.rs").contains("unwrap_valr("));
}

#[tokio::test]
async fn ascii_output_escapes_non_ascii() {
    let out = run_jq_with_args(&["-ac", "."], r#"{"s":"olá ☃ 😀"}"#)
        .await
        .unwrap();
    assert_eq!(out, "{\"s\":\"ol\\u00e1 \\u2603 \\ud83d\\ude00\"}\n");
    // -a keeps strings JSON-encoded even under -r, like jq.
    let out = run_jq_with_args(&["-ra", "."], "\"é\"").await.unwrap();
    assert_eq!(out, "\"\\u00e9\"\n");
}

#[tokio::test]
async fn raw_output0_separates_with_nul() {
    let out = run_jq_with_args(&["--raw-output0", ".[]"], r#"[1,"x",{}]"#)
        .await
        .unwrap();
    assert_eq!(out, "1\0x\0{}\0");
    let result = run_jq_result_with_args(&["--raw-output0", ".[]"], r#"["a\u0000b","c"]"#)
        .await
        .unwrap();
    assert_eq!(result.stdout, "");
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot dump a string containing NUL with --raw-output0 option\n"
    );
    assert_eq!(result.exit_code, 5);
}

#[tokio::test]
async fn stream_flag_feeds_path_events() {
    let out = run_jq_with_args(&["-c", "--stream", "."], r#"{"a":[1,{"b":null}],"c":"d"}"#)
        .await
        .unwrap();
    assert_eq!(
        out,
        "[[\"a\",0],1]\n[[\"a\",1,\"b\"],null]\n[[\"a\",1,\"b\"]]\n[[\"a\",1]]\n[[\"c\"],\"d\"]\n[[\"c\"]]\n"
    );
    let out = run_jq_with_args(&["-c", "--stream", "."], "1 [] {}")
        .await
        .unwrap();
    assert_eq!(out, "[[],1]\n[[],[]]\n[[],{}]\n");
    let out = run_jq_with_args(&["-nc", "--stream", "fromstream(inputs)"], r#"{"a":[1,2]}"#)
        .await
        .unwrap();
    assert_eq!(out, "{\"a\":[1,2]}\n");
}

#[tokio::test]
async fn stream_slurp_and_metadata_preserve_event_order() {
    let result = run_jq_with_files(
        &[
            "-c",
            "--stream",
            "[input_filename, .]",
            "/first.json",
            "/second.json",
        ],
        &[("/first.json", "[1,[]]"), ("/second.json", "{}")],
    )
    .await
    .unwrap();
    assert_eq!(
        result.stdout,
        "[\"/first.json\",[[0],1]]\n[\"/first.json\",[[1],[]]]\n[\"/first.json\",[[1]]]\n[\"/second.json\",[[],{}]]\n"
    );
    let out = run_jq_with_args(&["-sc", "--stream", "."], "[1,[]] {}")
        .await
        .unwrap();
    assert_eq!(out, "[[[0],1],[[1],[]],[[1]],[[],{}]]\n");
    let out = run_jq_with_args(&["-nc", "--stream", "[limit(1; inputs)], input"], "[1,2]")
        .await
        .unwrap();
    assert_eq!(out, "[[[0],1]]\n[[1],2]\n");
}

#[tokio::test]
async fn seq_flag_uses_record_separators() {
    let out = run_jq_with_args(&["--seq", "-c", "."], "\x1e[1]\n\x1e2\n")
        .await
        .unwrap();
    assert_eq!(out, "\x1e[1]\n\x1e2\n");
}

#[tokio::test]
async fn destructuring_alternatives_follow_jq() {
    let out = run_jq_with_args(
        &["-c", ".[] as [$x, $y] ?// $x | [$x, $y]"],
        r#"[1, {"b": 2}, [4, 5]]"#,
    )
    .await
    .unwrap();
    assert_eq!(out, "[1,null]\n[{\"b\":2},null]\n[4,5]\n");
    // An error in the body moves on to the next pattern; the last one's
    // error propagates.
    let result = run_jq_result_with_args(
        &[
            "-c",
            ".[] as [$a] ?// $a | if $a == 1 then error(\"x\") else $a end",
        ],
        "[[1]]",
    )
    .await
    .unwrap();
    assert_eq!(result.stdout, "[1]\n");
    let result = run_jq_result_with_args(&["-c", ". as [$a] ?// $a | error(\"e\")"], "[1]")
        .await
        .unwrap();
    assert_eq!(result.stderr, "jq: error (at <stdin>:0): e\n");
    let result = run_jq_result_with_args(&["-c", ". as [$a] ?// {a: $a} | error(\"e\")"], "[1]")
        .await
        .unwrap();
    assert_eq!(
        result.stderr,
        "jq: error (at <stdin>:0): Cannot index array with string \"a\"\n"
    );
}

#[tokio::test]
async fn decoding_builtins_follow_jq() {
    let out = run_jq_with_args(
        &[
            "-nc",
            "([55296, 65] | implode), (\"YW\" | @base64d), (\"YQ\" | @base64d), \
             (try (\"!!\" | @base64d) catch .), (try (\"Y\" | @base64d) catch .), \
             (try (\"x\" | strptime(\"%Y\")) catch .), (try (\"2026-01-15\" | fromdate) catch .), \
             (\"2026-01-15T12:00:00Z\" | fromdate)",
        ],
        "",
    )
    .await
    .unwrap();
    assert_eq!(
        out,
        "\"\u{fffd}A\"\n\"a\"\n\"a\"\n\"string (\\\"!!\\\") is not valid base64 data\"\n\
         \"string (\\\"Y\\\") trailing base64 byte found\"\n\
         \"date \\\"x\\\" does not match format \\\"%Y\\\"\"\n\
         \"date \\\"2026-01-15\\\" does not match format \\\"%Y-%m-%dT%H:%M:%SZ\\\"\"\n1768478400\n"
    );
}