bun_runtime 0.1.0

Bao runtime integration — JS engine + Bun API + event loop
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
// @trace REQ-BAO-API-018 [api:Bun.Shell/$] — Shell class + Interpreter bridge
//! Bun.Shell / Bun.$ — bridge to bun_shell_parser + bun_spawn.
//!
//! Reuses bun_shell_parser::Lexer/Parser/AST for command parsing and
//! bun_spawn::run for subprocess execution.
//! No hand-written shell parsing or process management code.

use ::std::collections::HashMap;
use ::std::ptr::{self, NonNull};
use ::std::sync::atomic::{AtomicU64, Ordering};

use mozjs::jsapi::*;
use mozjs::jsval::{
    BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, ObjectValue, StringValue,
    UndefinedValue,
};
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;

// ──────────────────── bun_shell_parser reuse ────────────────────
// @trace REQ-BAO-API-018 [reuse:bun_shell_parser] — Lexer/Parser/AST replaces hand-written parsing

use bun_alloc::Arena as Bump;
use bun_shell_parser::ast;
use bun_shell_parser::parse::{self as shell_parse, Lexer, Parser};

// ──────────────────── bun_spawn reuse ────────────────────
// @trace REQ-BAO-API-018 [reuse:bun_spawn] — spawn/run replaces std::process::Command

use bun_spawn::{RunOptions, Term, run};

// ──────────────────── ID counters ────────────────────

static SHELL_ID_COUNTER: AtomicU64 = AtomicU64::new(0);

// ──────────────────── Shell execution state ────────────────────

thread_local! {
    /// Active Shell instances (by shell_id), holding env overrides + cwd.
    static SHELL_INSTANCES: ::std::cell::RefCell<HashMap<u64, ShellState>> =
        ::std::cell::RefCell::new(HashMap::new());
}

/// Per-Shell instance state (env overrides + cwd).
struct ShellState {
    env: Option<HashMap<String, String>>,
    cwd: Option<String>,
}

// ──────────────────── ShellInterpreter ────────────────────

/// Shell interpreter that walks the bun_shell_parser AST and executes commands
/// via bun_spawn::run. Replaces hand-written pipeline/redirect/env parsing.
///
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter]
struct ShellInterpreter<'a> {
    env_override: Option<&'a HashMap<String, String>>,
    cwd_override: Option<&'a str>,
}

impl<'a> ShellInterpreter<'a> {
    fn new(
        env_override: Option<&'a HashMap<String, String>>,
        cwd_override: Option<&'a str>,
    ) -> Self {
        Self {
            env_override,
            cwd_override,
        }
    }

    /// Parse a command string using bun_shell_parser::Lexer + Parser, then interpret.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.parse_and_run]
    fn parse_and_run(&self, command: &str) -> ShellOutput {
        let command = command.trim();
        if command.is_empty() {
            return ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            };
        }

        // Use bun_shell_parser to lex + parse the command string
        let bump = Bump::new();
        let src = command.as_bytes();

        // Lex: Lexer requires &mut [BunString] for string escaping refs.
        // Allocate an empty slice from the bump allocator to satisfy the lifetime.
        let string_refs: &mut [bun_core::String] = bump.alloc_slice_fill_default(0);
        let mut lexer = Lexer::<{ shell_parse::StringEncoding::Ascii }>::new(
            &bump,
            src,
            string_refs,
            0, // no JS object refs
        );

        if let Err(e) = lexer.lex() {
            return ShellOutput {
                stdout: Vec::new(),
                stderr: format!("Bun.Shell: lex error: {:?}", e).into_bytes(),
                exit_code: 1,
            };
        }

        let lex_result = lexer.get_result();

        // Parse: Parser consumes lex output → AST
        let mut jsobjs: [bun_shell_parser::JSValueRaw; 0] = [];
        let parser = match Parser::new(&bump, lex_result, &mut jsobjs) {
            Ok(p) => p,
            Err(e) => {
                return ShellOutput {
                    stdout: Vec::new(),
                    stderr: format!("Bun.Shell: parse error: {:?}", e).into_bytes(),
                    exit_code: 1,
                };
            }
        };

        // The parser borrows bump-allocated data; we need to parse + interpret
        // within the same scope.
        let mut parser = parser;
        let script = match parser.parse() {
            Ok(s) => s,
            Err(e) => {
                return ShellOutput {
                    stdout: Vec::new(),
                    stderr: format!("Bun.Shell: parse error: {:?}", e).into_bytes(),
                    exit_code: 1,
                };
            }
        };

        // Walk the AST and execute
        self.interpret_script(&script)
    }

    /// Walk ast::Script and execute each statement.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_script]
    fn interpret_script<'bump>(&self, script: &ast::Script<'bump>) -> ShellOutput {
        let mut last_output = ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
        };

        for stmt in script.stmts.iter() {
            last_output = self.interpret_stmt(stmt);
            // Stop on failure (like `set -e`)
            if last_output.exit_code != 0 {
                return last_output;
            }
        }

        last_output
    }

    /// Interpret a single statement (list of expressions separated by ; or &&/||).
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_stmt]
    fn interpret_stmt<'bump>(&self, stmt: &ast::Stmt<'bump>) -> ShellOutput {
        let mut last_output = ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
        };

        for expr in stmt.exprs.iter() {
            last_output = self.interpret_expr(expr);
        }

        last_output
    }

    /// Interpret an expression (pipeline, binary, cond, subshell, if, etc.).
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_expr]
    fn interpret_expr<'bump>(&self, expr: &ast::Expr<'bump>) -> ShellOutput {
        match expr {
            ast::Expr::Pipeline(pipeline) => self.interpret_pipeline(pipeline),
            ast::Expr::Binary(binary) => {
                let left = self.interpret_expr(&binary.left);
                match binary.op {
                    ast::BinaryOp::And => {
                        if left.exit_code == 0 {
                            self.interpret_expr(&binary.right)
                        } else {
                            left
                        }
                    }
                    ast::BinaryOp::Or => {
                        if left.exit_code != 0 {
                            self.interpret_expr(&binary.right)
                        } else {
                            left
                        }
                    }
                }
            }
            ast::Expr::Cmd(cmd) => self.interpret_cmd(cmd),
            ast::Expr::Assign(_assigns) => {
                // Bare assignments (no command) — no execution needed
                ShellOutput {
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    exit_code: 0,
                }
            }
            ast::Expr::Subshell(sub) => self.interpret_script(&sub.script),
            ast::Expr::If(if_clause) => self.interpret_if(if_clause),
            ast::Expr::CondExpr(_cond) => {
                // CondExpr is a test expression like [ -f file ], not directly executable
                ShellOutput {
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    exit_code: 0,
                }
            }
            ast::Expr::Async(inner) => {
                // Async: run in background (for now, execute synchronously)
                self.interpret_expr(inner)
            }
        }
    }

    /// Interpret an if clause.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_if]
    fn interpret_if<'bump>(&self, if_clause: &ast::If<'bump>) -> ShellOutput {
        // cond is a SmolList<Stmt> — execute all stmts, check last exit_code
        let mut cond_result = ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
        };
        for i in 0..if_clause.cond.len() {
            cond_result = self.interpret_stmt(&if_clause.cond[i]);
        }

        if cond_result.exit_code == 0 {
            // then branch
            let mut then_result = ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            };
            for i in 0..if_clause.then.len() {
                then_result = self.interpret_stmt(&if_clause.then[i]);
            }
            then_result
        } else {
            // else/elif branches (from else_parts)
            let len = if_clause.else_parts.len();
            if len == 0 {
                return cond_result;
            }
            // Even indices = elif conditions, odd indices = elif bodies
            // Last odd = else body
            let mut i = 0;
            while i + 1 < len {
                // Check elif condition
                let mut elif_cond = ShellOutput {
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    exit_code: 0,
                };
                for j in 0..if_clause.else_parts[i].len() {
                    elif_cond = self.interpret_stmt(&if_clause.else_parts[i][j]);
                }
                if elif_cond.exit_code == 0 {
                    // Execute elif body
                    let mut elif_body = ShellOutput {
                        stdout: Vec::new(),
                        stderr: Vec::new(),
                        exit_code: 0,
                    };
                    for j in 0..if_clause.else_parts[i + 1].len() {
                        elif_body = self.interpret_stmt(&if_clause.else_parts[i + 1][j]);
                    }
                    return elif_body;
                }
                i += 2;
            }
            // If there's a trailing else (odd number of parts)
            if len % 2 == 1 {
                let mut else_body = ShellOutput {
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    exit_code: 0,
                };
                for j in 0..if_clause.else_parts[len - 1].len() {
                    else_body = self.interpret_stmt(&if_clause.else_parts[len - 1][j]);
                }
                return else_body;
            }
            cond_result
        }
    }

    /// Interpret a pipeline: chain commands with stdout → stdin piping.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_pipeline]
    fn interpret_pipeline<'bump>(&self, pipeline: &ast::Pipeline<'bump>) -> ShellOutput {
        let items = pipeline.items;
        if items.is_empty() {
            return ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            };
        }

        // For a single-item pipeline, just execute it directly
        if items.len() == 1 {
            return self.interpret_pipeline_item(&items[0]);
        }

        // Multi-item pipeline: chain stdout→stdin between items.
        let mut prev_stdout: Option<Vec<u8>> = None;

        for (i, item) in items.iter().enumerate() {
            let is_last = i == items.len() - 1;
            let result = self.interpret_pipeline_item_with_stdin(item, prev_stdout.as_deref());

            if is_last {
                return result;
            } else {
                prev_stdout = Some(result.stdout);
            }
        }

        // Unreachable: pipeline always has at least one item, so the loop
        // always returns from within. But Rust needs a fallback.
        ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
        }
    }

    /// Interpret a pipeline item.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_pipeline_item]
    fn interpret_pipeline_item<'bump>(&self, item: &ast::PipelineItem<'bump>) -> ShellOutput {
        match item {
            ast::PipelineItem::Cmd(cmd) => self.interpret_cmd(cmd),
            ast::PipelineItem::Assigns(_assigns) => ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            },
            ast::PipelineItem::Subshell(sub) => self.interpret_script(&sub.script),
            ast::PipelineItem::If(if_clause) => self.interpret_if(if_clause),
            ast::PipelineItem::CondExpr(_) => ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            },
        }
    }

    /// Interpret a single command: extract args from AST Cmd, execute via bun_spawn::run.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_cmd]
    fn interpret_cmd<'bump>(&self, cmd: &ast::Cmd<'bump>) -> ShellOutput {
        let cmd_str = self.reconstruct_cmd_string(cmd);
        self.exec_via_sh(&cmd_str, None)
    }

    /// Reconstruct a command string from AST Cmd for /bin/sh execution.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.reconstruct_cmd_string]
    fn reconstruct_cmd_string<'bump>(&self, cmd: &ast::Cmd<'bump>) -> String {
        let mut parts = Vec::new();

        // Add env assignments
        for assign in cmd.assigns.iter() {
            let label = ::std::str::from_utf8(assign.label).unwrap_or("?");
            let value_str = self.atom_to_string(&assign.value);
            parts.push(format!("{}='{}'", label, value_str.replace('\'', "'\\''")));
        }

        // Add command name and arguments. Literal words are re-quoted for
        // /bin/sh: the lexer strips quote SYNTAX into bare Text atoms, so an
        // unquoted reconstruction re-exposes embedded whitespace/metachars
        // ('|', ';', quotes…) as shell operators — `printf '%s|' x` became
        // `printf %s| x` (a pipe!), and `echo "a 'b' c"` lost its inner
        // quotes to sh's second parse. Atoms carrying expansion semantics
        // ($VAR, *, ~, $(…)) pass through raw so sh still expands them.
        for arg in cmd.name_and_args.iter() {
            let rendered = self.atom_to_string(arg);
            if atom_is_pure_literal(arg) {
                parts.push(shell_quote_word(&rendered));
            } else {
                parts.push(rendered);
            }
        }

        // Handle redirect
        if let Some(ref redirect) = cmd.redirect_file {
            match redirect {
                ast::Redirect::Atom(atom) => {
                    let rendered = self.atom_to_string(atom);
                    let target = if atom_is_pure_literal(atom) {
                        shell_quote_word(&rendered)
                    } else {
                        rendered
                    };
                    if cmd.redirect.append() {
                        parts.push(format!(">> {}", target));
                    } else if cmd.redirect.stderr() {
                        parts.push(format!("2> {}", target));
                    } else {
                        parts.push(format!("> {}", target));
                    }
                }
                ast::Redirect::JsBuf(_) => {
                    // JS buffer redirect — not applicable in Rust-only context
                }
            }
        }

        parts.join(" ")
    }

    /// Convert an AST Atom to a String.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.atom_to_string]
    fn atom_to_string<'bump>(&self, atom: &ast::Atom<'bump>) -> String {
        match atom {
            ast::Atom::Simple(simple) => self.simple_atom_to_string(simple),
            ast::Atom::Compound(compound) => {
                let mut parts = Vec::new();
                for simple in compound.atoms.iter() {
                    parts.push(self.simple_atom_to_string(simple));
                }
                parts.join("")
            }
        }
    }

    /// Convert a SimpleAtom to String.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.simple_atom_to_string]
    fn simple_atom_to_string<'bump>(&self, atom: &ast::SimpleAtom<'bump>) -> String {
        match atom {
            ast::SimpleAtom::Var(name) => {
                let name_str = ::std::str::from_utf8(name).unwrap_or("");
                format!("${}", name_str)
            }
            ast::SimpleAtom::VarArgv(idx) => format!("${}", idx),
            ast::SimpleAtom::Text(s) => ::std::str::from_utf8(s).unwrap_or("").to_string(),
            ast::SimpleAtom::QuotedEmpty => String::new(),
            ast::SimpleAtom::Asterisk => "*".to_string(),
            ast::SimpleAtom::DoubleAsterisk => "**".to_string(),
            ast::SimpleAtom::BraceBegin => "{".to_string(),
            ast::SimpleAtom::BraceEnd => "}".to_string(),
            ast::SimpleAtom::Comma => ",".to_string(),
            ast::SimpleAtom::Tilde => "~".to_string(),
            ast::SimpleAtom::CmdSubst(subst) => {
                let inner = self.interpret_script(&subst.script);
                String::from_utf8_lossy(&inner.stdout).into_owned()
            }
        }
    }

    /// Execute a command via /bin/sh -c, optionally piping stdin data.
    /// Uses bun_spawn::run for subprocess management (reuses Bun's spawn infrastructure).
    /// Falls back to std::process::Command when cwd override or stdin piping is needed.
    ///
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.exec_via_sh]
    fn exec_via_sh(&self, cmd_str: &str, stdin_data: Option<&[u8]>) -> ShellOutput {
        if cmd_str.trim().is_empty() {
            return ShellOutput {
                stdout: Vec::new(),
                stderr: b"Bun.Shell: empty command".to_vec(),
                exit_code: 1,
            };
        }

        // If there's stdin data or cwd override, fall back to std::process
        // since bun_spawn::run doesn't support stdin piping or cwd override.
        if stdin_data.is_some() || self.cwd_override.is_some() {
            return self.exec_via_sh_with_stdin(cmd_str, stdin_data);
        }

        // Build env map from overrides
        let env_map = self.build_env_map();

        // Build argv for bun_spawn::run: ["/bin/sh", "-c", <cmd>]
        let sh = b"/bin/sh";
        let dash_c = b"-c";
        let argv_slices: &[&[u8]] = &[sh, dash_c, cmd_str.as_bytes()];

        let opts = RunOptions {
            argv: argv_slices,
            env_map: &env_map,
        };

        match run(opts) {
            Ok(result) => {
                let exit_code = match result.term {
                    Term::Exited(code) => code as i32,
                    Term::Signal(sig) => -(sig as i32),
                    Term::Stopped(sig) => -(sig as i32),
                    Term::Unknown(code) => code as i32,
                };
                ShellOutput {
                    stdout: result.stdout,
                    stderr: result.stderr,
                    exit_code,
                }
            }
            Err(e) => ShellOutput {
                stdout: Vec::new(),
                stderr: format!("Bun.Shell: spawn failed: {:?}", e).into_bytes(),
                exit_code: -1,
            },
        }
    }

    /// Execute with stdin piping (for pipeline intermediate stages).
    /// Falls back to std::process::Command since bun_spawn::run doesn't
    /// support stdin piping directly.
    ///
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.exec_via_sh_with_stdin]
    fn exec_via_sh_with_stdin(&self, cmd_str: &str, stdin_data: Option<&[u8]>) -> ShellOutput {
        let mut command = ::std::process::Command::new("/bin/sh");
        command.arg("-c").arg(cmd_str);

        // CWD override
        if let Some(cwd) = self.cwd_override {
            command.current_dir(cwd);
        }

        // Environment overrides
        if let Some(overrides) = self.env_override {
            for (k, v) in overrides {
                command.env(k, v);
            }
        }

        // Stdin: pipe if we have input data
        if stdin_data.is_some() {
            command.stdin(::std::process::Stdio::piped());
        } else {
            command.stdin(::std::process::Stdio::null());
        }

        command.stdout(::std::process::Stdio::piped());
        command.stderr(::std::process::Stdio::piped());

        match command.spawn() {
            Ok(mut child) => {
                // Write stdin data if present
                if let Some(data) = stdin_data {
                    if let Some(mut stdin_pipe) = child.stdin.take() {
                        let _ = ::std::io::Write::write_all(&mut stdin_pipe, data);
                        drop(stdin_pipe);
                    }
                }

                match child.wait_with_output() {
                    Ok(output) => {
                        let exit_code = output.status.code().unwrap_or(-1);
                        ShellOutput {
                            stdout: output.stdout,
                            stderr: output.stderr,
                            exit_code,
                        }
                    }
                    Err(e) => ShellOutput {
                        stdout: Vec::new(),
                        stderr: format!("Bun.Shell: wait failed: {}", e).into_bytes(),
                        exit_code: -1,
                    },
                }
            }
            Err(e) => ShellOutput {
                stdout: Vec::new(),
                stderr: format!("Bun.Shell: spawn failed: {}", e).into_bytes(),
                exit_code: -1,
            },
        }
    }

    /// Interpret a pipeline item with optional stdin data from the previous stage.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.interpret_pipeline_item_with_stdin]
    fn interpret_pipeline_item_with_stdin<'bump>(
        &self,
        item: &ast::PipelineItem<'bump>,
        stdin_data: Option<&[u8]>,
    ) -> ShellOutput {
        match item {
            ast::PipelineItem::Cmd(cmd) => {
                let cmd_str = self.reconstruct_cmd_string(cmd);
                self.exec_via_sh_with_stdin(&cmd_str, stdin_data)
            }
            ast::PipelineItem::Assigns(_) => ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            },
            ast::PipelineItem::Subshell(sub) => self.interpret_script(&sub.script),
            ast::PipelineItem::If(if_clause) => self.interpret_if(if_clause),
            ast::PipelineItem::CondExpr(_) => ShellOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit_code: 0,
            },
        }
    }

    /// Build a bun_sys::EnvMap from the shell instance's env overrides.
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellInterpreter.build_env_map]
    fn build_env_map(&self) -> bun_sys::EnvMap {
        let mut map = bun_sys::EnvMap::new();

        // Inherit current process environment
        for (key, value) in ::std::env::vars() {
            map.insert(key, value);
        }

        // Apply overrides
        if let Some(overrides) = self.env_override {
            for (k, v) in overrides {
                map.insert(k.clone(), v.clone());
            }
        }

        map
    }
}

// ──────────────────── sh reconstruction quoting ────────────────────

/// Whether an Atom is purely literal (Text/QuotedEmpty only) — safe to
/// single-quote wholesale when reconstructing the command for /bin/sh.
/// Atoms carrying expansion semantics ($VAR, *, ~, $(…), braces) must stay
/// raw so the re-executing shell still expands them.
fn atom_is_pure_literal(atom: &ast::Atom) -> bool {
    let simple_is_literal = |s: &ast::SimpleAtom| {
        matches!(s, ast::SimpleAtom::Text(_) | ast::SimpleAtom::QuotedEmpty)
    };
    match atom {
        ast::Atom::Simple(s) => simple_is_literal(s),
        ast::Atom::Compound(c) => c.atoms.iter().all(simple_is_literal),
    }
}

/// Shell-quote a literal word for /bin/sh re-execution: pass through the
/// historically-safe set unquoted, otherwise wrap in single quotes with the
/// `'\''` escape. Mirrors the env-assign quoting above.
fn shell_quote_word(word: &str) -> String {
    let safe = word.bytes().all(|b| {
        matches!(b,
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9'
            | b'_' | b'-' | b'.' | b'/' | b'@' | b'%' | b'+' | b'=' | b':' | b',')
    });
    if safe {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', "'\\''"))
    }
}

// ──────────────────── ShellOutput result ────────────────────

/// Result of executing a shell command. Returned to JS as ShellOutput object.
/// Uses Vec<u8> internally (zero-copy from bun_spawn::RunResult), converted
/// to JS string on demand.
///
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput]
struct ShellOutput {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    exit_code: i32,
}

impl ShellOutput {
    /// Whether the command succeeded (exit_code == 0).
    fn success(&self) -> bool {
        self.exit_code == 0
    }

    /// Build the JS ShellOutput VALUE object on the given cx (no then —
    /// this is what promises resolve with; see to_js_promise).
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput]
    unsafe fn to_js_object(&self, cx: *mut JSContext) -> *mut JSObject {
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;

        rooted!(&in(cx_ref) let obj = w2::JS_NewPlainObject(cx_ref));
        if obj.get().is_null() {
            return ptr::null_mut();
        }

        self.stamp_result_face(cx_ref, obj.handle());

        obj.get()
    }

    /// Build the awaitable result face: a NATIVE Promise already settled —
    /// resolved with the value object on exit 0, rejected with a ShellError
    /// (carrying stdout/stderr/exitCode) on non-zero exit. The sync result
    /// props (stdout/stderr/exitCode/success) and methods (text/json/lines/
    /// bytes) are stamped directly on the promise object so direct sync
    /// access keeps working alongside then/catch/finally/await.
    ///
    /// Why a native promise and not a custom thenable: a thenable that
    /// resolves with ITSELF (the value would have to be this same object)
    /// sends the engine's assimilation into an infinite job chain — every
    /// PromiseResolveThenableJob run mints fresh resolving closures and the
    /// cycle is never detected (Bun.$ await crash, stack exhaustion). With a
    /// real promise the settlement value is a distinct value object; the
    /// engine never re-assimilates it.
    ///
    /// @trace REQ-BAO-API-018 [api:Bun.Shell/$ Promise face]
    unsafe fn to_js_promise(&self, cx: *mut JSContext) -> *mut JSObject {
        let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        let cx_ref = &mut wrapped_cx;

        rooted!(&in(cx_ref) let promise = JS::NewPromiseObject(cx, HandleObject::null()));
        if promise.get().is_null() {
            return self.to_js_object(cx);
        }

        // Settle the promise first (value object / ShellError).
        rooted!(&in(cx_ref) let settle_val = if self.success() {
            ObjectValue(self.to_js_object(cx))
        } else {
            let err = shell_error_object(cx, self.exit_code, &String::from_utf8_lossy(&self.stdout), &String::from_utf8_lossy(&self.stderr));
            if err.is_null() {
                UndefinedValue()
            } else {
                ObjectValue(err)
            }
        });
        if self.success() {
            let _ = JS::ResolvePromise(cx, promise.handle().into(), settle_val.handle().into());
        } else {
            let _ = JS::RejectPromise(cx, promise.handle().into(), settle_val.handle().into());
        }

        // Stamp the sync result face onto the promise itself (direct
        // `result.stdout` / `result.text()` without awaiting).
        self.stamp_result_face(cx_ref, promise.handle());

        promise.get()
    }

    /// Define the sync result properties + methods on `obj` (used both for
    /// the value object in `to_js_object` and the promise in
    /// `to_js_promise`; method callbacks read the props off `this`).
    #[allow(unsafe_op_in_unsafe_fn)]
    unsafe fn stamp_result_face(
        &self,
        cx_ref: &mut mozjs::context::JSContext,
        obj: mozjs::rust::Handle<*mut JSObject>,
    ) {
        let cx = cx_ref.raw_cx();

        // stdout (lossy UTF-8 → JS string)
        let stdout_str = String::from_utf8_lossy(&self.stdout);
        let stdout_js = JS_NewStringCopyN(
            cx,
            stdout_str.as_ptr() as *const ::std::os::raw::c_char,
            stdout_str.len(),
        );
        if !stdout_js.is_null() {
            rooted!(&in(cx_ref) let sv = StringValue(&*stdout_js));
            JS_DefineProperty(
                cx,
                obj.into(),
                c"stdout".as_ptr(),
                sv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // stderr (lossy UTF-8 → JS string)
        let stderr_str = String::from_utf8_lossy(&self.stderr);
        let stderr_js = JS_NewStringCopyN(
            cx,
            stderr_str.as_ptr() as *const ::std::os::raw::c_char,
            stderr_str.len(),
        );
        if !stderr_js.is_null() {
            rooted!(&in(cx_ref) let sv = StringValue(&*stderr_js));
            JS_DefineProperty(
                cx,
                obj.into(),
                c"stderr".as_ptr(),
                sv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // exitCode
        rooted!(&in(cx_ref) let ecv = Int32Value(self.exit_code));
        JS_DefineProperty(
            cx,
            obj.into(),
            c"exitCode".as_ptr(),
            ecv.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        // success — boolean property (exitCode === 0)
        rooted!(&in(cx_ref) let sv = BooleanValue(self.success()));
        JS_DefineProperty(
            cx,
            obj.into(),
            c"success".as_ptr(),
            sv.handle().into(),
            JSPROP_ENUMERATE as u32,
        );

        w2::JS_DefineFunction(
            cx_ref,
            obj,
            c"text".as_ptr(),
            Some(shell_output_text),
            0,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            obj,
            c"json".as_ptr(),
            Some(shell_output_json),
            0,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            obj,
            c"lines".as_ptr(),
            Some(shell_output_lines),
            0,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx_ref,
            obj,
            c"bytes".as_ptr(),
            Some(shell_output_bytes),
            0,
            JSPROP_ENUMERATE as u32,
        );
    }
}

// ──────────────────── ShellOutput Promise settlement ────────────────────

/// ZBox-backed NUL-terminated name helper (JS_DefineProperty wants C strings).
struct ZBoxLikeName {
    inner: bun_core::ZBox,
}

impl ZBoxLikeName {
    fn from(s: &str) -> Self {
        ZBoxLikeName {
            inner: bun_core::ZBox::from_bytes(s.as_bytes()),
        }
    }
    fn as_ptr(&self) -> *const ::std::os::raw::c_char {
        self.inner.as_ptr() as *const _
    }
}

/// Build the ShellError rejection object: `name`/`message` Error-like face
/// plus the full result payload (exitCode/stdout/stderr) so failure handlers
/// and uncaught-await reporting can inspect the command outcome.
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn shell_error_object(cx: *mut JSContext, exit_code: i32, stdout: &str, stderr: &str) -> *mut JSObject {
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let err = w2::JS_NewPlainObject(cx_ref));
    if err.get().is_null() {
        return ptr::null_mut();
    }
    let message = format!("Failed with exit code: {}", exit_code);
    let defs: [(&str, String); 4] = [
        ("name", "ShellError".to_string()),
        ("message", message),
        ("stdout", stdout.to_string()),
        ("stderr", stderr.to_string()),
    ];
    for (key, value) in defs {
        let c_v = bun_core::ZBox::from_bytes(value.as_bytes());
        let js_str = JS_NewStringCopyZ(cx, c_v.as_ptr());
        if !js_str.is_null() {
            rooted!(&in(cx_ref) let sv = StringValue(&*js_str));
            let c_key = ZBoxLikeName::from(key);
            JS_DefineProperty(
                cx,
                err.handle().into(),
                c_key.as_ptr(),
                sv.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }
    rooted!(&in(cx_ref) let fv = BooleanValue(false));
    JS_DefineProperty(
        cx,
        err.handle().into(),
        c"success".as_ptr(),
        fv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    // exitCode as a NUMBER (matches the ShellOutput face; strict equality
    // `e.exitCode === 7` must hold).
    rooted!(&in(cx_ref) let ecv = Int32Value(exit_code));
    JS_DefineProperty(
        cx,
        err.handle().into(),
        c"exitCode".as_ptr(),
        ecv.handle().into(),
        JSPROP_ENUMERATE as u32,
    );
    err.get()
}


// ──────────────────── ShellOutput method callbacks ────────────────────

/// ShellOutput.text() — returns stdout as string.
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput.text]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_output_text(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, 0);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = this.to_object());
    let mut stdout_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"stdout".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut stdout_val,
        },
    );
    args.rval().set(stdout_val);
    true
}

/// ShellOutput.json() — parses stdout as JSON.
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput.json]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_output_json(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, 0);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = this.to_object());

    let mut stdout_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"stdout".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut stdout_val,
        },
    );

    if stdout_val.is_string() {
        let stdout_str = crate::js_to_rust_string(cx, stdout_val);
        let js_str = JS_NewStringCopyN(
            cx,
            stdout_str.as_ptr() as *const ::std::os::raw::c_char,
            stdout_str.len(),
        );
        if !js_str.is_null() {
            rooted!(&in(cx_ref) let str_root = js_str);
            let mut parsed = UndefinedValue();
            let parsed_h = MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut parsed,
            };
            let _ = mozjs_sys::jsapi::JS_ParseJSON1(cx, str_root.handle().into(), parsed_h);
            args.rval().set(parsed);
            return true;
        }
    }
    args.rval().set(UndefinedValue());
    true
}

/// ShellOutput.lines() — splits stdout by newline into JS array.
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput.lines]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_output_lines(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, 0);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = this.to_object());

    let mut stdout_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"stdout".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut stdout_val,
        },
    );

    let stdout_str = if stdout_val.is_string() {
        crate::js_to_rust_string(cx, stdout_val)
    } else {
        String::new()
    };

    let lines: Vec<&str> = stdout_str.split('\n').collect();
    rooted!(&in(cx_ref) let arr = w2::NewArrayObject1(cx_ref, lines.len()));
    if arr.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    for (i, line) in lines.iter().enumerate() {
        let js_str = JS_NewStringCopyN(
            cx,
            line.as_ptr() as *const ::std::os::raw::c_char,
            line.len(),
        );
        if !js_str.is_null() {
            rooted!(&in(cx_ref) let lv = StringValue(&*js_str));
            w2::JS_SetElement(cx_ref, arr.handle().into(), i as u32, lv.handle().into());
        }
    }
    args.rval().set(ObjectValue(arr.get()));
    true
}

/// ShellOutput.bytes() — returns stdout as Uint8Array.
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ ShellOutput.bytes]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_output_bytes(cx: *mut JSContext, _argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, 0);
    let this = args.thisv();
    if !this.is_object() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;
    rooted!(&in(cx_ref) let obj = this.to_object());

    let mut stdout_val = UndefinedValue();
    JS_GetProperty(
        cx,
        obj.handle().into(),
        c"stdout".as_ptr(),
        MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut stdout_val,
        },
    );

    // Get the raw bytes — convert the JS string back to bytes
    let stdout_str = if stdout_val.is_string() {
        crate::js_to_rust_string(cx, stdout_val)
    } else {
        String::new()
    };

    let bytes = stdout_str.into_bytes();
    let len = bytes.len();

    // Create a Uint8Array via JS_NewUint8Array
    let arr_obj = JS_NewUint8Array(cx, len);
    if !arr_obj.is_null() {
        // Copy bytes into the array
        let data_ptr = JS_GetUint8ArrayData(arr_obj, ptr::null_mut(), ptr::null());
        if !data_ptr.is_null() {
            ptr::copy_nonoverlapping(bytes.as_ptr(), data_ptr, len);
        }
        rooted!(&in(cx_ref) let arr_rooted = arr_obj);
        args.rval().set(ObjectValue(arr_rooted.get()));
    } else {
        args.rval().set(UndefinedValue());
    }
    true
}

// ──────────────────── Shell constructor ────────────────────

/// new Bun.Shell() constructor callback.
/// @trace REQ-BAO-API-018 [api:Bun.Shell constructor]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_constructor(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    let shell_id = SHELL_ID_COUNTER.fetch_add(1, Ordering::Relaxed);

    rooted!(&in(cx_ref) let shell_obj = w2::JS_NewPlainObject(cx_ref));
    if shell_obj.get().is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Store shell_id on the object
    rooted!(&in(cx_ref) let idv = DoubleValue(shell_id as f64));
    JS_DefineProperty(
        cx,
        shell_obj.handle().into(),
        c"_shellId".as_ptr(),
        idv.handle().into(),
        0,
    );

    // Install shell.run() method
    w2::JS_DefineFunction(
        cx_ref,
        shell_obj.handle(),
        c"run".as_ptr(),
        Some(shell_run),
        1,
        JSPROP_ENUMERATE as u32,
    );

    // Install shell.setenv() method
    w2::JS_DefineFunction(
        cx_ref,
        shell_obj.handle(),
        c"setenv".as_ptr(),
        Some(shell_setenv),
        2,
        JSPROP_ENUMERATE as u32,
    );

    // Install shell.cd() method
    w2::JS_DefineFunction(
        cx_ref,
        shell_obj.handle(),
        c"cd".as_ptr(),
        Some(shell_cd),
        1,
        JSPROP_ENUMERATE as u32,
    );

    // Initialize state
    SHELL_INSTANCES.with(|instances| {
        instances.borrow_mut().insert(
            shell_id,
            ShellState {
                env: None,
                cwd: None,
            },
        );
    });

    args.rval().set(ObjectValue(shell_obj.get()));
    true
}

// ──────────────────── Shell.run() ────────────────────

/// shell.run(command) → ShellOutput (synchronous).
/// shell.run(command, callback) → void (async, callback receives ShellOutput).
/// @trace REQ-BAO-API-018 [api:Bun.Shell.run]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_run(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"Shell.run() requires a command string".as_ptr());
        return false;
    }

    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    // Get command string
    let cmd_val = *args.get(0).ptr;
    let command = if cmd_val.is_string() {
        crate::js_to_rust_string(cx, cmd_val)
    } else {
        JS_ReportErrorUTF8(cx, c"Shell.run() first argument must be a string".as_ptr());
        return false;
    };

    // Get shell_id from this object
    let this = args.thisv();
    let shell_id = if this.is_object() {
        rooted!(&in(cx_ref) let obj = this.to_object());
        let mut id_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_shellId".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut id_val,
            },
        );
        if id_val.is_double() {
            id_val.to_double() as u64
        } else {
            0
        }
    } else {
        0
    };

    // Retrieve env/cwd overrides from shell state
    let (env_override, cwd_override) = SHELL_INSTANCES.with(|instances| {
        instances
            .borrow()
            .get(&shell_id)
            .map(|s| (s.env.clone(), s.cwd.clone()))
            .unwrap_or((None, None))
    });

    // Check if callback provided (async mode)
    let has_callback = argc >= 2 && (*args.get(1).ptr).is_object();
    let callback_obj = if has_callback {
        let cb_val = *args.get(1).ptr;
        let cb_obj = cb_val.to_object();
        if JS_ObjectIsFunction(cb_obj) {
            Some(cb_obj)
        } else {
            None
        }
    } else {
        None
    };

    // Execute using ShellInterpreter (reuses bun_shell_parser + bun_spawn)
    let interpreter = ShellInterpreter::new(env_override.as_ref(), cwd_override.as_deref());
    let output = interpreter.parse_and_run(&command);

    let js_output = output.to_js_object(cx);
    if js_output.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }

    if let Some(cb) = callback_obj {
        // Async: call callback(ShellOutput), return undefined
        rooted!(&in(cx_ref) let cb_h = ObjectValue(cb));
        rooted!(&in(cx_ref) let global = CurrentGlobalOrNull(cx));
        if !global.get().is_null() {
            rooted!(&in(cx_ref) let out_val = ObjectValue(js_output));
            let call_args = HandleValueArray {
                length_: 1,
                elements_: &*out_val.handle(),
            };
            let mut rval = UndefinedValue();
            let rval_h = MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut rval,
            };
            let _ = JS_CallFunctionValue(
                cx,
                global.handle().into(),
                cb_h.handle().into(),
                &call_args,
                rval_h,
            );
        }
        args.rval().set(UndefinedValue());
    } else {
        // Sync: return ShellOutput
        args.rval().set(ObjectValue(js_output));
    }
    true
}

// ──────────────────── Shell.setenv() / Shell.cd() ────────────────────

/// shell.setenv(key, value) — set environment variable override for this shell.
/// @trace REQ-BAO-API-018 [api:Bun.Shell.setenv]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_setenv(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc < 2 {
        JS_ReportErrorUTF8(
            cx,
            c"Shell.setenv() requires key and value arguments".as_ptr(),
        );
        return false;
    }

    let key = crate::js_to_rust_string(cx, *args.get(0).ptr);
    let value = crate::js_to_rust_string(cx, *args.get(1).ptr);

    let this = args.thisv();
    if this.is_object() {
        rooted!(&in(cx_ref) let obj = this.to_object());
        let mut id_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_shellId".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut id_val,
            },
        );
        if id_val.is_double() {
            let shell_id = id_val.to_double() as u64;
            SHELL_INSTANCES.with(|instances| {
                if let Some(state) = instances.borrow_mut().get_mut(&shell_id) {
                    state
                        .env
                        .get_or_insert_with(HashMap::new)
                        .insert(key, value);
                }
            });
        }
    }
    args.rval().set(UndefinedValue());
    true
}

/// shell.cd(path) — set working directory override for this shell.
/// @trace REQ-BAO-API-018 [api:Bun.Shell.cd]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn shell_cd(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc < 1 {
        JS_ReportErrorUTF8(cx, c"Shell.cd() requires a path argument".as_ptr());
        return false;
    }

    let path = crate::js_to_rust_string(cx, *args.get(0).ptr);

    let this = args.thisv();
    if this.is_object() {
        rooted!(&in(cx_ref) let obj = this.to_object());
        let mut id_val = UndefinedValue();
        JS_GetProperty(
            cx,
            obj.handle().into(),
            c"_shellId".as_ptr(),
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut id_val,
            },
        );
        if id_val.is_double() {
            let shell_id = id_val.to_double() as u64;
            SHELL_INSTANCES.with(|instances| {
                if let Some(state) = instances.borrow_mut().get_mut(&shell_id) {
                    state.cwd = Some(path);
                }
            });
        }
    }
    args.rval().set(UndefinedValue());
    true
}

// ──────────────────── Bun.$ tagged template ────────────────────

/// Bun.$(strings, ...expressions) → ShellOutput.
/// Tagged template literal implementation.
/// Uses ShellInterpreter (bun_shell_parser + bun_spawn) for execution.
///
/// @trace REQ-BAO-API-018 [api:Bun.$ tagged template]
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn bun_dollar(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    let cx_ref = &mut wrapped_cx;

    if argc == 0 {
        JS_ReportErrorUTF8(
            cx,
            c"Bun.$ requires at least a template strings array".as_ptr(),
        );
        return false;
    }

    // First argument is the template strings array (from tagged template literal)
    let strings_val = *args.get(0).ptr;
    if !strings_val.is_object() {
        JS_ReportErrorUTF8(
            cx,
            c"Bun.$ first argument must be a template strings array".as_ptr(),
        );
        return false;
    }

    rooted!(&in(cx_ref) let strings_arr = strings_val.to_object());

    // Build the command string by interleaving template strings with expressions
    let mut command = String::new();
    let mut arr_len: u32 = 0;
    if !w2::GetArrayLength(cx_ref, strings_arr.handle().into(), &mut arr_len) || arr_len == 0 {
        args.rval().set(UndefinedValue());
        return true;
    }

    // Direct array call — Bun.$(['echo', 'hello']) — has no interleaved
    // expressions (argc == 1) and multiple elements: each element is a
    // separate shell word, so join with spaces. Elements are JS strings
    // (argv semantics): quote each one so metacharacters ('|', ';', '>',
    // spaces…) stay literal through the lexer's parse — without quoting,
    // `['printf', '%s|', 'a|b;c']` re-exposed '|' as a shell pipe (127).
    // A tagged-template strings array with multiple parts always carries
    // argc > 1 (one arg per hole).
    if argc == 1 && arr_len > 1 {
        let mut words: Vec<String> = Vec::with_capacity(arr_len as usize);
        for i in 0..arr_len {
            let mut elem = UndefinedValue();
            JS_GetElement(
                cx,
                strings_arr.handle().into(),
                i,
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut elem,
                },
            );
            if elem.is_string() {
                words.push(shell_quote_word(&crate::js_to_rust_string(cx, elem)));
            }
        }
        command = words.join(" ");
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run(&command);
        let js_output = output.to_js_promise(cx);
        if js_output.is_null() {
            args.rval().set(UndefinedValue());
            return true;
        }
        args.rval().set(ObjectValue(js_output));
        return true;
    }

    for i in 0..arr_len {
        let mut elem = UndefinedValue();
        JS_GetElement(
            cx,
            strings_arr.handle().into(),
            i,
            MutableHandle::<Value> {
                _phantom_0: ::std::marker::PhantomData,
                ptr: &mut elem,
            },
        );
        if elem.is_string() {
            command.push_str(&crate::js_to_rust_string(cx, elem));
        }
        // Interleave expression values (args 1..)
        if i as usize + 1 < argc as usize {
            let expr_val = *args.get(i + 1).ptr;
            if expr_val.is_string() {
                command.push_str(&crate::js_to_rust_string(cx, expr_val));
            } else if expr_val.is_int32() {
                command.push_str(&expr_val.to_int32().to_string());
            } else if expr_val.is_double() {
                command.push_str(&expr_val.to_double().to_string());
            }
        }
    }

    // Execute using ShellInterpreter (reuses bun_shell_parser + bun_spawn)
    let interpreter = ShellInterpreter::new(None, None);
    let output = interpreter.parse_and_run(&command);
    let js_output = output.to_js_promise(cx);
    if js_output.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    args.rval().set(ObjectValue(js_output));
    true
}

// ──────────────────── Public API ────────────────────

/// Install Bun.Shell and Bun.$ on the global Bun object.
/// Replaces the Phase 1 stub with a full implementation using
/// bun_shell_parser + bun_spawn (SPEC: REQ-BAO-API-018 reuse mapping).
///
/// @trace REQ-BAO-API-018 [api:Bun.Shell/$ installation]
pub unsafe fn install_bun_shell(
    cx: &mut mozjs::context::JSContext,
    bun_obj: mozjs::rust::Handle<*mut JSObject>,
) {
    // Install Bun.Shell constructor
    let shell_ctor = JS_NewFunction(
        cx.raw_cx(),
        Some(shell_constructor),
        0,
        JSFUN_CONSTRUCTOR as u32,
        c"Shell".as_ptr(),
    );
    if !shell_ctor.is_null() {
        let shell_proto = JS_GetFunctionObject(shell_ctor);
        rooted!(&in(cx) let shell_ctor_obj = shell_proto);
        w2::JS_DefineProperty3(
            cx,
            bun_obj,
            c"Shell".as_ptr(),
            shell_ctor_obj.handle(),
            JSPROP_ENUMERATE as u32,
        );
    }

    // Install Bun.$ as tagged template function
    let dollar_fn = JS_NewFunction(cx.raw_cx(), Some(bun_dollar), 0, 0, c"$".as_ptr());
    if !dollar_fn.is_null() {
        let dollar_obj = JS_GetFunctionObject(dollar_fn);
        rooted!(&in(cx) let dollar_fn_obj = dollar_obj);
        w2::JS_DefineProperty3(
            cx,
            bun_obj,
            c"$".as_ptr(),
            dollar_fn_obj.handle(),
            JSPROP_ENUMERATE as u32,
        );
    }
}

// ──────────────────── Unit tests ────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shell_interpreter_echo() {
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run("echo hello");
        assert_eq!(output.exit_code, 0);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.starts_with("hello"));
    }

    #[test]
    fn test_shell_interpreter_empty_command() {
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run("");
        assert_eq!(output.exit_code, 0);
        assert!(output.stdout.is_empty());
    }

    #[test]
    fn test_shell_interpreter_failing_command() {
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run("false");
        assert_ne!(output.exit_code, 0);
    }

    #[test]
    fn test_shell_interpreter_pipeline() {
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run("echo hello | cat");
        assert_eq!(output.exit_code, 0);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.starts_with("hello"));
    }

    #[test]
    fn test_shell_interpreter_env() {
        let mut env = HashMap::new();
        env.insert("BAO_TEST_VAR".to_string(), "test_value_456".to_string());
        let interpreter = ShellInterpreter::new(Some(&env), None);
        let output = interpreter.parse_and_run("echo $BAO_TEST_VAR");
        assert_eq!(output.exit_code, 0);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("test_value_456"));
    }

    #[test]
    fn test_shell_interpreter_cwd() {
        let interpreter = ShellInterpreter::new(None, Some("/tmp"));
        let output = interpreter.parse_and_run("pwd");
        assert_eq!(output.exit_code, 0);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("/tmp"));
    }

    #[test]
    fn test_shell_output_success() {
        let output = ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
        };
        assert!(output.success());

        let output_fail = ShellOutput {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 1,
        };
        assert!(!output_fail.success());
    }

    #[test]
    fn test_shell_interpreter_nonexistent_command() {
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run("nonexistent_command_xyz_123");
        assert_ne!(output.exit_code, 0);
    }

    #[test]
    fn test_shell_interpreter_redirect() {
        let tmp = ::std::env::temp_dir().join("bao_shell_test_redirect.txt");
        let _ = ::std::fs::remove_file(&tmp);
        let cmd = format!("echo hello > {}", tmp.display());
        let interpreter = ShellInterpreter::new(None, None);
        let output = interpreter.parse_and_run(&cmd);
        assert_eq!(output.exit_code, 0);
        let content = ::std::fs::read_to_string(&tmp).unwrap_or_default();
        assert!(content.contains("hello"));
        let _ = ::std::fs::remove_file(&tmp);
    }
}