kaish-repl 0.1.8

Interactive REPL for kaish (会sh)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! Integration tests for kaish REPL.
//!
//! These tests run scripts through the REPL and verify behavior.

use kaish_repl::{ProcessResult, Repl};

/// Helper to run multiple lines through a REPL and collect outputs.
///
/// For multi-line constructs (if/fi, for/done, case/esac, while/done),
/// lines are joined before parsing so that the parser can handle them
/// as complete statements.
fn run_script(script: &str) -> Vec<String> {
    let mut repl = Repl::new().expect("Failed to create REPL");
    let mut outputs = Vec::new();

    // Collect lines, joining multi-line constructs
    let mut current_block = String::new();
    let mut block_depth: usize = 0;

    for line in script.lines() {
        // Skip comments and empty lines at the top level
        let trimmed = line.trim();
        if block_depth == 0 && (trimmed.is_empty() || trimmed.starts_with('#')) {
            continue;
        }

        // Track block depth for multi-line constructs
        // Count opening keywords (if, for, while, case)
        for word in trimmed.split_whitespace() {
            match word {
                "if" | "for" | "while" | "case" => block_depth += 1,
                "fi" | "done" | "esac" => block_depth = block_depth.saturating_sub(1),
                _ => {}
            }
            // Handle semi-terminated keywords like "fi;" or "done;"
            let word_clean = word.trim_end_matches(';');
            match word_clean {
                "fi" | "done" | "esac" if word != word_clean => {
                    // Already counted above, but with semicolon
                }
                _ => {}
            }
        }

        // Append line to current block
        if !current_block.is_empty() {
            current_block.push('\n');
        }
        current_block.push_str(trimmed);

        // If we're at top level (depth 0), process the block
        if block_depth == 0 && !current_block.is_empty() {
            match repl.process_line(&current_block) {
                ProcessResult::Output(output) => outputs.push(output),
                ProcessResult::Empty => {}
                ProcessResult::Exit => break,
            }
            current_block.clear();
        }
    }

    // Process any remaining content
    if !current_block.is_empty() {
        match repl.process_line(&current_block) {
            ProcessResult::Output(output) => outputs.push(output),
            ProcessResult::Empty => {}
            ProcessResult::Exit => {}
        }
    }

    outputs
}

/// Helper to check if output contains expected strings.
fn outputs_contain(outputs: &[String], expected: &[&str]) -> bool {
    let joined = outputs.join("\n");
    expected.iter().all(|e| joined.contains(e))
}

// ============================================================================
// Scope Tests
// ============================================================================

#[test]
fn scope_basic_variable() {
    let outputs = run_script(r#"
        X=42
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["42"]));
}

#[test]
fn scope_variable_shadowing_in_loop() {
    let outputs = run_script(r#"
        X="outer"
        for I in "inner"; do X=${I}; echo ${X}; done
        echo ${X}
    "#);
    // Note: Current behavior - X in loop is in inner frame, so outer X unchanged
    // This tests ACTUAL behavior, not necessarily DESIRED behavior
    let joined = outputs.join("\n");
    assert!(joined.contains("inner"), "Should print inner inside loop. Output was: {}", joined);
}

#[test]
fn scope_json_as_string() {
    // Objects are now stored as JSON strings, processed with jq
    let outputs = run_script(r#"
        DATA='{"user": {"name": "Alice"}}'
        echo ${DATA}
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("Alice"), "JSON string should contain Alice. Output was: {}", joined);
}

#[test]
fn scope_last_result_propagation() {
    let outputs = run_script(r#"
        echo "first"
        echo "code was ${?.code}"
    "#);
    assert!(outputs_contain(&outputs, &["first", "code was 0"]));
}

#[test]
fn scope_last_result_fields() {
    let outputs = run_script(r#"
        echo "test output"
        echo "ok=${?.ok}"
    "#);
    assert!(outputs_contain(&outputs, &["ok=true"]));
}

// ============================================================================
// Interpolation Tests
// ============================================================================

#[test]
fn interpolation_basic() {
    let outputs = run_script(r#"
        NAME="World"
        echo "Hello ${NAME}"
    "#);
    assert!(outputs_contain(&outputs, &["Hello World"]));
}

#[test]
fn interpolation_empty_string() {
    let outputs = run_script(r#"
        EMPTY=""
        echo "before${EMPTY}after"
    "#);
    assert!(outputs_contain(&outputs, &["beforeafter"]));
}

#[test]
fn interpolation_multiple_vars() {
    let outputs = run_script(r#"
        A="one"
        B="two"
        echo "${A} ${B}"
    "#);
    assert!(outputs_contain(&outputs, &["one two"]));
}

#[test]
fn interpolation_adjacent_no_space() {
    let outputs = run_script(r#"
        A="one"
        B="two"
        echo "${A}${B}"
    "#);
    assert!(outputs_contain(&outputs, &["onetwo"]));
}

#[test]
fn interpolation_json_string() {
    // Objects are now JSON strings
    let outputs = run_script(r#"
        OBJ='{"inner": {"value": "nested"}}'
        echo "got: ${OBJ}"
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("nested"), "JSON string should contain nested. Output was: {}", joined);
}

#[test]
fn interpolation_word_split() {
    // Explicit split required — kaish has no implicit word splitting
    let outputs = run_script(r#"
        ITEMS="zero one two"
        for I in $(split ${ITEMS}); do echo ${I}; done
    "#);
    assert!(outputs_contain(&outputs, &["zero", "one", "two"]));
}

#[test]
fn interpolation_number() {
    let outputs = run_script(r#"
        NUM=42
        echo "num=${NUM}"
    "#);
    assert!(outputs_contain(&outputs, &["num=42"]));
}

#[test]
fn interpolation_boolean() {
    let outputs = run_script(r#"
        FLAG=true
        echo "flag=${FLAG}"
    "#);
    assert!(outputs_contain(&outputs, &["flag=true"]));
}

#[test]
fn interpolation_null() {
    let outputs = run_script(r#"
        NOTHING=null
        echo "val=${NOTHING}"
    "#);
    assert!(outputs_contain(&outputs, &["val=null"]));
}

// ============================================================================
// Expression Tests
// ============================================================================

#[test]
fn expr_equality() {
    // Shell-compatible: use [[ ]] for comparisons
    let outputs = run_script(r#"
        X=5
        if [[ ${X} == 5 ]]; then echo "equal"; fi
    "#);
    assert!(outputs_contain(&outputs, &["equal"]));
}

#[test]
fn expr_inequality() {
    let outputs = run_script(r#"
        X=5
        if [[ ${X} != 3 ]]; then echo "not equal"; fi
    "#);
    assert!(outputs_contain(&outputs, &["not equal"]));
}

#[test]
fn expr_less_than() {
    let outputs = run_script(r#"
        if [[ 3 -lt 5 ]]; then echo "less"; fi
    "#);
    assert!(outputs_contain(&outputs, &["less"]));
}

#[test]
fn expr_greater_than() {
    let outputs = run_script(r#"
        if [[ 5 -gt 3 ]]; then echo "greater"; fi
    "#);
    assert!(outputs_contain(&outputs, &["greater"]));
}

#[test]
fn expr_and_short_circuit() {
    let outputs = run_script(r#"
        if true && true; then echo "both true"; fi
        if true && false; then echo "wrong"; else echo "short circuit"; fi
    "#);
    assert!(outputs_contain(&outputs, &["both true", "short circuit"]));
}

#[test]
fn expr_or_short_circuit() {
    let outputs = run_script(r#"
        if false || true; then echo "found true"; fi
        if true || false; then echo "first true"; fi
    "#);
    assert!(outputs_contain(&outputs, &["found true", "first true"]));
}

#[test]
fn expr_precedence_and_or() {
    // && binds tighter than ||
    // true || false && false  =  true || (false && false)  =  true || false  =  true
    // Shell-compatible: command chaining with && and ||
    let outputs = run_script(r#"
        if true || false && false; then echo "precedence ok"; fi
    "#);
    assert!(outputs_contain(&outputs, &["precedence ok"]));
}

#[test]
fn expr_int_float_comparison() {
    // Shell-compatible: use [[ ]] for comparisons
    let outputs = run_script(r#"
        I=5
        F=5.0
        if [[ ${I} == ${F} ]]; then echo "int equals float"; fi
    "#);
    assert!(outputs_contain(&outputs, &["int equals float"]));
}

#[test]
fn expr_string_comparison() {
    // Shell-compatible: use [[ ]] with == for string comparison
    // Note: lexicographic < comparison may have parsing issues in REPL context
    let outputs = run_script(r#"
        if [[ "apple" != "banana" ]]; then echo "apple different"; fi
    "#);
    let joined = outputs.join("\n");
    assert!(outputs_contain(&outputs, &["apple different"]), "Output was: {}", joined);
}

#[test]
fn expr_truthiness_zero() {
    // Shell-compatible: test zero with explicit comparison
    let outputs = run_script(r#"
        if [[ 0 == 0 ]]; then echo "zero is zero"; fi
        if [[ 0 != 1 ]]; then echo "zero not one"; fi
    "#);
    assert!(outputs_contain(&outputs, &["zero is zero", "zero not one"]));
}

#[test]
fn expr_truthiness_empty_string() {
    // Shell-compatible: use [[ -z ]] to test for empty string
    let outputs = run_script(r#"
        if [[ -z "" ]]; then echo "empty falsy"; fi
    "#);
    assert!(outputs_contain(&outputs, &["empty falsy"]));
}

#[test]
fn expr_truthiness_null() {
    // Shell-compatible: test zero value with explicit comparison
    let outputs = run_script(r#"
        ZERO=0
        if [[ ${ZERO} == 0 ]]; then echo "zero falsy"; fi
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("zero falsy"), "Output was: {}", joined);
}

#[test]
fn expr_truthiness_empty_string_var() {
    // Shell-compatible: use [[ -z ]] to test empty string variable
    let outputs = run_script(r#"
        EMPTY=""
        if [[ -z ${EMPTY} ]]; then echo "empty var falsy"; fi
    "#);
    assert!(outputs_contain(&outputs, &["empty var falsy"]));
}

#[test]
fn expr_truthiness_non_empty_string() {
    // Shell-compatible: use [[ -n ]] to test non-empty string
    let outputs = run_script(r#"
        STR="hello"
        if [[ -n ${STR} ]]; then echo "string truthy"; fi
    "#);
    assert!(outputs_contain(&outputs, &["string truthy"]));
}

// ============================================================================
// Control Flow Tests
// ============================================================================

#[test]
fn control_if_then() {
    let outputs = run_script(r#"
        if true; then echo "yes"; fi
    "#);
    assert!(outputs_contain(&outputs, &["yes"]));
}

#[test]
fn control_if_else() {
    let outputs = run_script(r#"
        if false; then echo "wrong"; else echo "else branch"; fi
    "#);
    assert!(outputs_contain(&outputs, &["else branch"]));
}

#[test]
fn control_nested_if() {
    // Shell-compatible: use [[ ]] for comparisons
    let outputs = run_script(r#"
        X=5
        if [[ ${X} -gt 0 ]]; then
            if [[ ${X} -lt 10 ]]; then
                echo "in range"
            fi
        fi
    "#);
    assert!(outputs_contain(&outputs, &["in range"]));
}

#[test]
fn control_for_loop() {
    // kaish requires explicit split for word splitting (no implicit splitting)
    let outputs = run_script(r#"
        for I in $(split "1 2 3"); do echo ${I}; done
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("1"), "Output was: {}", joined);
    assert!(joined.contains("2"), "Output was: {}", joined);
    assert!(joined.contains("3"), "Output was: {}", joined);
}

#[test]
fn control_nested_loops() {
    // kaish requires explicit split for word splitting
    let outputs = run_script(r#"
        for I in $(split "1 2"); do for J in $(split "a b"); do echo "${I}-${J}"; done; done
    "#);
    assert!(outputs_contain(&outputs, &["1-a", "1-b", "2-a", "2-b"]));
}

#[test]
fn control_empty_loop() {
    // Empty split produces no iterations
    let outputs = run_script(r#"
        EMPTY=""
        for I in $(split ${EMPTY}); do echo "never"; done
        echo "after"
    "#);
    assert!(outputs_contain(&outputs, &["after"]));
    assert!(!outputs_contain(&outputs, &["never"]));
}

#[test]
fn control_loop_with_conditional() {
    // kaish requires explicit split; values are strings, compare with string "2"
    let outputs = run_script(r#"
        for I in $(split "1 2 3"); do if [[ ${I} == "2" ]]; then echo "found two"; fi; done
    "#);
    assert!(outputs_contain(&outputs, &["found two"]));
}

// ============================================================================
// Command Substitution Tests
// ============================================================================

#[test]
fn cmd_subst_basic() {
    // Command substitution captures stdout as a string
    let outputs = run_script(r#"
        R=$(echo "hello")
        echo ${R}
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("hello"), "Should have captured output. Output was: {}", joined);
}

#[test]
fn cmd_subst_last_result() {
    // $? returns last command exit code
    let outputs = run_script(r#"
        echo "hello"
        echo "code was ${?}"
    "#);
    assert!(outputs_contain(&outputs, &["code was 0"]));
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn error_undefined_variable() {
    let outputs = run_script(r#"
        echo ${UNDEFINED}
    "#);
    let joined = outputs.join("\n");
    // Should produce an error, not crash
    assert!(joined.contains("ERROR") || joined.contains("undefined"));
}

#[test]
fn error_invalid_path() {
    let outputs = run_script(r#"
        X=42
        echo ${X.field}
    "#);
    let joined = outputs.join("\n");
    // Should error on field access of int
    assert!(joined.contains("ERROR") || joined.contains("undefined"));
}

#[test]
fn error_invalid_field_access() {
    let outputs = run_script(r#"
        NUM=42
        echo ${NUM.field}
    "#);
    let joined = outputs.join("\n");
    // Should error on field access of non-object
    assert!(joined.contains("ERROR") || joined.contains("undefined"));
}

// ============================================================================
// Unicode Tests
// ============================================================================

#[test]
fn unicode_basic() {
    let outputs = run_script(r#"
        echo "Hello, 世界!"
    "#);
    assert!(outputs_contain(&outputs, &["Hello, 世界!"]));
}

#[test]
fn unicode_emoji() {
    let outputs = run_script(r#"
        echo "🎉🚀✨"
    "#);
    assert!(outputs_contain(&outputs, &["🎉🚀✨"]));
}

#[test]
fn unicode_in_variable() {
    let outputs = run_script(r#"
        GREETING="こんにちは"
        echo ${GREETING}
    "#);
    assert!(outputs_contain(&outputs, &["こんにちは"]));
}

// ============================================================================
// Stress Tests
// ============================================================================

#[test]
fn stress_many_variables() {
    let outputs = run_script(r#"
        V1=1
        V2=2
        V3=3
        V4=4
        V5=5
        echo "${V1}${V2}${V3}${V4}${V5}"
    "#);
    assert!(outputs_contain(&outputs, &["12345"]));
}

#[test]
fn stress_json_string() {
    // Complex JSON stored as string
    let outputs = run_script(r#"
        D='{"a": {"b": {"c": {"d": "deep"}}}}'
        echo ${D}
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("deep"), "JSON string should contain deep. Output was: {}", joined);
}

#[test]
fn stress_many_items() {
    // Explicit split — kaish has no implicit word splitting
    let outputs = run_script(r#"
        ITEMS="1 2 3 4 5 6 7 8 9 10"
        for I in $(split ${ITEMS}); do echo ${I}; done
    "#);
    assert!(outputs_contain(&outputs, &["1", "5", "10"]));
}

#[test]
fn stress_complex_condition() {
    let outputs = run_script(r#"
        if true && true && true && true && true; then
            if false || false || false || true; then
                echo "complex passed"
            fi
        fi
    "#);
    assert!(outputs_contain(&outputs, &["complex passed"]));
}

// ============================================================================
// Introspection Builtin Tests
// ============================================================================

#[test]
fn introspect_vars_shows_set_variables() {
    let outputs = run_script(r#"
        X=42
        NAME="Alice"
        vars
    "#);
    let joined = outputs.join("\n");
    // Table format: NAME\tVALUE\tTYPE (canonical TSV from OutputData)
    assert!(joined.contains("X"), "vars should show X. Output was: {}", joined);
    assert!(joined.contains("42"), "vars should show 42. Output was: {}", joined);
    assert!(joined.contains("NAME"), "vars should show NAME. Output was: {}", joined);
}

#[test]
fn introspect_vars_json_format() {
    let outputs = run_script(r#"
        COUNT=100
        vars --json
    "#);
    let joined = outputs.join("\n");
    // Global --json produces table-keyed JSON: [{"NAME": ..., "VALUE": ..., "TYPE": ...}]
    assert!(joined.contains("\"NAME\""), "vars --json should have NAME field. Output was: {}", joined);
    assert!(joined.contains("\"VALUE\""), "vars --json should have VALUE field. Output was: {}", joined);
    assert!(joined.contains("COUNT"), "vars --json should include COUNT. Output was: {}", joined);
}

#[test]
fn introspect_tools_lists_builtins() {
    let outputs = run_script(r#"
        tools
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("echo"), "tools should list echo. Output was: {}", joined);
    assert!(joined.contains("ls"), "tools should list ls. Output was: {}", joined);
    assert!(joined.contains("cat"), "tools should list cat. Output was: {}", joined);
    assert!(joined.contains("vars"), "tools should list vars. Output was: {}", joined);
}

#[test]
fn introspect_tools_json_format() {
    let outputs = run_script(r#"
        tools --json
    "#);
    let joined = outputs.join("\n");
    // Global --json produces table-keyed JSON: [{"NAME": ..., "DESCRIPTION": ..., "PARAMS": ...}]
    assert!(joined.contains("\"NAME\""), "tools --json should have NAME field. Output was: {}", joined);
    assert!(joined.contains("\"DESCRIPTION\""), "tools --json should have DESCRIPTION field. Output was: {}", joined);
    // Should contain JSON array structure
    assert!(joined.contains('[') && joined.contains(']'), "tools --json should return array. Output was: {}", joined);
}

#[test]
fn introspect_tools_detail() {
    let outputs = run_script(r#"
        tools echo
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("echo"), "tools echo should show echo info. Output was: {}", joined);
}

#[test]
fn introspect_mounts_shows_vfs() {
    let outputs = run_script(r#"
        mounts
    "#);
    let joined = outputs.join("\n");
    // Should show at least the root mount
    assert!(joined.contains("/"), "mounts should show root. Output was: {}", joined);
    // Should indicate read-write or read-only
    assert!(joined.contains("rw") || joined.contains("ro"), "mounts should show mode. Output was: {}", joined);
}

#[test]
fn introspect_mounts_json_format() {
    let outputs = run_script(r#"
        mounts --json
    "#);
    let joined = outputs.join("\n");
    // Global --json produces table-keyed JSON: [{"PATH": ..., "MODE": ...}]
    assert!(joined.contains("\"PATH\""), "mounts --json should have PATH. Output was: {}", joined);
    assert!(joined.contains("\"MODE\""), "mounts --json should have MODE. Output was: {}", joined);
}

// ============================================================================
// Case Statement Integration Tests
// ============================================================================

#[test]
fn case_simple_match() {
    let outputs = run_script(r#"
        EXT="rs"
        case ${EXT} in
            rs) echo "Rust" ;;
            py) echo "Python" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["Rust"]));
}

#[test]
fn case_wildcard_match() {
    let outputs = run_script(r#"
        FILE="main.rs"
        case ${FILE} in
            *.py) echo "Python" ;;
            *.rs) echo "Rust" ;;
            *) echo "Unknown" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["Rust"]));
}

#[test]
fn case_default_fallthrough() {
    let outputs = run_script(r#"
        FILE="data.json"
        case ${FILE} in
            *.py) echo "Python" ;;
            *.rs) echo "Rust" ;;
            *) echo "Other" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["Other"]));
}

#[test]
fn case_no_match() {
    let outputs = run_script(r#"
        X="nomatch"
        case ${X} in
            foo) echo "foo" ;;
            bar) echo "bar" ;;
        esac
        echo "done"
    "#);
    // Should not match anything, then continue to echo done
    assert!(outputs_contain(&outputs, &["done"]));
    let joined = outputs.join("\n");
    assert!(!joined.contains("foo") && !joined.contains("bar"));
}

#[test]
fn case_multiple_patterns() {
    // Test multiple patterns with | separator
    let outputs = run_script(r#"
        EXT="ts"
        case ${EXT} in
            js|ts|jsx|tsx) echo "JavaScript family" ;;
            py|pyc|pyw) echo "Python family" ;;
            *) echo "other" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["JavaScript family"]));
}

#[test]
fn case_char_class() {
    let outputs = run_script(r#"
        CH="B"
        case ${CH} in
            [a-z]) echo "lower" ;;
            [A-Z]) echo "upper" ;;
            [0-9]) echo "digit" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["upper"]));
}

#[test]
fn case_question_mark() {
    let outputs = run_script(r#"
        CODE="A1"
        case ${CODE} in
            ??) echo "two chars" ;;
            ???) echo "three chars" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["two chars"]));
}

#[test]
fn case_in_loop() {
    let outputs = run_script(r#"
        for F in "a.rs" "b.py" "c.go"; do
            case ${F} in
                *.rs) echo "rust" ;;
                *.py) echo "python" ;;
                *) echo "other" ;;
            esac
        done
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("rust"), "Should find rust");
    assert!(joined.contains("python"), "Should find python");
    assert!(joined.contains("other"), "Should find other");
}

#[test]
fn case_nested_control_flow() {
    let outputs = run_script(r#"
        X="test"
        case ${X} in
            test)
                if true; then
                    echo "nested-if"
                fi
            ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["nested-if"]));
}

#[test]
fn case_with_brace_expansion() {
    let outputs = run_script(r#"
        FILE="code.ts"
        case ${FILE} in
            *.{js,ts}) echo "JavaScript family" ;;
            *.{c,cpp,h}) echo "C family" ;;
            *) echo "Unknown" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["JavaScript family"]));
}

// ============================================================================
// Arithmetic Expression Integration Tests
// ============================================================================

#[test]
fn arithmetic_simple() {
    let outputs = run_script(r#"
        X=$((1 + 2))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["3"]));
}

#[test]
fn arithmetic_with_variables() {
    let outputs = run_script(r#"
        A=10
        B=20
        C=$((A + B))
        echo ${C}
    "#);
    assert!(outputs_contain(&outputs, &["30"]));
}

#[test]
fn arithmetic_complex() {
    let outputs = run_script(r#"
        X=$((2 * (3 + 4) - 5))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["9"]));
}

#[test]
fn arithmetic_negative() {
    let outputs = run_script(r#"
        X=$((-5 + 3))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["-2"]));
}

#[test]
fn arithmetic_modulo() {
    let outputs = run_script(r#"
        X=$((17 % 5))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["2"]));
}

#[test]
fn arithmetic_in_condition() {
    let outputs = run_script(r#"
        A=5
        B=3
        if [[ $((A + B)) -gt 5 ]]; then
            echo "sum is big"
        fi
    "#);
    assert!(outputs_contain(&outputs, &["sum is big"]));
}

#[test]
fn arithmetic_in_loop() {
    let outputs = run_script(r#"
        SUM=0
        for N in 1 2 3 4 5; do
            SUM=$((SUM + N))
        done
        echo ${SUM}
    "#);
    assert!(outputs_contain(&outputs, &["15"]));
}

#[test]
fn arithmetic_division() {
    let outputs = run_script(r#"
        X=$((100 / 4))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["25"]));
}

#[test]
fn arithmetic_precedence() {
    let outputs = run_script(r#"
        X=$((2 + 3 * 4))
        echo ${X}
    "#);
    // Should be 14, not 20
    assert!(outputs_contain(&outputs, &["14"]));
}

#[test]
fn arithmetic_dollar_var() {
    let outputs = run_script(r#"
        N=7
        X=$(($N * 2))
        echo ${X}
    "#);
    assert!(outputs_contain(&outputs, &["14"]));
}

// ============================================================================
// Cross-Feature Tests
// ============================================================================

#[test]
fn cross_case_with_arithmetic() {
    let outputs = run_script(r#"
        N=$((2 + 3))
        case ${N} in
            5) echo "five" ;;
            *) echo "other" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["five"]));
}

#[test]
fn cross_loop_with_arithmetic_and_case() {
    let outputs = run_script(r#"
        for I in 1 2 3; do
            DOUBLE=$((I * 2))
            case ${DOUBLE} in
                2) echo "one doubled" ;;
                4) echo "two doubled" ;;
                6) echo "three doubled" ;;
            esac
        done
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("one doubled"));
    assert!(joined.contains("two doubled"));
    assert!(joined.contains("three doubled"));
}

#[test]
fn cross_condition_with_arithmetic() {
    let outputs = run_script(r#"
        A=10
        B=5
        if [[ $((A - B)) -gt 3 ]]; then
            echo "difference is significant"
        else
            echo "difference is small"
        fi
    "#);
    assert!(outputs_contain(&outputs, &["difference is significant"]));
}

#[test]
fn cross_nested_case_statements() {
    let outputs = run_script(r#"
        CATEGORY="animal"
        TYPE="dog"
        case ${CATEGORY} in
            animal)
                case ${TYPE} in
                    dog) echo "woof" ;;
                    cat) echo "meow" ;;
                esac
            ;;
            plant) echo "photosynthesis" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["woof"]));
}

#[test]
fn cross_conditional_arithmetic() {
    let outputs = run_script(r#"
        X=10
        if [[ $X -gt 5 ]]; then
            Y=$((X * 2))
        else
            Y=$((X / 2))
        fi
        echo ${Y}
    "#);
    assert!(outputs_contain(&outputs, &["20"]));
}

#[test]
fn cross_case_in_if() {
    // Shell-compatible: use [[ ]] for comparisons, compare to "true" string
    let outputs = run_script(r#"
        FLAG=true
        if [[ ${FLAG} == true ]]; then
            case "test.rs" in
                *.rs) echo "rust in if" ;;
            esac
        fi
    "#);
    assert!(outputs_contain(&outputs, &["rust in if"]));
}

// ============================================================================
// String and Variable Edge Cases
// ============================================================================

#[test]
fn var_with_default_unset() {
    let outputs = run_script(r#"
        echo "${UNDEFINED:-fallback}"
    "#);
    assert!(outputs_contain(&outputs, &["fallback"]));
}

#[test]
fn var_with_default_set() {
    let outputs = run_script(r#"
        DEFINED="value"
        echo "${DEFINED:-fallback}"
    "#);
    assert!(outputs_contain(&outputs, &["value"]));
}

#[test]
fn var_with_default_empty() {
    let outputs = run_script(r#"
        EMPTY=""
        echo "${EMPTY:-fallback}"
    "#);
    assert!(outputs_contain(&outputs, &["fallback"]));
}

#[test]
fn var_length() {
    let outputs = run_script(r#"
        MSG="hello"
        echo "${#MSG}"
    "#);
    assert!(outputs_contain(&outputs, &["5"]));
}

#[test]
fn var_length_empty() {
    let outputs = run_script(r#"
        EMPTY=""
        echo "${#EMPTY}"
    "#);
    assert!(outputs_contain(&outputs, &["0"]));
}

// ============================================================================
// Control Flow Edge Cases
// ============================================================================

#[test]
fn while_loop_with_counter() {
    let outputs = run_script(r#"
        I=0
        while [[ $I -lt 3 ]]; do
            echo "iteration ${I}"
            I=$((I + 1))
        done
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("iteration 0"));
    assert!(joined.contains("iteration 1"));
    assert!(joined.contains("iteration 2"));
}

#[test]
fn break_in_loop() {
    let outputs = run_script(r#"
        for I in "1" "2" "3" "4" "5"; do
            if [[ $I > "2" ]]; then
                break
            fi
            echo ${I}
        done
        echo "done"
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("1"), "Should contain 1: {}", joined);
    assert!(joined.contains("2"), "Should contain 2: {}", joined);
    assert!(!joined.contains("3"), "Should not contain 3: {}", joined);
    assert!(joined.contains("done"), "Should contain done: {}", joined);
}

#[test]
fn continue_in_loop() {
    let outputs = run_script(r#"
        for I in "1" "2" "3" "4" "5"; do
            if [[ $I == "3" ]]; then
                continue
            fi
            echo ${I}
        done
    "#);
    let joined = outputs.join("\n");
    assert!(joined.contains("1"), "Should contain 1: {}", joined);
    assert!(joined.contains("2"), "Should contain 2: {}", joined);
    assert!(!joined.contains("\n3\n") && !joined.contains("3\n") && !joined.contains("\n3"), "Should not contain 3 as separate output: {}", joined);
    assert!(joined.contains("4"), "Should contain 4: {}", joined);
    assert!(joined.contains("5"), "Should contain 5: {}", joined);
}

#[test]
fn elif_chain() {
    let outputs = run_script(r#"
        X=2
        if [[ $X == 1 ]]; then
            echo "one"
        elif [[ $X == 2 ]]; then
            echo "two"
        elif [[ $X == 3 ]]; then
            echo "three"
        else
            echo "other"
        fi
    "#);
    assert!(outputs_contain(&outputs, &["two"]));
}

// ============================================================================
// Glob Pattern Tests
// ============================================================================

#[test]
fn glob_asterisk() {
    let outputs = run_script(r#"
        case "hello.txt" in
            *.txt) echo "text file" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["text file"]));
}

#[test]
fn glob_question() {
    let outputs = run_script(r#"
        case "ab" in
            ??) echo "two chars" ;;
            ???) echo "three chars" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["two chars"]));
}

#[test]
fn glob_char_class_range() {
    let outputs = run_script(r#"
        case "5" in
            [0-9]) echo "digit" ;;
            [a-z]) echo "letter" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["digit"]));
}

#[test]
fn glob_char_class_negated() {
    let outputs = run_script(r#"
        case "A" in
            [!a-z]) echo "not lowercase" ;;
            [a-z]) echo "lowercase" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["not lowercase"]));
}

#[test]
fn glob_brace_expansion() {
    let outputs = run_script(r#"
        case "file.go" in
            *.{rs,go,py}) echo "supported lang" ;;
            *) echo "unsupported" ;;
        esac
    "#);
    assert!(outputs_contain(&outputs, &["supported lang"]));
}