gshell 1.0.1

gshell is a shell for people who live in the terminal. It pairs familiar Unix behavior with a tighter core, fast interaction, and an interface built to stay out of the way.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
use gshell::{
    builtins::{
        AliasBuiltin, BgBuiltin, Builtin, BuiltinRegistry, CdBuiltin, ClearBuiltin, EchoBuiltin,
        ExitBuiltin, FgBuiltin, HistoryBuiltin, JobsBuiltin, KillBuiltin, PwdBuiltin,
        SourceBuiltin, TypeBuiltin, UnaliasBuiltin,
    },
    jobs::{JobDisposition, JobState, ProcessState},
    parser::Parser,
    runtime::{BootstrapExecutor, Executor, load_startup_file, refresh_job_statuses},
    shell::{ExitCode, ShellAction, ShellState},
};

#[cfg(unix)]
use tokio::process::Command;

#[cfg(unix)]
use nix::{
    sys::{
        signal::{Signal, kill},
        wait::waitpid,
    },
    unistd::Pid,
};

#[test]
fn builtin_registry_lookup_works() {
    let registry = BuiltinRegistry::with_defaults();

    assert!(registry.contains("cd"));
    assert!(registry.contains("exit"));
    assert!(registry.contains("clear"));
    assert!(registry.contains("alias"));
    assert!(registry.contains("type"));
    assert!(registry.contains("unalias"));
    assert!(registry.contains("echo"));
    assert!(registry.contains("pwd"));
    assert!(registry.contains("history"));
    assert!(registry.contains("jobs"));
    assert!(registry.contains("fg"));
    assert!(registry.contains("bg"));
    assert!(registry.contains("kill"));
    assert!(registry.contains("source"));
    assert!(registry.get("missing").is_none());
}

#[tokio::test]
async fn jobs_builtin_lists_jobs() {
    let state = ShellState::shared().await.expect("state should initialize");
    {
        let mut guard = state.write().await;
        let first = guard.jobs_mut().insert(
            4100,
            "sleep 10",
            JobDisposition::Background,
            vec![gshell::jobs::ProcessRecord::new(4100, "sleep 10")],
        );
        let second = guard.jobs_mut().insert(
            4200,
            "printf hi | cat",
            JobDisposition::Background,
            vec![
                gshell::jobs::ProcessRecord::new(4201, "printf hi"),
                gshell::jobs::ProcessRecord::new(4202, "cat"),
            ],
        );
        let _ = guard
            .jobs_mut()
            .update_process_state(second, 4201, ProcessState::Stopped);
        let _ = guard
            .jobs_mut()
            .update_process_state(first, 4100, ProcessState::Completed(0));
        let _third = guard.jobs_mut().insert(
            4300,
            "sleep 30",
            JobDisposition::Foreground,
            vec![gshell::jobs::ProcessRecord::new(4300, "sleep 30")],
        );
    }
    let builtin = JobsBuiltin;

    let result = builtin
        .execute(state, &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "[2] Stopped printf hi | cat\n");
        }
        ShellAction::Exit(_) => panic!("jobs should not exit"),
    }
}

#[tokio::test]
async fn fg_builtin_rejects_invalid_job_ids() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = FgBuiltin;

    let result = builtin
        .execute(state.clone(), &["%abc".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "fg: invalid job id: %abc\n");
        }
        ShellAction::Exit(_) => panic!("fg should not exit"),
    }

    let result = builtin
        .execute(state, &["%1".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "fg: no such job: %1\n");
        }
        ShellAction::Exit(_) => panic!("fg should not exit"),
    }
}

#[tokio::test]
async fn bg_builtin_rejects_missing_current_job() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = BgBuiltin;

    let result = builtin
        .execute(state, &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "bg: no current job\n");
        }
        ShellAction::Exit(_) => panic!("bg should not exit"),
    }
}

#[tokio::test]
async fn kill_builtin_requires_at_least_one_target() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = KillBuiltin;

    let result = builtin
        .execute(state, &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "kill: usage: kill [-SIGNAL] <pid|%job>...\n");
        }
        ShellAction::Exit(_) => panic!("kill should not exit"),
    }
}

#[tokio::test]
async fn kill_builtin_rejects_invalid_job_ids() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = KillBuiltin;

    let result = builtin
        .execute(state.clone(), &["%abc".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "kill: invalid job id: %abc\n");
        }
        ShellAction::Exit(_) => panic!("kill should not exit"),
    }

    let result = builtin
        .execute(state, &["%1".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert_eq!(output.stderr, "kill: no such job: %1\n");
        }
        ShellAction::Exit(_) => panic!("kill should not exit"),
    }
}

#[cfg(unix)]
#[tokio::test]
async fn bg_builtin_resumes_stopped_job_in_background() {
    let (state, pid, job_id) = spawn_stopped_sleep_job().await;
    let builtin = BgBuiltin;

    let result = builtin
        .execute(state.clone(), &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, format!("[{job_id}] sleep 1\n"));
        }
        ShellAction::Exit(_) => panic!("bg should not exit"),
    }

    let guard = state.read().await;
    let job = guard.jobs().get(job_id).expect("job should exist");
    assert_eq!(job.state(), JobState::Running);
    assert_eq!(job.disposition(), JobDisposition::Background);
    drop(guard);

    kill(Pid::from_raw(pid as i32), Signal::SIGTERM).expect("SIGTERM should be delivered");
    let _ = waitpid(Pid::from_raw(pid as i32), None).expect("waitpid should succeed");
}

#[cfg(unix)]
#[tokio::test]
async fn fg_builtin_resumes_stopped_job_in_foreground() {
    let (state, _pid, job_id) = spawn_stopped_sleep_job().await;
    let builtin = FgBuiltin;

    let result = builtin
        .execute(state.clone(), &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "sleep 1\n");
        }
        ShellAction::Exit(_) => panic!("fg should not exit"),
    }

    let guard = state.read().await;
    let job = guard.jobs().get(job_id).expect("job should exist");
    assert_eq!(job.state(), JobState::Completed);
    assert_eq!(guard.jobs().foreground_job(), None);
}

#[cfg(unix)]
#[tokio::test]
async fn kill_builtin_terminates_job_by_job_id() {
    let (state, _pid, job_id) = spawn_stopped_sleep_job().await;
    let builtin = KillBuiltin;

    let result = builtin
        .execute(
            state.clone(),
            &[String::from("-KILL"), format!("%{job_id}")],
        )
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.is_empty());
            assert!(output.stderr.is_empty());
        }
        ShellAction::Exit(_) => panic!("kill should not exit"),
    }

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    refresh_job_statuses(state.clone())
        .await
        .expect("job refresh should succeed");

    let guard = state.read().await;
    let job = guard.jobs().get(job_id).expect("job should exist");
    assert_eq!(job.state(), JobState::Completed);
}

#[cfg(unix)]
#[tokio::test]
#[ignore = "flaky completion timing in CI"]
async fn jobs_builtin_hides_completed_background_jobs_after_refresh() {
    let state = ShellState::shared().await.expect("state should initialize");
    let child = Command::new("sleep")
        .arg("0.1")
        .spawn()
        .expect("sleep should spawn");
    let pid = child.id().expect("child should have a pid");

    {
        let mut guard = state.write().await;
        guard.jobs_mut().insert(
            pid,
            "sleep 0.1",
            JobDisposition::Background,
            vec![gshell::jobs::ProcessRecord::new(pid, "sleep 0.1")],
        );
    }

    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        loop {
            refresh_job_statuses(state.clone())
                .await
                .expect("job refresh should succeed");

            let completed = {
                let guard = state.read().await;
                guard
                    .jobs()
                    .iter()
                    .any(|job| job.processes().iter().any(|process| process.pid() == pid))
                    && guard
                        .jobs()
                        .iter()
                        .find(|job| job.processes().iter().any(|process| process.pid() == pid))
                        .is_some_and(|job| job.state() == JobState::Completed)
            };

            if completed {
                break;
            }

            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
    })
    .await
    .expect("job should complete within timeout");

    let builtin = JobsBuiltin;
    let result = builtin
        .execute(state.clone(), &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.is_empty());
        }
        ShellAction::Exit(_) => panic!("jobs should not exit"),
    }

    drop(child);
}

#[cfg(unix)]
#[tokio::test]
async fn bg_job_disappears_from_jobs_after_it_finishes() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");
    let parsed = parser.parse("sleep 1").expect("parse should succeed");

    let state_for_task = state.clone();
    let task = tokio::spawn(async move {
        executor
            .execute(state_for_task, &parsed)
            .await
            .expect("execution should succeed")
    });

    let (pid, job_id) = loop {
        if let Some((pid, job_id)) = {
            let guard = state.read().await;
            guard.jobs().foreground_job().and_then(|job_id| {
                guard.jobs().get(job_id).and_then(|job| {
                    job.processes()
                        .first()
                        .map(|process| (process.pid(), job_id))
                })
            })
        } {
            break (pid, job_id);
        }

        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    };

    kill(Pid::from_raw(pid as i32), Signal::SIGSTOP).expect("SIGSTOP should be delivered");

    let result = tokio::time::timeout(std::time::Duration::from_secs(5), task)
        .await
        .expect("execution should return after stop")
        .expect("task should join successfully");

    match result {
        ShellAction::Continue(output) => assert!(output.exit_code.is_failure()),
        ShellAction::Exit(_) => panic!("sleep should not exit the shell"),
    }

    let bg = BgBuiltin;
    let result = bg
        .execute(state.clone(), &[])
        .await
        .expect("bg should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, format!("[{job_id}] sleep 1\n"));
        }
        ShellAction::Exit(_) => panic!("bg should not exit"),
    }

    tokio::time::sleep(std::time::Duration::from_millis(1300)).await;

    let jobs = JobsBuiltin;
    let result = jobs
        .execute(state.clone(), &[])
        .await
        .expect("jobs should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(
                output.stdout.is_empty(),
                "unexpected jobs output: {}",
                output.stdout
            );
        }
        ShellAction::Exit(_) => panic!("jobs should not exit"),
    }
}

#[cfg(unix)]
async fn spawn_stopped_sleep_job() -> (gshell::shell::SharedShellState, u32, u32) {
    use std::time::Duration;

    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");
    let parsed = parser.parse("sleep 1").expect("parse should succeed");

    let state_for_task = state.clone();
    let task = tokio::spawn(async move {
        executor
            .execute(state_for_task, &parsed)
            .await
            .expect("execution should succeed")
    });

    let (pid, job_id) = loop {
        if let Some((pid, job_id)) = {
            let guard = state.read().await;
            guard.jobs().foreground_job().and_then(|job_id| {
                guard.jobs().get(job_id).and_then(|job| {
                    job.processes()
                        .first()
                        .map(|process| (process.pid(), job_id))
                })
            })
        } {
            break (pid, job_id);
        }

        tokio::time::sleep(Duration::from_millis(25)).await;
    };

    kill(Pid::from_raw(pid as i32), Signal::SIGSTOP).expect("SIGSTOP should be delivered");

    let result = tokio::time::timeout(Duration::from_secs(5), task)
        .await
        .expect("execution should return after stop")
        .expect("task should join successfully");

    match result {
        ShellAction::Continue(output) => assert!(output.exit_code.is_failure()),
        ShellAction::Exit(_) => panic!("sleep should not exit the shell"),
    }

    (state, pid, job_id)
}

#[tokio::test]
async fn alias_builtin_sets_and_lists_aliases() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = AliasBuiltin;

    let result = builtin
        .execute(state.clone(), &["ll=echo hello".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.is_empty());
            assert_eq!(state.read().await.aliases().get("ll"), Some("echo hello"));
        }
        ShellAction::Exit(_) => panic!("alias should not exit"),
    }

    let result = builtin
        .execute(state, &["ll".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "alias ll='echo hello'\n");
        }
        ShellAction::Exit(_) => panic!("alias should not exit"),
    }
}

#[tokio::test]
async fn unalias_builtin_removes_existing_alias() {
    let state = ShellState::shared().await.expect("state should initialize");
    state.write().await.aliases_mut().set("ll", "echo hello");
    let builtin = UnaliasBuiltin;

    let result = builtin
        .execute(state.clone(), &["ll".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(state.read().await.aliases().get("ll").is_none());
        }
        ShellAction::Exit(_) => panic!("unalias should not exit"),
    }
}

#[tokio::test]
async fn echo_builtin_outputs_joined_args() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = EchoBuiltin;

    let result = builtin
        .execute(state, &["hello".into(), "world".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "hello world\n");
        }
        ShellAction::Exit(_) => panic!("echo should not exit"),
    }
}

#[tokio::test]
async fn pwd_builtin_outputs_current_directory() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = PwdBuiltin;

    let result = builtin
        .execute(state.clone(), &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            let cwd = state.read().await.cwd().display().to_string();
            assert_eq!(output.stdout, format!("{cwd}\n"));
        }
        ShellAction::Exit(_) => panic!("pwd should not exit"),
    }
}

#[tokio::test]
async fn clear_builtin_emits_escape_sequence() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = ClearBuiltin;

    let result = builtin
        .execute(state, &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "\x1B[2J\x1B[H");
        }
        ShellAction::Exit(_) => panic!("clear should not exit"),
    }
}

#[tokio::test]
async fn cd_builtin_changes_shell_state_directory() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = CdBuiltin;

    let tmp = tempfile::tempdir().expect("temp dir should be created");
    let path = tmp.path().display().to_string();

    let result = builtin
        .execute(state.clone(), &[path])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            let cwd = state.read().await.cwd().to_path_buf();
            let expected = std::fs::canonicalize(tmp.path())
                .expect("temp dir path should canonicalize successfully");
            assert_eq!(cwd, expected);
        }
        ShellAction::Exit(_) => panic!("cd should not exit"),
    }
}

#[tokio::test]
async fn cd_builtin_rejects_too_many_arguments() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = CdBuiltin;

    let result = builtin
        .execute(state, &["a".into(), "b".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert!(output.stderr.contains("too many arguments"));
        }
        ShellAction::Exit(_) => panic!("cd should not exit"),
    }
}

#[tokio::test]
async fn type_builtin_reports_builtin() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = TypeBuiltin;

    let result = builtin
        .execute(state, &["echo".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.contains("echo is a shell builtin"));
        }
        ShellAction::Exit(_) => panic!("type should not exit"),
    }
}

#[tokio::test]
async fn type_builtin_reports_alias() {
    let state = ShellState::shared().await.expect("state should initialize");
    state.write().await.aliases_mut().set("ll", "echo hello");
    let builtin = TypeBuiltin;

    let result = builtin
        .execute(state, &["ll".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.contains("ll is aliased to `echo hello`"));
        }
        ShellAction::Exit(_) => panic!("type should not exit"),
    }
}

#[tokio::test]
async fn type_builtin_reports_function() {
    let state = ShellState::shared().await.expect("state should initialize");
    let parser = Parser::default();
    let defined = parser
        .parse("greet() { echo hi; }")
        .expect("parse should succeed");
    let executor = BootstrapExecutor;
    let _ = executor
        .execute(state.clone(), &defined)
        .await
        .expect("function definition should succeed");
    let builtin = TypeBuiltin;

    let result = builtin
        .execute(state, &["greet".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.contains("greet is a shell function"));
        }
        ShellAction::Exit(_) => panic!("type should not exit"),
    }
}

#[tokio::test]
async fn type_builtin_fails_for_unknown_command() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = TypeBuiltin;

    let result = builtin
        .execute(state, &["definitely-not-real".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::FAILURE);
            assert!(output.stderr.contains("not found"));
        }
        ShellAction::Exit(_) => panic!("type should not exit"),
    }
}

#[tokio::test]
async fn exit_builtin_requests_shell_exit() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = ExitBuiltin;

    let result = builtin
        .execute(state, &["42".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Exit(code) => assert_eq!(code, ExitCode::new(42)),
        ShellAction::Continue(_) => panic!("exit should terminate the shell"),
    }
}

#[tokio::test]
async fn history_builtin_outputs_entries() {
    let state = ShellState::shared().await.expect("state should initialize");
    {
        let mut guard = state.write().await;
        guard.history_mut().push("echo hello");
        guard.history_mut().push("history");
    }

    let builtin = HistoryBuiltin;
    let result = builtin
        .execute(state, &[])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert!(output.stdout.contains("echo hello"));
            assert!(output.stdout.contains("history"));
        }
        ShellAction::Exit(_) => panic!("history should not exit"),
    }
}

#[tokio::test]
async fn source_builtin_loads_gshrc_via_tilde_expansion() {
    let state = ShellState::shared().await.expect("state should initialize");
    let builtin = SourceBuiltin;
    let tmp = tempfile::tempdir().expect("temp dir should be created");
    let rc_path = tmp.path().join(".gshrc");

    std::fs::write(&rc_path, "alias ll='echo first'\nRC_VALUE=loaded\n")
        .expect("rc file should be written");

    state
        .write()
        .await
        .set_env_var("HOME", tmp.path().display().to_string());

    let result = builtin
        .execute(state.clone(), &["~/.gshrc".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            let guard = state.read().await;
            assert_eq!(guard.aliases().get("ll"), Some("echo first"));
            assert_eq!(guard.env_var("RC_VALUE"), Some("loaded"));
        }
        ShellAction::Exit(_) => panic!("source should not exit"),
    }

    std::fs::write(&rc_path, "alias ll='echo second'\nRC_VALUE=reloaded\n")
        .expect("rc file should be rewritten");

    let result = builtin
        .execute(state.clone(), &["~/.gshrc".into()])
        .await
        .expect("builtin execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            let guard = state.read().await;
            assert_eq!(guard.aliases().get("ll"), Some("echo second"));
            assert_eq!(guard.env_var("RC_VALUE"), Some("reloaded"));
        }
        ShellAction::Exit(_) => panic!("source should not exit"),
    }
}

#[tokio::test]
async fn startup_loader_sources_gshrc_from_home() {
    let state = ShellState::shared().await.expect("state should initialize");
    let tmp = tempfile::tempdir().expect("temp dir should be created");
    let rc_path = tmp.path().join(".gshrc");

    std::fs::write(&rc_path, "GREETING=ready\ngreet() { echo hi; }\n")
        .expect("rc file should be written");

    state
        .write()
        .await
        .set_env_var("HOME", tmp.path().display().to_string());

    load_startup_file(state.clone())
        .await
        .expect("startup file should load");

    let guard = state.read().await;
    assert_eq!(guard.env_var("GREETING"), Some("ready"));
    assert!(guard.functions().get("greet").is_some());
}

#[tokio::test]
async fn parsed_argv_reaches_echo_builtin_with_single_quotes() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");

    let parsed = parser
        .parse("echo 'hello world'")
        .expect("parse should succeed");

    let result = executor
        .execute(state, &parsed)
        .await
        .expect("execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "hello world\n");
        }
        ShellAction::Exit(_) => panic!("echo should not exit"),
    }
}

#[tokio::test]
async fn parsed_argv_reaches_echo_builtin_with_double_quotes() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");

    let parsed = parser
        .parse("echo \"hello world\"")
        .expect("parse should succeed");

    let result = executor
        .execute(state, &parsed)
        .await
        .expect("execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "hello world\n");
        }
        ShellAction::Exit(_) => panic!("echo should not exit"),
    }
}

#[tokio::test]
async fn assignment_only_command_updates_shell_environment() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");

    let parsed = parser.parse("NAME=gencho").expect("parse should succeed");

    let result = executor
        .execute(state.clone(), &parsed)
        .await
        .expect("execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(state.read().await.env_var("NAME"), Some("gencho"));
        }
        ShellAction::Exit(_) => panic!("assignment should not exit"),
    }
}

#[tokio::test]
async fn assignment_prefix_is_visible_to_builtin_arguments() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");

    let parsed = parser
        .parse("NAME=gencho echo $NAME")
        .expect("parse should succeed");

    let result = executor
        .execute(state.clone(), &parsed)
        .await
        .expect("execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "gencho\n");
        }
        ShellAction::Exit(_) => panic!("echo should not exit"),
    }
}

#[tokio::test]
async fn assignment_prefix_does_not_persist_after_builtin_runs() {
    let parser = Parser::default();
    let executor = BootstrapExecutor;
    let state = ShellState::shared().await.expect("state should initialize");

    let parsed = parser
        .parse("NAME=gencho echo $NAME; echo $NAME")
        .expect("parse should succeed");

    let result = executor
        .execute(state.clone(), &parsed)
        .await
        .expect("execution should succeed");

    match result {
        ShellAction::Continue(output) => {
            assert_eq!(output.exit_code, ExitCode::SUCCESS);
            assert_eq!(output.stdout, "gencho\n\n");
            assert_eq!(state.read().await.env_var("NAME"), None);
        }
        ShellAction::Exit(_) => panic!("echo should not exit"),
    }
}