vce-shell 0.1.1

VCE Shell layer: command language, builtins, execution coordination
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
//! The Bash shell implementation.
//!
//! The Shell layer is split into a shared execution core
//! ([`ShellCore`](crate::core::ShellCore)) and per-shell shells. Bash is
//! one of them: it owns its grammar (via [`brush_parser`]), its builtin
//! table, and its dialect (messages and prompt). Builtins it shares with
//! Zsh delegate to core mechanisms only where the two shells were verified
//! to behave identically (`cd`, `pwd`, `jobs`, `fg`, `bg`, `hash`, `dirs`,
//! `pushd`, `popd`, `unset`, `source`, `clear`); anything with different
//! semantics (`echo`, `export`, `alias`, `type`) is implemented here.
//!
//! Parsing uses the [`brush_parser`] crate — the tokenizer and AST parser
//! from the brush-shell project — so shell grammar (quoting, operators,
//! pipelines, compound commands) is real grammar, not a hand-rolled
//! approximation.
//!
//! Supported compound constructs: `if`/`elif`/`else`, `while`/`until`,
//! brace groups, subshells (isolated session state), `for` iteration,
//! `case` clauses, arithmetic (`$(( ))` and `(( ))`, sharing one evaluator
//! with the expander), function definitions, and `[[ ]]` extended tests.
//! Arrays are not supported yet.

use engine::{Input, Output, Terminal, VirtualPath};
use os::{Credentials, ExitStatus, UnixOs};

use crate::core::{ShellCore, ShellDialect};

/// The Bash shell.
pub struct Bash<'os> {
    /// The shared execution core in the Bash dialect.
    core: ShellCore<'os>,
}

impl<'os> Bash<'os> {
    /// Creates a Bash shell for a session.
    pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
        let mut core = ShellCore::new(os, credentials, bash_dialect())?;
        // Scripts run through this shell, not a separate interpreter.
        core.install_shell_bindings();
        // Startup files define the session's aliases and functions.
        core.source_startup_files();
        Ok(Self { core })
    }
}

/// The behavior of `/bin/sh` and `/bin/bash`: the Bash dialect as a
/// program. Scripts and `sh -c` invocations run through the same
/// implementation as interactive commands.
pub struct BashInterpreter;

impl os::runtime::Command for BashInterpreter {
    fn name(&self) -> &'static str {
        "bash"
    }

    fn execute(
        &self,
        context: &mut os::runtime::CommandContext<'_, '_, '_, '_>,
    ) -> Result<os::runtime::ExitStatus, os::OsError> {
        crate::core::run_interpreter_invocation(
            context.os,
            context.credentials.clone(),
            bash_dialect(),
            context.cwd,
            context.argv,
            &mut *context.stdin,
            &mut *context.stdout,
            &mut *context.stderr,
        )
    }
}

/// The Bash dialect: identity, messages, and the builtin table.
/// The Bash dialect, also used for non-interactive interpreter invocations
/// (`/bin/sh`, `/bin/bash`): the shell grammar this project implements.
pub(crate) fn bash_dialect() -> ShellDialect {
    ShellDialect {
        name: "bash",
        command_not_found: |name| format!("bash: {name}: command not found\n"),
        run_builtin: bash_run_builtin,
        system_rc: "/etc/bashrc",
        user_rc: ".bashrc",
        echo_escapes_default: false,
        export_prefix: "declare -x ",
        alias_prefix: "alias ",
    }
}

/// Whether a name is a Bash builtin.
fn bash_is_builtin(name: &str) -> bool {
    matches!(
        name,
        "cd" | "pwd"
            | "export"
            | "history"
            | "alias"
            | "unalias"
            | "jobs"
            | "fg"
            | "bg"
            | "wait"
            | "hash"
            | "echo"
            | "clear"
            | ":"
            | "dirs"
            | "pushd"
            | "popd"
            | "unset"
            | "source"
            | "."
            | "type"
            | "exit"
    )
}

/// Dispatches a Bash builtin (function → builtin → external).
fn bash_run_builtin(
    core: &mut ShellCore,
    name: &str,
    argv: &[String],
    stdin: &mut dyn Input,
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> Option<ExitStatus> {
    let status = match name {
        // Shared mechanisms, verified identical in Bash and Zsh.
        "cd" => core.cd_to(argv, stdout, stderr),
        "pwd" => core.pwd_of(stdout),
        "jobs" => core.list_jobs(stdout),
        "fg" => core.foreground_job(argv, stdout, stderr),
        "bg" => core.background_job(argv, stdout, stderr),
        "wait" => core.wait_for_jobs(argv, stderr),
        "hash" => core.hash_table(argv, stdout, stderr),
        "dirs" => core.print_dirs(stdout),
        "pushd" => core.push_directory(argv, stdout, stderr),
        "popd" => core.pop_directory(argv, stdout, stderr),
        "unset" => core.unset_names(argv, stderr),
        "source" | "." => core.source_file(argv, stdin, stdout, stderr),
        "clear" => core.clear_screen(stdout),
        ":" => core.null_command(),
        // Bash-owned semantics on shared mechanisms (the dialect carries
        // the phrasing).
        "echo" => core.builtin_echo(argv, stdout),
        "export" => core.builtin_export(argv, stdout, stderr),
        "history" => core.builtin_history(stdout),
        "alias" => core.builtin_alias(argv, stdout, stderr),
        "unalias" => core.builtin_unalias(argv, stderr),
        "type" => bash_type(core, argv, stdout, stderr),
        "exit" => core.request_exit(argv.get(1).map(String::as_str)),
        _ => return None,
    };
    Some(status)
}

/// The Bash `type` builtin: reports how a name would be resolved.
fn bash_type(
    core: &mut ShellCore,
    argv: &[String],
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> ExitStatus {
    let mut exit_status = ExitStatus::SUCCESS;
    for name in argv.iter().skip(1) {
        let resolution = core.resolve_name(name, bash_is_builtin);
        if let Some(alias) = resolution.alias {
            let _ = stdout.write(format!("{name} is aliased to `{alias}'\n").as_bytes());
            continue;
        }
        if resolution.function {
            let _ = stdout.write(format!("{name} is a function\n").as_bytes());
            continue;
        }
        if resolution.builtin {
            let _ = stdout.write(format!("{name} is a shell builtin\n").as_bytes());
            continue;
        }
        if let Some(path) = resolution.paths.into_iter().next() {
            let _ = stdout.write(format!("{name} is {path}\n").as_bytes());
        } else {
            exit_status = ExitStatus::FAILURE;
            let _ = stderr.write(format!("bash: type: {name}: not found\n").as_bytes());
        }
    }
    exit_status
}

impl<'os> crate::Shell for Bash<'os> {
    fn name(&self) -> &'static str {
        "bash"
    }

    fn actor(&self) -> engine::ActorId {
        self.core.credentials().actor()
    }

    fn environment(&self) -> &os::Environment {
        self.core.environment()
    }

    fn engine(&self) -> &engine::Engine {
        self.core.os().engine()
    }

    fn boot_time(&self) -> engine::Timestamp {
        self.core.os().boot_time()
    }

    fn hostname(&self) -> String {
        crate::core::hostname_from_etc(self.core.os())
    }

    fn cwd(&self) -> &VirtualPath {
        self.core.cwd()
    }

    fn prompt(&self, hostname: &str) -> String {
        format!(
            "{}@{}:{}> ",
            self.core.credentials().username(),
            hostname,
            self.core.cwd()
        )
    }

    fn banner(&self) -> Option<String> {
        Some(format!(
            "Last login: {} on ttys000\n",
            crate::core::format_login_line(self.core.os().boot_time())
        ))
    }

    fn set_terminal_size(&mut self, rows: u16, cols: u16) {
        self.core.set_terminal_size(rows, cols);
    }

    fn execute(
        &mut self,
        line: &str,
        stdin: &mut dyn Input,
        stdout: &mut dyn Output,
        stderr: &mut dyn Output,
    ) -> ExitStatus {
        self.core.execute(line, stdin, stdout, stderr)
    }

    fn execute_with_terminal(
        &mut self,
        line: &str,
        stdin: &mut dyn Input,
        stdout: &mut dyn Output,
        stderr: &mut dyn Output,
        terminal: Option<&mut dyn Terminal>,
    ) -> ExitStatus {
        self.core
            .execute_with_terminal(line, stdin, stdout, stderr, terminal)
    }

    fn take_exit_status(&mut self) -> Option<ExitStatus> {
        self.core.take_exit_request()
    }

    fn history(&self) -> &[String] {
        self.core.history()
    }

    fn record_history(&mut self, line: &str) {
        self.core.record_history(line);
    }

    fn needs_continuation(&self, input: &str) -> bool {
        crate::core::needs_continuation(input)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Shell;
    use crate::core::needs_continuation;
    use engine::{BytesInput, BytesOutput, Timestamp};
    use os::HostIdentity;
    use os::linux::Linux;

    fn test_shell() -> Bash<'static> {
        // Leak the Linux to get a 'static reference for test convenience.
        let linux = Box::leak(Box::new(
            Linux::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let credentials = linux
            .unix()
            .users()
            .authenticate("demo", "demo", linux.unix().groups())
            .unwrap();
        Bash::new(linux.unix(), credentials).unwrap()
    }

    /// Runs a line, returning (status, stdout).
    fn run(shell: &mut Bash<'static>, line: &str) -> (ExitStatus, Vec<u8>, Vec<u8>) {
        let mut stdin = BytesInput::new(b"");
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
        (status, stdout.into_bytes(), stderr.into_bytes())
    }

    #[test]
    fn builtin_cd_and_pwd() {
        let mut shell = test_shell();
        assert_eq!(run(&mut shell, "mkdir /tmp/testdir").0, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "cd /tmp/testdir");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(shell.cwd().to_string(), "/tmp/testdir");
        let (_, out, _) = run(&mut shell, "pwd");
        assert_eq!(out, b"/tmp/testdir\n");
    }

    #[test]
    fn external_ls_and_which() {
        let mut shell = test_shell();
        let (status, out, _) = run(&mut shell, "which ls");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"/usr/bin/ls\n");

        let (status, out, _) = run(&mut shell, "ls /");
        assert_eq!(status, ExitStatus::SUCCESS);
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("bin"));
        assert!(output.contains("etc"));
    }

    #[test]
    fn redirection_and_cat() {
        let mut shell = test_shell();
        let (status, out, _) = run(&mut shell, "echo hello > /tmp/hello.txt");
        assert_eq!(status, ExitStatus::SUCCESS);
        // Redirection must not leak to the caller's stdout.
        assert_eq!(out, b"");
        let (status, out, _) = run(&mut shell, "cat /tmp/hello.txt");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"hello\n");
    }

    #[test]
    fn single_quotes_do_not_expand() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo '$HOME'");
        assert_eq!(out, b"$HOME\n");
    }

    #[test]
    fn double_quotes_expand_but_do_not_split() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo \"$HOME/x y\"");
        assert_eq!(out, b"/home/demo/x y\n");
    }

    #[test]
    fn quoted_operators_are_not_operators() {
        let mut shell = test_shell();
        let (status, out, _) = run(&mut shell, "echo \"a & b; c\"");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"a & b; c\n");
    }

    #[test]
    fn and_or_sequencing_preserves_quoting() {
        let mut shell = test_shell();
        let (status, out, _) = run(
            &mut shell,
            "echo 'first word' > /tmp/q.txt && cat /tmp/q.txt",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"first word\n");
    }

    #[test]
    fn background_ampersand_is_recorded() {
        let mut shell = test_shell();
        // Both commands run; the backgrounded one is recorded as a job.
        let (_, out, _) = run(&mut shell, "echo backgrounded & echo foreground");
        assert_eq!(out, b"backgrounded\nforeground\n");
        let (_, jobs, _) = run(&mut shell, "jobs");
        assert!(String::from_utf8_lossy(&jobs).contains("echo backgrounded"));
    }

    #[test]
    fn arithmetic_expansion_evaluates() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo $((1 + 1))");
        assert_eq!(out, b"2\n");
        // Precedence and grouping.
        let (_, out, _) = run(&mut shell, "echo $((2 + 3 * 4))");
        assert_eq!(out, b"14\n");
        let (_, out, _) = run(&mut shell, "echo $(((2 + 3) * 4))");
        assert_eq!(out, b"20\n");
        // Variables are references; assignment operators mutate them.
        run(&mut shell, "count=5");
        let (_, out, _) = run(&mut shell, "echo $((count * 2))");
        assert_eq!(out, b"10\n");
        run(&mut shell, "((count += 3))");
        let (_, out, _) = run(&mut shell, "echo $count");
        assert_eq!(out, b"8\n");
        // Substitution inside the expression.
        let (_, out, _) = run(&mut shell, "echo $(($(grep -c . /dev/null) + 7))");
        assert_eq!(out, b"7\n");
    }

    #[test]
    fn arithmetic_command_reports_nonzero_as_success() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "((1 + 1))");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "((1 - 1))");
        assert_eq!(status.code(), 1);
    }

    #[test]
    fn case_clause_matches_patterns_in_order() {
        let mut shell = test_shell();
        let (_, out, _) = run(
            &mut shell,
            "case /etc/passwd in /etc/*) echo system ;; *) echo other ;; esac",
        );
        assert_eq!(out, b"system\n");
        // No match at all succeeds.
        let (status, out, _) = run(&mut shell, "case zzz in aaa) echo a ;; esac");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"");
        // First matching branch wins.
        let (_, out, _) = run(
            &mut shell,
            "case abc in a*) echo one ;; *) echo two ;; esac",
        );
        assert_eq!(out, b"one\n");
    }

    #[test]
    fn subshell_isolates_state() {
        let mut shell = test_shell();
        run(&mut shell, "cd /tmp && mkdir -p /tmp/subshell-test");
        // Variable changes, cd, and exit do not escape the subshell.
        let (status, out, _) = run(
            &mut shell,
            "(value=inner; cd /tmp/subshell-test); echo $value; pwd",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"\n/tmp\n");
        // The subshell's own output and status propagate.
        let (status, out, _) = run(&mut shell, "(false || echo recovered)");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"recovered\n");
    }

    #[test]
    fn bang_negates_pipeline_status() {
        let mut shell = test_shell();
        run(&mut shell, "echo x > /tmp/real_file.txt");
        let (status, _, _) = run(&mut shell, "! cat /tmp/real_file.txt");
        assert_eq!(status, ExitStatus::FAILURE, "! <success> fails");
        let (status, _, _) = run(&mut shell, "! cat /tmp/none");
        assert_eq!(status, ExitStatus::SUCCESS, "! <failure> succeeds");
    }

    #[test]
    fn if_elif_else_executes() {
        let mut shell = test_shell();
        run(&mut shell, "echo yes > /tmp/marker.txt");
        let (status, out, _) = run(
            &mut shell,
            "if cat /tmp/marker.txt; then echo branch-then; elif cat /tmp/none; then echo branch-elif; else echo branch-else; fi",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"yes\nbranch-then\n");

        let (status, out, _) = run(
            &mut shell,
            "if cat /tmp/none; then echo branch-then; elif cat /tmp/marker.txt; then echo branch-elif; else echo branch-else; fi",
        );
        // `cat /tmp/marker.txt` prints the marker, then the elif body runs.
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"yes\nbranch-elif\n");

        let (status, out, _) = run(
            &mut shell,
            "if cat /tmp/none; then echo branch-then; else echo branch-else; fi",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"branch-else\n");
    }

    #[test]
    fn while_loops_until_the_condition_fails() {
        let mut shell = test_shell();
        // A loop over real state: run while the guard file exists, removing
        // it in the body, so the loop runs exactly once.
        run(&mut shell, "echo guard > /tmp/loop_guard.txt");
        let (status, _, _) = run(
            &mut shell,
            "while cat /tmp/loop_guard.txt; do rm /tmp/loop_guard.txt; done",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "cat /tmp/loop_guard.txt");
        assert_eq!(
            status,
            ExitStatus::FAILURE,
            "the loop body removed the guard"
        );
    }

    #[test]
    fn functions_are_defined_and_called() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "greet() { echo hello; }");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, out, _) = run(&mut shell, "greet");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"hello\n");
    }

    #[test]
    fn assignments_prefix_the_command_environment() {
        let mut shell = test_shell();
        // With PATH=/bin, `which ls` reports the path exactly as
        // constructed from the PATH entry, like real GNU which on a
        // merged-/usr system.
        let (status, out, _) = run(&mut shell, "PATH=/bin which ls");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"/bin/ls\n");
    }

    #[test]
    fn bare_assignments_persist_in_the_shell() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "MYVAR=hello");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(shell.environment().get("MYVAR"), Some("hello"));
        let (_, out, _) = run(&mut shell, "echo $MYVAR");
        assert_eq!(out, b"hello\n");
    }

    #[test]
    fn heredoc_feeds_stdin() {
        let mut shell = test_shell();
        let (status, out, _) = run(&mut shell, "cat <<EOF\nhello heredoc\nEOF");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"hello heredoc\n");
    }

    #[test]
    fn pipeline_pipes_output() {
        let mut shell = test_shell();
        run(&mut shell, "echo hello > /tmp/a.txt");
        let (status, out, _) = run(&mut shell, "cat /tmp/a.txt | cat");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"hello\n");
    }

    #[test]
    fn globs_expand_unquoted_stars() {
        let mut shell = test_shell();
        run(&mut shell, "echo a > /tmp/glob_a.txt");
        run(&mut shell, "echo b > /tmp/glob_b.txt");
        let (status, out, _) = run(&mut shell, "echo /tmp/glob_*.txt");
        assert_eq!(status, ExitStatus::SUCCESS);
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("glob_a.txt"));
        assert!(output.contains("glob_b.txt"));
        // Quoted globs stay literal.
        let (_, out, _) = run(&mut shell, "echo '/tmp/glob_*.txt'");
        assert_eq!(out, b"/tmp/glob_*.txt\n");
    }

    #[test]
    fn mv_overwrites_existing_files() {
        let mut shell = test_shell();
        run(&mut shell, "echo one > /tmp/a.txt");
        run(&mut shell, "echo two > /tmp/b.txt");
        let (status, _, _) = run(&mut shell, "mv /tmp/a.txt /tmp/b.txt");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (_, out, _) = run(&mut shell, "cat /tmp/b.txt");
        assert_eq!(out, b"one\n");
        let (status, _, _) = run(&mut shell, "cat /tmp/a.txt");
        assert_eq!(status, ExitStatus::FAILURE);
    }

    #[test]
    fn scripts_run_through_the_interpreter() {
        let mut shell = test_shell();
        run(
            &mut shell,
            "echo 'echo hello > /tmp/script_out.txt' > /tmp/script.sh",
        );
        let (status, _, _) = run(&mut shell, "sh /tmp/script.sh");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (_, out, _) = run(&mut shell, "cat /tmp/script_out.txt");
        assert_eq!(out, b"hello\n");
    }

    #[test]
    fn exit_carries_a_status_and_requests_session_end() {
        let mut shell = test_shell();
        assert!(shell.take_exit_status().is_none());
        let (status, _, _) = run(&mut shell, "exit 7");
        assert_eq!(status, ExitStatus::new(7));
        assert_eq!(shell.take_exit_status(), Some(ExitStatus::new(7)));
        // The request is consumed: a second poll sees none.
        assert!(shell.take_exit_status().is_none());
    }

    #[test]
    fn exit_defaults_to_success_and_wraps_out_of_range_codes() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "exit");
        assert_eq!(status, ExitStatus::SUCCESS);
        // bash wraps modulo 256: 300 & 0xFF == 44.
        let mut shell2 = test_shell();
        let (status, _, _) = run(&mut shell2, "exit 300");
        assert_eq!(status, ExitStatus::new(44));
    }

    #[test]
    fn exit_stops_script_processing_at_the_exit_line() {
        let mut shell = test_shell();
        run(&mut shell, "echo 'echo before' > /tmp/exit_script.sh");
        run(&mut shell, "echo 'exit 5' >> /tmp/exit_script.sh");
        run(&mut shell, "echo 'echo after' >> /tmp/exit_script.sh");
        let (status, out, _) = run(&mut shell, "bash /tmp/exit_script.sh");
        assert_eq!(status, ExitStatus::new(5));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("before"), "expected before: {text:?}");
        assert!(!text.contains("after"), "after must not print: {text:?}");
    }

    #[test]
    fn functions_receive_positional_parameters() {
        let mut shell = test_shell();
        run(&mut shell, "greet() { echo \"hello $1 ($# args)\"; }");
        let (status, out, _) = run(&mut shell, "greet world extra");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"hello world (2 args)\n");
    }

    #[test]
    fn nested_function_calls_restore_outer_parameters() {
        let mut shell = test_shell();
        run(&mut shell, "inner() { echo \"inner=$1\"; }");
        run(&mut shell, "outer() { inner X; echo \"outer=$1\"; }");
        let (_, out, _) = run(&mut shell, "outer Y");
        let text = String::from_utf8(out).unwrap();
        assert_eq!(text, "inner=X\nouter=Y\n");
    }

    #[test]
    fn scripts_receive_positional_parameters() {
        let mut shell = test_shell();
        run(
            &mut shell,
            "echo 'echo \"$0 got $1 and $2\"' > /tmp/args_script.sh",
        );
        let (_, out, _) = run(&mut shell, "bash /tmp/args_script.sh foo bar");
        assert_eq!(out, b"/tmp/args_script.sh got foo and bar\n");
    }

    #[test]
    fn command_substitution_receives_positional_parameters() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "bash -c 'echo value=$1' prog alpha");
        assert_eq!(out, b"value=alpha\n");
    }

    #[test]
    fn scripts_support_pipelines_and_conditionals() {
        let mut shell = test_shell();
        run(
            &mut shell,
            "echo 'cat /etc/hostname | cat && echo ok' > /tmp/pipe_script.sh",
        );
        let (status, out, _) = run(&mut shell, "sh /tmp/pipe_script.sh");
        assert_eq!(status, ExitStatus::SUCCESS);
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("demo-host"), "pipeline output flows");
        assert!(output.contains("ok"), "&& runs after success");
    }

    #[test]
    fn syntax_errors_report_usage_status() {
        let mut shell = test_shell();
        let (status, _, err) = run(&mut shell, "echo 'unterminated");
        assert_eq!(status, ExitStatus::USAGE);
        assert!(!err.is_empty());
    }

    #[test]
    fn continuation_detects_incomplete_constructs() {
        assert!(!needs_continuation("echo hi"));
        assert!(needs_continuation("cat <<EOF"));
        assert!(!needs_continuation("cat <<EOF\nbody\nEOF"));
        assert!(needs_continuation("if true; then"));
        assert!(!needs_continuation("if true; then echo x; fi"));
        assert!(needs_continuation("echo 'unterminated"));
    }

    #[test]
    fn break_stops_loops_and_continue_skips() {
        let mut shell = test_shell();
        run(&mut shell, "echo x > /tmp/brk_guard.txt");
        let (status, out, _) = run(
            &mut shell,
            "while cat /tmp/brk_guard.txt; do echo body; rm /tmp/brk_guard.txt; break; echo never; done",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        // The condition's `cat` prints the guard, then one body iteration.
        assert_eq!(out, b"x\nbody\n", "break stops after one iteration");

        let (status, out, _) = run(
            &mut shell,
            "for_placeholder=1; echo pre; continue; echo after",
        );
        let _ = status;
        // `continue` outside a loop is a no-op: the following unit still runs.
        assert_eq!(out, b"pre\nafter\n");
    }

    #[test]
    fn aliases_expand_at_invocation() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "alias ll='echo listed'");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, out, _) = run(&mut shell, "ll");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"listed\n");
        // Alias with arguments appends them.
        let (status, _, _) = run(&mut shell, "alias g='echo got'");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (_, out, _) = run(&mut shell, "g one two");
        assert_eq!(out, b"got one two\n");
    }

    #[test]
    fn bash_echo_does_not_interpret_escapes_by_default() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo 'a\\tb'");
        assert_eq!(out, b"a\\tb\n");
        let (_, out, _) = run(&mut shell, "echo -e 'a\\tb'");
        assert_eq!(out, b"a\tb\n");
    }

    #[test]
    fn for_loops_iterate_and_set_the_variable() {
        let mut shell = test_shell();
        let (status, out, _) = run(&mut shell, "for i in 1 2 3; do echo \"i=$i\"; done");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"i=1\ni=2\ni=3\n");
        let (status, out, _) = run(
            &mut shell,
            "for f in /etc/hostname /etc/passwd; do echo \"f=$f\"; done",
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        let output = String::from_utf8(out).unwrap();
        assert!(output.contains("f=/etc/hostname"));
        assert!(output.contains("f=/etc/passwd"));
    }

    #[test]
    fn parameter_operators_and_substitution() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo \"${NOTSET:-fallback}\"");
        assert_eq!(out, b"fallback\n");
        let (_, out, _) = run(&mut shell, "echo \"${NOTSET:=set-me}\"");
        assert_eq!(out, b"set-me\n");
        let (_, out, _) = run(&mut shell, "echo \"$NOTSET\"");
        assert_eq!(out, b"set-me\n");
        run(&mut shell, "export P=/a/b/c.txt");
        let (_, out, _) = run(&mut shell, "echo \"${P##*/}\"");
        assert_eq!(out, b"c.txt\n");
        let (_, out, _) = run(&mut shell, "echo \"${P%/*}\"");
        assert_eq!(out, b"/a/b\n");
        let (_, out, _) = run(&mut shell, "echo \"${#P}\"");
        assert_eq!(out, b"10\n");
        let (_, out, _) = run(&mut shell, "echo \"$(echo substituted)\"");
        assert_eq!(out, b"substituted\n");
        let (_, out, _) = run(&mut shell, "echo \"`echo backticked`\"");
        assert_eq!(out, b"backticked\n");
    }

    #[test]
    fn null_command_and_cd_dash() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, ":");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (_, _, _) = run(&mut shell, ": \"${BAR:=defaulted}\"");
        let (_, out, _) = run(&mut shell, "echo \"$BAR\"");
        assert_eq!(out, b"defaulted\n");
        run(&mut shell, "cd /etc");
        let (status, _, _) = run(&mut shell, "cd -");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (_, out, _) = run(&mut shell, "pwd");
        assert_eq!(out, b"/home/demo\n");
    }

    #[test]
    fn stderr_redirection_works() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "cat /etc/nonexistent 2> /tmp/err.txt");
        assert_eq!(status, ExitStatus::FAILURE);
        let (_, out, _) = run(&mut shell, "cat /tmp/err.txt");
        assert!(!out.is_empty());
        let (_, out, _) = run(&mut shell, "cat /etc/nonexistent 2>&1");
        assert!(!out.is_empty());
    }

    #[test]
    fn extended_test_evaluates() {
        let mut shell = test_shell();
        let (status, _, _) = run(&mut shell, "[[ 1 == 1 ]]");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "[[ -d /etc ]]");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "[[ \"abc\" == a* ]]");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "[[ 5 -gt 3 ]]");
        assert_eq!(status, ExitStatus::SUCCESS);
        let (status, _, _) = run(&mut shell, "[[ 1 == 2 ]]");
        assert_eq!(status, ExitStatus::FAILURE);
    }

    #[test]
    fn bash_type_reports_resolution() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "type cd");
        assert_eq!(out, b"cd is a shell builtin\n");
        let (_, out, _) = run(&mut shell, "type ls");
        assert_eq!(out, b"ls is /usr/bin/ls\n");
    }
}

#[cfg(test)]
mod terminal_tests {
    use super::*;
    use crate::Shell;
    use engine::{BytesInput, BytesOutput, Timestamp};
    use os::HostIdentity;
    use os::linux::Linux;
    use terminal::{Size, Terminal, TerminalModel};

    #[test]
    fn terminal_is_threaded_through_compound_lines() {
        let linux = Box::leak(Box::new(
            Linux::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let credentials = linux
            .unix()
            .users()
            .authenticate("demo", "demo", linux.unix().groups())
            .unwrap();
        let mut shell = Bash::new(linux.unix(), credentials).unwrap();
        let mut stdin = BytesInput::new(b"");
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let mut terminal = TerminalModel::new(Size::new(24, 80));
        terminal.push_keys(&[terminal::KeyEvent::character('q')]);
        // man consumes the terminal; the following unit still runs and the
        // terminal remains usable (main screen restored).
        let status = shell.execute_with_terminal(
            "man ls; echo done",
            &mut stdin,
            &mut stdout,
            &mut stderr,
            Some(&mut terminal),
        );
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(stdout.into_bytes(), b"done\n");
        assert!(!terminal.in_alternate_screen());
    }
}