bashkit 0.1.20

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
//! jq - JSON processor builtin
//!
//! Implements jq functionality using the jaq library.
//!
//! Usage:
//!   echo '{"name":"foo"}' | jq '.name'
//!   jq '.[] | .id' < data.json

use async_trait::async_trait;
use jaq_core::load::{Arena, File, Loader};
use jaq_core::{Compiler, Ctx, Vars, data};
use jaq_json::Val;
use jaq_std::input::{HasInputs, Inputs, RcIter};

use super::{Builtin, Context, read_text_file, resolve_path};
use crate::error::{Error, Result};
use crate::interpreter::ExecResult;

/// Custom DataT that holds both the LUT and a shared input iterator.
/// Required by jaq 3.0 for `input`/`inputs` filter support.
struct InputData<V>(std::marker::PhantomData<V>);

impl<V: jaq_core::ValT + 'static> data::DataT for InputData<V> {
    type V<'a> = V;
    type Data<'a> = InputDataRef<'a, V>;
}

#[derive(Clone)]
struct InputDataRef<'a, V: jaq_core::ValT + 'static> {
    lut: &'a jaq_core::Lut<InputData<V>>,
    inputs: &'a RcIter<dyn Iterator<Item = std::result::Result<V, String>> + 'a>,
}

impl<'a, V: jaq_core::ValT + 'static> data::HasLut<'a, InputData<V>> for InputDataRef<'a, V> {
    fn lut(&self) -> &'a jaq_core::Lut<InputData<V>> {
        self.lut
    }
}

impl<'a, V: jaq_core::ValT + 'static> HasInputs<'a, V> for InputDataRef<'a, V> {
    fn inputs(&self) -> Inputs<'a, V> {
        self.inputs
    }
}

/// Convert serde_json::Value to jaq Val.
fn serde_to_val(v: serde_json::Value) -> Val {
    match v {
        serde_json::Value::Null => Val::Null,
        serde_json::Value::Bool(b) => Val::from(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                if let Ok(i) = isize::try_from(i) {
                    Val::from(i)
                } else {
                    Val::from(i as f64)
                }
            } else if let Some(f) = n.as_f64() {
                Val::from(f)
            } else {
                Val::from(0isize) // unreachable in practice
            }
        }
        serde_json::Value::String(s) => Val::from(s),
        serde_json::Value::Array(arr) => arr.into_iter().map(serde_to_val).collect(),
        serde_json::Value::Object(map) => Val::obj(
            map.into_iter()
                .map(|(k, v)| (Val::from(k), serde_to_val(v)))
                .collect(),
        ),
    }
}

/// Convert jaq Val to serde_json::Value for output formatting.
fn val_to_serde(v: &Val) -> serde_json::Value {
    match v {
        Val::Null => serde_json::Value::Null,
        Val::Bool(b) => serde_json::Value::Bool(*b),
        Val::Num(n) => {
            // Use Display to get the number string, then parse
            let s = format!("{n}");
            if let Ok(i) = s.parse::<i64>() {
                serde_json::Value::Number(serde_json::Number::from(i))
            } else if let Ok(f) = s.parse::<f64>() {
                serde_json::Number::from_f64(f)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::Null)
            } else {
                serde_json::Value::Null
            }
        }
        Val::BStr(_) | Val::TStr(_) => {
            // Extract string bytes and convert to UTF-8
            let displayed = format!("{v}");
            // Val's Display wraps strings in quotes — strip them
            if displayed.starts_with('"') && displayed.ends_with('"') {
                // Parse the JSON string to unescape
                serde_json::from_str(&displayed).unwrap_or(serde_json::Value::String(displayed))
            } else {
                serde_json::Value::String(displayed)
            }
        }
        Val::Arr(a) => serde_json::Value::Array(a.iter().map(val_to_serde).collect()),
        Val::Obj(o) => {
            let map: serde_json::Map<String, serde_json::Value> = o
                .iter()
                .map(|(k, v)| {
                    let key = match k {
                        Val::TStr(_) | Val::BStr(_) => {
                            let s = format!("{k}");
                            if s.starts_with('"') && s.ends_with('"') {
                                serde_json::from_str::<String>(&s).unwrap_or(s)
                            } else {
                                s
                            }
                        }
                        _ => format!("{k}"),
                    };
                    (key, val_to_serde(v))
                })
                .collect();
            serde_json::Value::Object(map)
        }
    }
}

/// THREAT[TM-DOS-027]: Maximum nesting depth for JSON input values.
/// Prevents stack overflow when jaq evaluates deeply nested JSON structures
/// like `[[[[...]]]]` or `{"a":{"a":{"a":...}}}`.
/// Also limits filter complexity indirectly since deeply nested filters
/// produce deeply nested parse trees in jaq.
const MAX_JQ_JSON_DEPTH: usize = 100;

/// Custom jq definitions prepended to every filter to patch jaq limitations:
/// - `setpath(p; v)`: recursive path-setting (not in jaq stdlib)
/// - `leaf_paths`: paths to scalar leaves (not in jaq stdlib)
/// - `match` override: adds `"name":null` to unnamed captures
/// - `scan` override: uses "g" flag for global matching (jq default)
const JQ_COMPAT_DEFS: &str = r#"
def setpath(p; v):
  if (p | length) == 0 then v
  else p[0] as $k |
    (if . == null then
      if ($k | type) == "number" then [] else {} end
    else . end) |
    .[$k] |= setpath(p[1:]; v)
  end;
def leaf_paths: paths(scalars);
def match(re; flags):
  matches(re; flags)[] |
  .[0] as $m |
  { offset: $m.offset, length: $m.length, string: $m.string,
    captures: [.[1:][] | { offset: .offset, length: .length, string: .string,
    name: (if has("name") then .name else null end) }] };
def match(re): match(re; "");
def scan(re; flags): matches(re; "g" + flags)[] | .[0].string;
def scan(re): scan(re; "");
"#;

/// Internal global variable name used to pass shell env to jq's `env` filter.
/// SECURITY: Replaces std::env::set_var() which was thread-unsafe and leaked
/// host process env vars. Shell variables are now passed as a jaq global
/// variable, and `def env:` is overridden to read from it.
const ENV_VAR_NAME: &str = "$__bashkit_env__";

/// jq command - JSON processor
pub struct Jq;

impl Jq {
    /// Parse multiple JSON values from input using streaming deserializer.
    /// Handles multi-line JSON, NDJSON, and concatenated JSON values.
    fn parse_json_values(input: &str) -> Result<Vec<serde_json::Value>> {
        use serde_json::Deserializer;

        let trimmed = input.trim();
        if trimmed.is_empty() {
            return Ok(Vec::new());
        }

        let mut vals = Vec::new();
        let stream = Deserializer::from_str(trimmed).into_iter::<serde_json::Value>();
        for result in stream {
            let json_input =
                result.map_err(|e| Error::Execution(format!("jq: invalid JSON: {}", e)))?;
            // THREAT[TM-DOS-027]: Check nesting depth before evaluation
            check_json_depth(&json_input, MAX_JQ_JSON_DEPTH).map_err(Error::Execution)?;
            vals.push(json_input);
        }
        Ok(vals)
    }
}

/// THREAT[TM-DOS-027]: Check JSON nesting depth to prevent stack overflow
/// during jaq filter evaluation on deeply nested input.
fn check_json_depth(
    value: &serde_json::Value,
    max_depth: usize,
) -> std::result::Result<(), String> {
    fn measure_depth(
        v: &serde_json::Value,
        current: usize,
        max: usize,
    ) -> std::result::Result<(), String> {
        if current > max {
            return Err(format!(
                "jq: JSON nesting too deep ({} levels, max {})",
                current, max
            ));
        }
        match v {
            serde_json::Value::Array(arr) => {
                for item in arr {
                    measure_depth(item, current + 1, max)?;
                }
            }
            serde_json::Value::Object(map) => {
                for (_k, item) in map {
                    measure_depth(item, current + 1, max)?;
                }
            }
            _ => {}
        }
        Ok(())
    }
    measure_depth(value, 0, max_depth)
}

/// Recursively sort all object keys in a JSON value
fn sort_json_keys(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => {
            let mut sorted: Vec<(String, serde_json::Value)> = map
                .into_iter()
                .map(|(k, v)| (k, sort_json_keys(v)))
                .collect();
            sorted.sort_by(|a, b| a.0.cmp(&b.0));
            serde_json::Value::Object(sorted.into_iter().collect())
        }
        serde_json::Value::Array(arr) => {
            serde_json::Value::Array(arr.into_iter().map(sort_json_keys).collect())
        }
        other => other,
    }
}

/// Format JSON with tabs instead of spaces
fn format_with_tabs(value: &serde_json::Value) -> String {
    let pretty = serde_json::to_string_pretty(value).unwrap_or_default();
    // Replace 2-space indentation with tabs
    let mut result = String::new();
    for line in pretty.lines() {
        let spaces = line.len() - line.trim_start().len();
        let tabs = spaces / 2;
        result.push_str(&"\t".repeat(tabs));
        result.push_str(line.trim_start());
        result.push('\n');
    }
    // Remove trailing newline to match pattern
    result.truncate(result.trim_end_matches('\n').len());
    result
}

#[async_trait]
impl Builtin for Jq {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        // jq uses -h for help and -V for version (unlike GNU coreutils)
        let help_text = "Usage: jq [OPTIONS...] FILTER [FILE...]\n\n\
             \tjq is a command-line JSON processor.\n\n\
             Options:\n\
             \t-c, --compact-output\tcompact instead of pretty-printed output\n\
             \t-r, --raw-output\toutput strings without escapes and quotes\n\
             \t-R, --raw-input\t\tread each line as string instead of JSON\n\
             \t-s, --slurp\t\tread entire input into a single array\n\
             \t-n, --null-input\tuse null as the single input value\n\
             \t-e, --exit-status\tset exit status code based on output\n\
             \t-S, --sort-keys\t\tsort object keys in output\n\
             \t-j, --join-output\tlike -r without trailing newline\n\
             \t--tab\t\t\tuse tabs for indentation\n\
             \t--indent N\t\tuse N spaces for indentation (default: 2)\n\
             \t--arg name value\tset variable $name to string value\n\
             \t--argjson name value\tset variable $name to JSON value\n\
             \t--args\t\t\tremaining args are string arguments\n\
             \t--jsonargs\t\tremaining args are JSON arguments\n\
             \t-V, --version\t\toutput version information and exit\n\
             \t-h, --help\t\toutput this help and exit\n";
        for arg in ctx.args {
            match arg.as_str() {
                "-h" | "--help" => return Ok(ExecResult::ok(help_text.to_string())),
                "-V" | "--version" => return Ok(ExecResult::ok("jq-1.8\n".to_string())),
                _ => {}
            }
        }

        // Parse arguments for flags using index-based loop to support
        // multi-arg flags like --arg name value and --argjson name value.
        let mut raw_output = false;
        let mut raw_input = false;
        let mut compact_output = false;
        let mut null_input = false;
        let mut sort_keys = false;
        let mut slurp = false;
        let mut exit_status = false;
        let mut tab_indent = false;
        let mut join_output = false;
        let mut filter = ".";
        let mut file_args: Vec<&str> = Vec::new();
        // Store variable bindings as (name, serde_json::Value) to avoid
        // holding non-Send jaq Val across await points.
        let mut var_bindings: Vec<(String, serde_json::Value)> = Vec::new();

        let mut found_filter = false;
        let mut i = 0;
        while i < ctx.args.len() {
            let arg = &ctx.args[i];
            if found_filter {
                // Everything after the filter is a file argument
                file_args.push(arg);
                i += 1;
                continue;
            }

            if arg == "--" {
                // End of options: next arg is filter, rest are files
                i += 1;
                if i < ctx.args.len() {
                    filter = &ctx.args[i];
                    found_filter = true;
                }
                i += 1;
                continue;
            }

            if arg == "--raw-output" {
                raw_output = true;
            } else if arg == "--raw-input" {
                raw_input = true;
            } else if arg == "--compact-output" {
                compact_output = true;
            } else if arg == "--null-input" {
                null_input = true;
            } else if arg == "--sort-keys" {
                sort_keys = true;
            } else if arg == "--slurp" {
                slurp = true;
            } else if arg == "--exit-status" {
                exit_status = true;
            } else if arg == "--tab" {
                tab_indent = true;
            } else if arg == "--join-output" {
                join_output = true;
            } else if arg == "--arg" {
                // --arg name value: bind $name to string value
                if i + 2 < ctx.args.len() {
                    let name = format!("${}", &ctx.args[i + 1]);
                    let value = serde_json::Value::String(ctx.args[i + 2].to_string());
                    var_bindings.push((name, value));
                    i += 3;
                    continue;
                }
                i += 1;
                continue;
            } else if arg == "--argjson" {
                // --argjson name value: bind $name to parsed JSON value
                if i + 2 < ctx.args.len() {
                    let name = format!("${}", &ctx.args[i + 1]);
                    let json_val: serde_json::Value = match serde_json::from_str(&ctx.args[i + 2]) {
                        Ok(v) => v,
                        Err(e) => {
                            return Ok(ExecResult::err(
                                format!("jq: invalid JSON for --argjson: {}\n", e),
                                2,
                            ));
                        }
                    };
                    var_bindings.push((name, json_val));
                    i += 3;
                    continue;
                }
                i += 1;
                continue;
            } else if arg == "--indent" {
                // --indent N: skip the numeric argument (use default formatting)
                i += 2;
                continue;
            } else if arg == "--args" || arg == "--jsonargs" {
                // Remaining args are positional, not files; skip for now
                i += 1;
                continue;
            } else if arg.starts_with("--") {
                // Unknown long flag: skip
            } else if arg.starts_with('-') && arg.len() > 1 {
                // Short flag(s): may be combined like -rn, -sc, -snr
                for ch in arg[1..].chars() {
                    match ch {
                        'r' => raw_output = true,
                        'R' => raw_input = true,
                        'c' => compact_output = true,
                        'n' => null_input = true,
                        'S' => sort_keys = true,
                        's' => slurp = true,
                        'e' => exit_status = true,
                        'j' => join_output = true,
                        _ => {} // ignore unknown short flags
                    }
                }
            } else {
                // Non-flag argument: this is the filter
                filter = arg;
                found_filter = true;
            }
            i += 1;
        }

        // Build input: read from file arguments if provided, otherwise stdin
        let file_content: String;
        let input = if !file_args.is_empty() {
            let mut combined = String::new();
            for file_arg in &file_args {
                let path = resolve_path(ctx.cwd, file_arg);
                let text = match read_text_file(&*ctx.fs, &path, "jq").await {
                    Ok(t) => t,
                    Err(e) => return Ok(e),
                };
                if !combined.is_empty() && !combined.ends_with('\n') {
                    combined.push('\n');
                }
                combined.push_str(&text);
            }
            file_content = combined;
            file_content.as_str()
        } else {
            ctx.stdin.unwrap_or("")
        };

        // If no input and not null_input mode, return empty
        // (but not for -Rs: raw_input+slurp should produce "" for empty stdin)
        if input.trim().is_empty() && !null_input && !(raw_input && slurp) {
            return Ok(ExecResult::ok(String::new()));
        }

        // Set up the loader with standard library definitions
        let defs = jaq_core::defs()
            .chain(jaq_std::defs())
            .chain(jaq_json::defs());
        let loader = Loader::new(defs);
        let arena = Arena::default();

        // Build shell env as a JSON object for the custom `env` filter.
        // SECURITY: This avoids calling std::env::set_var() which is
        // thread-unsafe and leaks host process env vars (TM-INF-013).
        // ctx.env takes precedence over ctx.variables (prefix assignments
        // like FOO=bar jq ... shadow exported variables).
        let env_obj = {
            let mut map = serde_json::Map::new();
            // variables first, then env overrides (last write wins)
            for (k, v) in ctx.variables.iter().chain(ctx.env.iter()) {
                map.insert(k.clone(), serde_json::Value::String(v.clone()));
            }
            serde_json::Value::Object(map)
        };

        // Prepend compatibility definitions (setpath, leaf_paths, match, scan)
        // to override jaq's defaults with jq-compatible behavior.
        // Also override `env` to read from our injected variable instead of
        // the process environment.
        let env_def = format!("def env: {};", ENV_VAR_NAME);
        let compat_filter = format!("{}\n{}\n{}", JQ_COMPAT_DEFS, env_def, filter);
        let filter = compat_filter.as_str();

        // Parse the filter
        let program = File {
            code: filter,
            path: (),
        };

        let modules = match loader.load(&arena, program) {
            Ok(m) => m,
            Err(errs) => {
                let msg = format!(
                    "jq: parse error: {}\n",
                    errs.into_iter()
                        .map(|e| format!("{:?}", e))
                        .collect::<Vec<_>>()
                        .join(", ")
                );
                return Ok(ExecResult::err(msg, 3));
            }
        };

        // Compile the filter, registering any --arg/--argjson variable names
        // plus the internal $__bashkit_env__ variable.
        // Filter out jaq-std's native `env` filter since we override it with
        // a def that reads from our injected global variable.
        let mut var_names: Vec<&str> = var_bindings.iter().map(|(n, _)| n.as_str()).collect();
        var_names.push(ENV_VAR_NAME);
        type D = InputData<Val>;
        let input_funs: Vec<jaq_core::native::Fun<D>> = jaq_std::input::funs::<D>()
            .into_vec()
            .into_iter()
            .map(|(name, arity, run)| (name, arity, jaq_core::Native::<D>::new(run)))
            .collect();
        let native_funs = jaq_core::funs::<D>()
            .chain(jaq_std::funs::<D>().filter(|(name, _, _)| *name != "env"))
            .chain(input_funs)
            .chain(jaq_json::funs::<D>());
        let compiler = Compiler::default()
            .with_funs(native_funs)
            .with_global_vars(var_names.iter().copied());
        let filter = match compiler.compile(modules) {
            Ok(f) => f,
            Err(errs) => {
                let msg = format!(
                    "jq: compile error: {}\n",
                    errs.into_iter()
                        .map(|e| format!("{:?}", e))
                        .collect::<Vec<_>>()
                        .join(", ")
                );
                return Ok(ExecResult::err(msg, 3));
            }
        };

        // Process input as JSON
        let mut output = String::new();

        // Build list of inputs to process
        let inputs_to_process: Vec<Val> = if null_input {
            // -n flag: use null as input
            vec![Val::Null]
        } else if raw_input && slurp {
            // -Rs flag: read entire input as single string
            vec![Val::from(input.to_string())]
        } else if raw_input {
            // -R flag: each line becomes a JSON string value
            input
                .lines()
                .map(|line| Val::from(line.to_string()))
                .collect()
        } else if slurp {
            // -s flag: read all inputs into a single array
            match Self::parse_json_values(input) {
                Ok(vals) => vec![serde_to_val(serde_json::Value::Array(vals))],
                Err(e) => return Ok(ExecResult::err(format!("{}\n", e), 5)),
            }
        } else {
            // Parse all JSON values from input (handles multi-line and NDJSON)
            match Self::parse_json_values(input) {
                Ok(json_vals) => json_vals.into_iter().map(serde_to_val).collect(),
                Err(e) => return Ok(ExecResult::err(format!("{}\n", e), 5)),
            }
        };

        // Track for -e exit status
        let mut has_output = false;
        let mut all_null_or_false = true;

        // Shared input iterator: main loop pops one value per filter run,
        // and jaq's input/inputs functions consume from the same source.
        let iter: Box<dyn Iterator<Item = std::result::Result<Val, String>>> =
            Box::new(inputs_to_process.into_iter().map(Ok::<Val, String>));
        let shared_inputs = RcIter::new(iter);

        // Pre-convert env object to jaq Val once (reused for each input)
        let env_val = serde_to_val(env_obj);

        for jaq_input in &shared_inputs {
            let jaq_input: Val = match jaq_input {
                Ok(v) => v,
                Err(e) => {
                    return Ok(ExecResult::err(format!("jq: input error: {}\n", e), 5));
                }
            };

            // Run the filter, passing --arg/--argjson variable values
            // plus the env object as the last global variable.
            let mut var_vals: Vec<Val> = var_bindings
                .iter()
                .map(|(_, v)| serde_to_val(v.clone()))
                .collect();
            var_vals.push(env_val.clone());
            let data = InputDataRef {
                lut: &filter.lut,
                inputs: &shared_inputs,
            };
            let ctx = Ctx::<InputData<Val>>::new(data, Vars::new(var_vals));
            for result in filter.id.run((ctx, jaq_input)) {
                match result {
                    Ok(val) => {
                        has_output = true;
                        // Convert back to serde_json::Value and format
                        let json = val_to_serde(&val);

                        // Track for -e exit status
                        if !matches!(
                            json,
                            serde_json::Value::Null | serde_json::Value::Bool(false)
                        ) {
                            all_null_or_false = false;
                        }

                        // Apply sort_keys if -S flag is set
                        let json = if sort_keys {
                            sort_json_keys(json)
                        } else {
                            json
                        };

                        // -j implies raw output for strings
                        let effective_raw = raw_output || join_output;

                        // In raw mode or join mode, strings are output without quotes
                        if effective_raw {
                            if let serde_json::Value::String(s) = &json {
                                output.push_str(s);
                                if !join_output {
                                    output.push('\n');
                                }
                            } else {
                                // For non-strings, use appropriate formatting
                                let formatted = if compact_output {
                                    serde_json::to_string(&json)
                                } else if tab_indent {
                                    Ok(format_with_tabs(&json))
                                } else {
                                    match &json {
                                        serde_json::Value::Array(_)
                                        | serde_json::Value::Object(_) => {
                                            serde_json::to_string_pretty(&json)
                                        }
                                        _ => serde_json::to_string(&json),
                                    }
                                };
                                match formatted {
                                    Ok(s) => {
                                        output.push_str(&s);
                                        if !join_output {
                                            output.push('\n');
                                        }
                                    }
                                    Err(e) => {
                                        return Ok(ExecResult::err(
                                            format!("jq: output error: {}\n", e),
                                            5,
                                        ));
                                    }
                                }
                            }
                        } else if compact_output {
                            // Compact mode: no pretty-printing
                            match serde_json::to_string(&json) {
                                Ok(s) => {
                                    output.push_str(&s);
                                    output.push('\n');
                                }
                                Err(e) => {
                                    return Ok(ExecResult::err(
                                        format!("jq: output error: {}\n", e),
                                        5,
                                    ));
                                }
                            }
                        } else if tab_indent {
                            // Tab indentation mode
                            let formatted = format_with_tabs(&json);
                            output.push_str(&formatted);
                            output.push('\n');
                        } else {
                            // Use pretty-print for arrays/objects to match real jq behavior
                            let formatted = match &json {
                                serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
                                    serde_json::to_string_pretty(&json)
                                }
                                _ => serde_json::to_string(&json),
                            };
                            match formatted {
                                Ok(s) => {
                                    output.push_str(&s);
                                    output.push('\n');
                                }
                                Err(e) => {
                                    return Ok(ExecResult::err(
                                        format!("jq: output error: {}\n", e),
                                        5,
                                    ));
                                }
                            }
                        }
                    }
                    Err(e) => {
                        return Ok(ExecResult::err(format!("jq: runtime error: {:?}\n", e), 5));
                    }
                }
            }
        }

        // Ensure output ends with newline if there's output (for consistency),
        // but not when -j/--join-output is set (it suppresses trailing newline).
        if !join_output && !output.is_empty() && !output.ends_with('\n') {
            output.push('\n');
        }

        // Handle -e exit status flag
        if exit_status && (!has_output || all_null_or_false) {
            return Ok(ExecResult::with_code(output, 1));
        }

        Ok(ExecResult::ok(output))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{FileSystem, InMemoryFs};
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    async fn run_jq(filter: &str, input: &str) -> Result<String> {
        let jq = Jq;
        let fs = Arc::new(InMemoryFs::new());
        let mut vars = HashMap::new();
        let mut cwd = PathBuf::from("/");
        let args = vec![filter.to_string()];

        let ctx = Context {
            args: &args,
            env: &HashMap::new(),
            variables: &mut vars,
            cwd: &mut cwd,
            fs,
            stdin: Some(input),
            #[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?;
        Ok(result.stdout)
    }

    #[tokio::test]
    async fn test_jq_identity() {
        let result = run_jq(".", r#"{"name":"test"}"#).await.unwrap();
        // Pretty-printed output to match real jq behavior
        assert_eq!(result.trim(), "{\n  \"name\": \"test\"\n}");
    }

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

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

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

    #[tokio::test]
    async fn test_jq_keys() {
        let result = run_jq("keys", r#"{"b":1,"a":2}"#).await.unwrap();
        // Pretty-printed array output to match real jq behavior
        assert_eq!(result.trim(), "[\n  \"a\",\n  \"b\"\n]");
    }

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

    async fn run_jq_with_args(args: &[&str], input: &str) -> Result<String> {
        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(input),
            #[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?;
        Ok(result.stdout)
    }

    async fn run_jq_result(filter: &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![filter.to_string()];

        let ctx = Context {
            args: &args,
            env: &HashMap::new(),
            variables: &mut vars,
            cwd: &mut cwd,
            fs,
            stdin: Some(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_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(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
    }

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

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

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

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

    /// TM-DOS-027: Deeply nested JSON arrays must be rejected
    /// Note: serde_json has a built-in recursion limit (~128 levels) that fires first.
    /// Our check_json_depth is defense-in-depth for values within serde's limit.
    #[tokio::test]
    async fn test_jq_input_reads_next() {
        let result = run_jq_with_args(&["input"], "1\n2").await.unwrap();
        assert_eq!(result.trim(), "2");
    }

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

    #[tokio::test]
    async fn test_jq_inputs_single_value() {
        // With single input, inputs yields empty array
        let result = run_jq_with_args(&["-c", "[inputs]"], "42").await.unwrap();
        assert_eq!(result.trim(), "[]");
    }

    #[tokio::test]
    async fn test_jq_json_depth_limit_arrays() {
        // Build 150-level nested JSON: [[[[....[1]....]]]]
        let depth = 150;
        let open = "[".repeat(depth);
        let close = "]".repeat(depth);
        let input = format!("{open}1{close}");

        let result = run_jq_result(".", &input).await.unwrap();
        assert!(
            result.exit_code != 0,
            "deeply nested JSON arrays must be rejected"
        );
        assert!(
            result.stderr.contains("nesting too deep") || result.stderr.contains("recursion limit"),
            "error should mention nesting or recursion limit: {}",
            result.stderr
        );
    }

    /// TM-DOS-027: Deeply nested JSON objects must be rejected
    #[tokio::test]
    async fn test_jq_json_depth_limit_objects() {
        // Build 150-level nested JSON objects: {"a":{"a":{"a":...}}}
        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,
            "deeply nested JSON objects must be rejected"
        );
        assert!(
            result.stderr.contains("nesting too deep") || result.stderr.contains("recursion limit"),
            "error should mention nesting or recursion limit: {}",
            result.stderr
        );
    }

    /// TM-DOS-027: Moderate JSON nesting within limit still works
    #[tokio::test]
    async fn test_jq_moderate_nesting_ok() {
        // 10 levels of nesting should be fine
        let depth = 10;
        let open = "[".repeat(depth);
        let close = "]".repeat(depth);
        let input = format!("{open}1{close}");

        let result = run_jq(".", &input).await;
        assert!(
            result.is_ok(),
            "moderate nesting should succeed: {:?}",
            result.err()
        );
    }

    /// TM-DOS-027: check_json_depth unit test
    #[test]
    fn test_check_json_depth() {
        // Flat value: ok
        let v = serde_json::json!(42);
        assert!(check_json_depth(&v, 100).is_ok());

        // 3-level nesting with limit 5: ok
        let v = serde_json::json!([[[1]]]);
        assert!(check_json_depth(&v, 5).is_ok());

        // 3-level nesting with limit 2: rejected
        assert!(check_json_depth(&v, 2).is_err());
    }

    /// Helper: run jq with file arguments on an in-memory filesystem
    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 {
            // Ensure parent directory exists
            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
    }

    #[tokio::test]
    async fn test_jq_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 test_jq_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);
        // Each file produces its own output
        let lines: Vec<&str> = result.stdout.trim().split('\n').collect();
        assert!(result.stdout.contains("\"x\": 1"), "should contain x:1");
        assert!(result.stdout.contains("\"y\": 2"), "should contain y:2");
        // Two separate JSON objects
        assert!(
            lines.len() > 3,
            "should have multi-line output for two objects"
        );
    }

    #[tokio::test]
    async fn test_jq_slurp_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);
        // Slurp should wrap both objects in an array
        assert!(result.stdout.contains("\"x\": 1"), "should contain x:1");
        assert!(result.stdout.contains("\"y\": 2"), "should contain y:2");
        // Verify it's an array
        let parsed: serde_json::Value = serde_json::from_str(result.stdout.trim()).unwrap();
        assert!(parsed.is_array(), "slurp output should be an array");
        assert_eq!(parsed.as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_jq_file_not_found() {
        let result = run_jq_with_files(&[".", "/missing.json"], &[])
            .await
            .unwrap();
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("jq: /missing.json:"));
    }

    #[tokio::test]
    async fn test_jq_slurp_files_in_subdir() {
        // Matches the reported scenario: jq -s '.' /workspace/json_data/*.json
        let result = run_jq_with_files(
            &[
                "-s",
                ".",
                "/workspace/json_data/a.json",
                "/workspace/json_data/b.json",
            ],
            &[
                ("/workspace/json_data/a.json", r#"{"id":1}"#),
                ("/workspace/json_data/b.json", r#"{"id":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());
        let arr = parsed.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["id"], 1);
        assert_eq!(arr[1]["id"], 2);
    }

    // --- env tests ---

    #[tokio::test]
    async fn test_jq_env_access() {
        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 test_jq_env_missing_var() {
        let jq = Jq;
        let fs = Arc::new(InMemoryFs::new());
        let mut vars = HashMap::new();
        let mut cwd = PathBuf::from("/");
        let args = vec!["-n".to_string(), "env.NO_SUCH_VAR_999".to_string()];

        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,
        };

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

    // --- Argument parsing bug regression tests ---

    #[tokio::test]
    async fn test_jq_combined_short_flags() {
        // -rn should be parsed as -r + -n
        let result = run_jq_with_args(&["-rn", "1+1"], "").await.unwrap();
        assert_eq!(result.trim(), "2");
    }

    #[tokio::test]
    async fn test_jq_combined_flags_sc() {
        // -sc should be parsed as -s + -c
        let result = run_jq_with_args(&["-sc", "add"], "1\n2\n3\n")
            .await
            .unwrap();
        assert_eq!(result.trim(), "6");
    }

    #[tokio::test]
    async fn test_jq_arg_flag() {
        // --arg name value: $name should resolve to "value" in the filter
        let result = run_jq_with_args(&["--arg", "name", "world", "-n", r#""hello \($name)""#], "")
            .await
            .unwrap();
        assert_eq!(result.trim(), r#""hello world""#);
    }

    #[tokio::test]
    async fn test_jq_argjson_flag() {
        // --argjson count 5: $count should resolve to 5 (number, not string)
        let result = run_jq_with_args(&["--argjson", "count", "5", "-n", "$count + 1"], "")
            .await
            .unwrap();
        assert_eq!(result.trim(), "6");
    }

    #[tokio::test]
    async fn test_jq_arg_does_not_eat_filter() {
        // --arg name value '.' should NOT treat '.' as a file
        let result = run_jq_with_args(&["--arg", "x", "hello", "."], r#"{"a":1}"#)
            .await
            .unwrap();
        assert!(result.contains("\"a\": 1"));
    }

    #[tokio::test]
    async fn test_jq_double_dash_separator() {
        // -- ends option parsing; next arg is filter
        let result = run_jq_with_args(&["-n", "--", "1+1"], "").await.unwrap();
        assert_eq!(result.trim(), "2");
    }

    #[tokio::test]
    async fn test_jq_indent_flag() {
        // --indent 4 should not eat the filter
        let result = run_jq_with_args(&["--indent", "4", "."], r#"{"a":1}"#)
            .await
            .unwrap();
        assert!(result.contains("\"a\""));
    }

    // --- Negative tests ---

    #[tokio::test]
    async fn test_jq_invalid_json_input() {
        let result = run_jq_result(".", "not valid json").await.unwrap();
        assert!(
            result.exit_code != 0,
            "invalid JSON input should have non-zero exit"
        );
        assert!(
            result.stderr.contains("jq:"),
            "should have jq error in stderr"
        );
    }

    #[tokio::test]
    async fn test_jq_invalid_filter_syntax() {
        let result = run_jq_result(".[", r#"{"a":1}"#).await.unwrap();
        assert!(
            result.exit_code != 0,
            "invalid filter should have non-zero exit"
        );
        assert!(
            result.stderr.contains("jq:"),
            "should have jq error in stderr"
        );
    }

    #[tokio::test]
    async fn test_jq_invalid_argjson_value() {
        let result = run_jq_result_with_args(&["--argjson", "x", "not json", "-n", "$x"], "")
            .await
            .unwrap();
        assert!(
            result.exit_code != 0,
            "invalid JSON for --argjson should have non-zero exit"
        );
    }

    #[tokio::test]
    async fn test_jq_empty_input_no_null() {
        // Empty stdin without -n should produce empty output, not error
        let result = run_jq(".", "").await.unwrap();
        assert_eq!(result, "");
    }

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

    #[tokio::test]
    async fn test_jq_ndjson_multiple_values() {
        // Multiple JSON values on separate lines (NDJSON)
        let result = run_jq(".a", "{\"a\":1}\n{\"a\":2}\n").await.unwrap();
        assert_eq!(result.trim(), "1\n2");
    }

    #[tokio::test]
    async fn test_jq_exit_status_false() {
        // -e flag: false output -> exit code 1
        let jq = Jq;
        let fs = Arc::new(InMemoryFs::new());
        let mut vars = HashMap::new();
        let mut cwd = PathBuf::from("/");
        let args = vec!["-e".to_string(), ".".to_string()];
        let ctx = Context {
            args: &args,
            env: &HashMap::new(),
            variables: &mut vars,
            cwd: &mut cwd,
            fs,
            stdin: Some("false"),
            #[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.exit_code, 1, "-e with false should exit 1");
    }

    #[tokio::test]
    async fn test_jq_exit_status_truthy() {
        // -e flag: truthy output -> exit code 0
        let jq = Jq;
        let fs = Arc::new(InMemoryFs::new());
        let mut vars = HashMap::new();
        let mut cwd = PathBuf::from("/");
        let args = vec!["-e".to_string(), ".".to_string()];
        let ctx = Context {
            args: &args,
            env: &HashMap::new(),
            variables: &mut vars,
            cwd: &mut cwd,
            fs,
            stdin: Some("42"),
            #[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.exit_code, 0, "-e with truthy value should exit 0");
    }

    #[tokio::test]
    async fn test_jq_multiple_arg_bindings() {
        let result = run_jq_with_args(
            &[
                "--arg",
                "x",
                "hello",
                "--arg",
                "y",
                "world",
                "-n",
                r#""[\($x)] [\($y)]""#,
            ],
            "",
        )
        .await
        .unwrap();
        assert_eq!(result.trim(), r#""[hello] [world]""#);
    }

    #[tokio::test]
    async fn test_jq_combined_flags_snr() {
        // -snr: slurp + null-input + raw-output
        let result = run_jq_with_args(&["-snr", r#""hello""#], "").await.unwrap();
        assert_eq!(result.trim(), "hello");
    }

    #[tokio::test]
    async fn test_jq_raw_input() {
        // -R: each line becomes a JSON string
        let result = run_jq_with_args(&["-R", "."], "hello\nworld\n")
            .await
            .unwrap();
        assert_eq!(result.trim(), "\"hello\"\n\"world\"");
    }

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

    #[tokio::test]
    async fn test_jq_raw_input_split() {
        // -R -s then split: CSV-like processing
        let result = run_jq_with_args(
            &["-Rs", r#"split("\n") | map(select(length>0))"#],
            "a,b,c\n1,2,3\n",
        )
        .await
        .unwrap();
        assert!(result.contains("a,b,c"));
        assert!(result.contains("1,2,3"));
    }

    #[tokio::test]
    async fn test_jq_raw_input_slurp_empty_stdin() {
        // -Rs on empty stdin should produce "" (empty JSON string), not nothing
        let result = run_jq_with_args(&["-Rs", "."], "").await.unwrap();
        assert_eq!(result.trim(), "\"\"");
    }

    // --- Process env pollution tests (issue #410) ---

    #[tokio::test]
    async fn test_jq_env_no_process_pollution() {
        // Shell variables passed via ctx.env must NOT leak into the process
        // environment. This is a security issue: std::env::set_var() is
        // thread-unsafe and exposes host env vars to jaq's `env` function.
        let unique_key = "BASHKIT_TEST_ENV_POLLUTION_410";

        // Ensure the var is not already in the process env
        assert!(
            std::env::var(unique_key).is_err(),
            "precondition: {} must not exist in process env",
            unique_key
        );

        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();
        // The jq filter should still see the variable via our custom env
        assert_eq!(result.stdout.trim(), "\"leaked\"");

        // CRITICAL: The process environment must NOT have been modified
        assert!(
            std::env::var(unique_key).is_err(),
            "process env was polluted with shell variable {}",
            unique_key
        );
    }

    #[tokio::test]
    async fn test_jq_env_no_host_leak() {
        // Host process env vars should NOT be visible to jq's env filter.
        // Only shell variables from ctx.env/ctx.variables should be exposed.
        let unique_key = "BASHKIT_TEST_HOST_LEAK_410";

        // Set a host process env var that should NOT be visible to jq
        // SAFETY: This test is single-threaded (serial_test) so set_var is safe
        unsafe { std::env::set_var(unique_key, "host_secret") };

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

        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,
        };

        let result = jq.execute(ctx).await.unwrap();
        // Host env var should NOT be visible - should return null
        assert_eq!(
            result.stdout.trim(),
            "null",
            "host env var {} leaked into jq env",
            unique_key
        );

        // Cleanup
        // SAFETY: This test is single-threaded (serial_test) so remove_var is safe
        unsafe { std::env::remove_var(unique_key) };
    }

    // ========================================================================
    // jq 1.8 builtins (issue #616)
    // ========================================================================

    #[tokio::test]
    async fn test_jq_version_string() {
        let result = run_jq_result_with_args(&["--version"], "null")
            .await
            .unwrap();
        assert_eq!(result.stdout.trim(), "jq-1.8");
    }

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

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

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

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

    #[tokio::test]
    async fn test_jq_if_without_else() {
        // jq 1.8: `if COND then EXPR end` 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 test_jq_paths_with_filter() {
        // jaq 2.x: paths/1 returns paths matching a 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();
        // Should contain ["a"] and ["b","c"]
        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 test_jq_getpath() {
        // jaq 2.x: getpath/1
        assert_eq!(
            run_jq(r#"getpath(["a","b"])"#, r#"{"a":{"b":42}}"#)
                .await
                .unwrap()
                .trim(),
            "42"
        );
    }

    #[tokio::test]
    async fn test_jq_help() {
        let result = run_jq_with_args(&["--help"], "").await.unwrap();
        assert!(result.contains("Usage:"), "should contain usage info");
        assert!(result.contains("jq"), "should mention jq");
    }

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