bashkit 0.1.18

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

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;

use super::{Builtin, Context};
use crate::error::Result;
use crate::fs::FileSystem;
use crate::interpreter::ExecResult;

/// The test builtin command.
pub struct Test;

#[async_trait]
impl Builtin for Test {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        // Handle empty args - returns false
        if ctx.args.is_empty() {
            return Ok(ExecResult::err(String::new(), 1));
        }

        let cwd = ctx.cwd.clone();
        // Parse and evaluate the expression
        let result = evaluate_expression(ctx.args, &ctx.fs, &cwd, ctx.variables).await;

        if result {
            Ok(ExecResult::ok(String::new()))
        } else {
            Ok(ExecResult::err(String::new(), 1))
        }
    }
}

/// The [ builtin (alias for test, but expects ] as last arg)
pub struct Bracket;

#[async_trait]
impl Builtin for Bracket {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        // Check for closing ]
        if ctx.args.is_empty() || ctx.args.last() != Some(&"]".to_string()) {
            return Ok(ExecResult::err("missing ]\n".to_string(), 2));
        }

        // Remove the trailing ]
        let args: Vec<String> = ctx.args[..ctx.args.len() - 1].to_vec();

        // Handle empty args - returns false
        if args.is_empty() {
            return Ok(ExecResult::err(String::new(), 1));
        }

        let cwd = ctx.cwd.clone();
        // Parse and evaluate the expression
        let result = evaluate_expression(&args, &ctx.fs, &cwd, ctx.variables).await;

        if result {
            Ok(ExecResult::ok(String::new()))
        } else {
            Ok(ExecResult::err(String::new(), 1))
        }
    }
}

/// Resolve a file path against cwd (relative paths become absolute)
fn resolve_file_path(cwd: &Path, arg: &str) -> PathBuf {
    let p = Path::new(arg);
    if p.is_absolute() {
        p.to_path_buf()
    } else {
        cwd.join(p)
    }
}

/// Evaluate a test expression
fn evaluate_expression<'a>(
    args: &'a [String],
    fs: &'a Arc<dyn FileSystem>,
    cwd: &'a Path,
    variables: &'a HashMap<String, String>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>> {
    Box::pin(async move {
        if args.is_empty() {
            return false;
        }

        // Handle negation
        if args[0] == "!" {
            return !evaluate_expression(&args[1..], fs, cwd, variables).await;
        }

        // Handle parentheses (basic support)
        if args[0] == "(" && args.last().map(|s| s.as_str()) == Some(")") {
            return evaluate_expression(&args[1..args.len() - 1], fs, cwd, variables).await;
        }

        // Look for logical operators: -o has lowest precedence, then -a.
        // Scan for -o first (split at lowest precedence first).
        for (i, arg) in args.iter().enumerate() {
            if arg == "-o" && i > 0 {
                return evaluate_expression(&args[..i], fs, cwd, variables).await
                    || evaluate_expression(&args[i + 1..], fs, cwd, variables).await;
            }
        }
        for (i, arg) in args.iter().enumerate() {
            if arg == "-a" && i > 0 {
                return evaluate_expression(&args[..i], fs, cwd, variables).await
                    && evaluate_expression(&args[i + 1..], fs, cwd, variables).await;
            }
        }

        // Now handle binary comparisons and unary tests
        match args.len() {
            1 => {
                // Single arg: true if non-empty string
                !args[0].is_empty()
            }
            2 => {
                // Unary operators
                evaluate_unary(&args[0], &args[1], fs, cwd, variables).await
            }
            3 => {
                // Binary operators
                evaluate_binary(&args[0], &args[1], &args[2], fs, cwd).await
            }
            _ => false,
        }
    })
}

/// Evaluate a unary test expression
async fn evaluate_unary(
    op: &str,
    arg: &str,
    fs: &Arc<dyn FileSystem>,
    cwd: &Path,
    variables: &HashMap<String, String>,
) -> bool {
    match op {
        // String tests
        "-z" => arg.is_empty(),
        "-n" => !arg.is_empty(),

        // File tests using the virtual filesystem
        "-e" | "-a" => {
            // file exists
            let path = resolve_file_path(cwd, arg);
            fs.exists(&path).await.unwrap_or(false)
        }
        "-f" => {
            // regular file
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                meta.file_type.is_file()
            } else {
                false
            }
        }
        "-d" => {
            // directory
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                meta.file_type.is_dir()
            } else {
                false
            }
        }
        "-r" => {
            // readable - in virtual fs, check if file exists
            // (permissions are stored but not enforced)
            let path = resolve_file_path(cwd, arg);
            fs.exists(&path).await.unwrap_or(false)
        }
        "-w" => {
            // writable - in virtual fs, check if file exists
            let path = resolve_file_path(cwd, arg);
            fs.exists(&path).await.unwrap_or(false)
        }
        "-x" => {
            // executable - in virtual fs, check if file exists and has executable permission
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                // Check if any execute bit is set (u+x, g+x, o+x)
                (meta.mode & 0o111) != 0
            } else {
                false
            }
        }
        "-s" => {
            // file exists and has size > 0
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                meta.size > 0
            } else {
                false
            }
        }
        "-L" | "-h" => {
            // symbolic link
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                meta.file_type.is_symlink()
            } else {
                false
            }
        }
        "-p" => {
            // named pipe (FIFO)
            let path = resolve_file_path(cwd, arg);
            if let Ok(meta) = fs.stat(&path).await {
                meta.file_type.is_fifo()
            } else {
                false
            }
        }
        "-S" => false, // socket (not supported)
        "-b" => false, // block device (not supported)
        "-c" => false, // character device (not supported)
        "-t" => {
            // file descriptor refers to a terminal
            // In VFS sandbox, defaults to false for all FDs.
            // Configurable via _TTY_N variables (e.g. _TTY_0=1 for stdin).
            let fd_key = format!("_TTY_{}", arg);
            variables.get(&fd_key).map(|v| v == "1").unwrap_or(false)
        }

        _ => false,
    }
}

/// Evaluate a binary test expression
async fn evaluate_binary(
    left: &str,
    op: &str,
    right: &str,
    fs: &Arc<dyn FileSystem>,
    cwd: &Path,
) -> bool {
    match op {
        // String comparisons
        "=" | "==" => left == right,
        "!=" => left != right,
        "<" => left < right,
        ">" => left > right,

        // Numeric comparisons
        "-eq" => parse_int(left) == parse_int(right),
        "-ne" => parse_int(left) != parse_int(right),
        "-lt" => parse_int(left) < parse_int(right),
        "-le" => parse_int(left) <= parse_int(right),
        "-gt" => parse_int(left) > parse_int(right),
        "-ge" => parse_int(left) >= parse_int(right),

        // File comparisons
        "-nt" => {
            // file1 is newer than file2
            let left_meta = fs.stat(&resolve_file_path(cwd, left)).await;
            let right_meta = fs.stat(&resolve_file_path(cwd, right)).await;
            match (left_meta, right_meta) {
                (Ok(lm), Ok(rm)) => lm.modified > rm.modified,
                (Ok(_), Err(_)) => true, // left exists, right doesn't → left is newer
                _ => false,
            }
        }
        "-ot" => {
            // file1 is older than file2
            let left_meta = fs.stat(&resolve_file_path(cwd, left)).await;
            let right_meta = fs.stat(&resolve_file_path(cwd, right)).await;
            match (left_meta, right_meta) {
                (Ok(lm), Ok(rm)) => lm.modified < rm.modified,
                (Err(_), Ok(_)) => true, // left doesn't exist, right does → left is older
                _ => false,
            }
        }
        "-ef" => {
            // file1 and file2 refer to the same file (same path after resolution)
            // In VFS without inodes, compare canonical paths
            let left_path = super::resolve_path(cwd, left);
            let right_path = super::resolve_path(cwd, right);
            left_path == right_path
        }

        _ => false,
    }
}

fn parse_int(s: &str) -> i64 {
    s.trim().parse().unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::fs::{FileSystem, InMemoryFs};

    async fn setup() -> (Arc<InMemoryFs>, PathBuf, HashMap<String, String>) {
        let fs = Arc::new(InMemoryFs::new());
        let cwd = PathBuf::from("/home/user");
        let variables = HashMap::new();
        fs.mkdir(&cwd, true).await.unwrap();
        (fs, cwd, variables)
    }

    // ==================== test builtin ====================

    #[tokio::test]
    async fn test_empty_args_returns_false() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args: Vec<String> = vec![];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_nonempty_string_is_true() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["hello".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_z_empty_string() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-z".to_string(), "".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_z_nonempty_string() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-z".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_n_nonempty_string() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-n".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_n_empty_string() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-n".to_string(), "".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_string_equality() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["abc".to_string(), "=".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_string_inequality() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["abc".to_string(), "!=".to_string(), "def".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_string_equality_fails() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["abc".to_string(), "=".to_string(), "xyz".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_eq_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["42".to_string(), "-eq".to_string(), "42".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_eq_numeric_fails() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["42".to_string(), "-eq".to_string(), "99".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_lt_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["5".to_string(), "-lt".to_string(), "10".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_lt_numeric_fails() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["10".to_string(), "-lt".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_gt_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["10".to_string(), "-gt".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_e_file_exists() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/file.txt"), b"hello")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-e".to_string(), "file.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_e_file_not_exists() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-e".to_string(), "nope.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_f_regular_file() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/file.txt"), b"data")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-f".to_string(), "file.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_f_directory_is_not_file() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.mkdir(Path::new("/home/user/subdir"), true)
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-f".to_string(), "subdir".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_d_directory() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.mkdir(Path::new("/home/user/subdir"), true)
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-d".to_string(), "subdir".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_d_file_is_not_dir() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/file.txt"), b"data")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-d".to_string(), "file.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_negation() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["!".to_string(), "-z".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0); // ! -z "abc" => ! false => true
    }

    #[tokio::test]
    async fn test_negation_true_becomes_false() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["!".to_string(), "-n".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1); // ! -n "abc" => ! true => false
    }

    // ==================== bracket builtin ====================

    #[tokio::test]
    async fn bracket_missing_closing() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-z".to_string(), "".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("missing ]"));
    }

    #[tokio::test]
    async fn bracket_with_closing() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-z".to_string(), "".to_string(), "]".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn bracket_empty_expression() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["]".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1); // empty expression => false
    }

    #[tokio::test]
    async fn bracket_empty_args() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args: Vec<String> = vec![];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 2);
    }

    // ==================== additional numeric operators ====================

    #[tokio::test]
    async fn test_ne_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["1".to_string(), "-ne".to_string(), "2".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_ne_numeric_equal() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["5".to_string(), "-ne".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_le_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["5".to_string(), "-le".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_le_numeric_greater() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["10".to_string(), "-le".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_ge_numeric() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["5".to_string(), "-ge".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_ge_numeric_less() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["3".to_string(), "-ge".to_string(), "5".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    // ==================== string comparison operators ====================

    #[tokio::test]
    async fn test_double_eq_string() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["foo".to_string(), "==".to_string(), "foo".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_string_less_than() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["abc".to_string(), "<".to_string(), "def".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_string_greater_than() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["xyz".to_string(), ">".to_string(), "abc".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    // ==================== file tests: -s, -r, -w, -x ====================

    #[tokio::test]
    async fn test_s_file_has_size() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/nonempty.txt"), b"data")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-s".to_string(), "nonempty.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_s_empty_file() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/empty.txt"), b"")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-s".to_string(), "empty.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_r_readable_file() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/readable.txt"), b"x")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-r".to_string(), "readable.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_w_writable_file() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/home/user/writable.txt"), b"x")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-w".to_string(), "writable.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_r_nonexistent() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-r".to_string(), "nope".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
    }

    // ==================== absolute path handling ====================

    #[tokio::test]
    async fn test_e_absolute_path() {
        let (fs, mut cwd, mut variables) = setup().await;
        fs.write_file(Path::new("/tmp/abs.txt"), b"hi")
            .await
            .unwrap();
        let env = HashMap::new();
        let args = vec!["-e".to_string(), "/tmp/abs.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    // ==================== numeric parse edge cases ====================

    #[tokio::test]
    async fn test_eq_non_numeric_treated_as_zero() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        // Non-numeric values parse as 0
        let args = vec!["abc".to_string(), "-eq".to_string(), "0".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_negative_numbers() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec!["-5".to_string(), "-lt".to_string(), "0".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    // ==================== bracket with binary ops ====================

    #[tokio::test]
    async fn bracket_numeric_eq() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec![
            "3".to_string(),
            "-eq".to_string(),
            "3".to_string(),
            "]".to_string(),
        ];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    // ==================== operator precedence ====================

    #[tokio::test]
    async fn test_or_and_precedence() {
        // [ true -o false -a false ] should be true (-a binds tighter than -o)
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec![
            "1".to_string(),
            "-eq".to_string(),
            "1".to_string(),
            "-o".to_string(),
            "1".to_string(),
            "-eq".to_string(),
            "2".to_string(),
            "-a".to_string(),
            "1".to_string(),
            "-eq".to_string(),
            "2".to_string(),
        ];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Test.execute(ctx).await.unwrap();
        assert_eq!(
            result.exit_code, 0,
            "-a should have higher precedence than -o"
        );
    }

    #[tokio::test]
    async fn bracket_string_neq() {
        let (fs, mut cwd, mut variables) = setup().await;
        let env = HashMap::new();
        let args = vec![
            "a".to_string(),
            "!=".to_string(),
            "b".to_string(),
            "]".to_string(),
        ];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);
        let result = Bracket.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }
}