kaish-kernel 0.8.2

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
//! Kaish-specific shell behavior tests that don't translate to bash.
//!
//! Bash-portable scenarios live in `shell_compat_tests.rs` (which runs each
//! script through both kaish AND `bash -c` when `KAISH_BASH_COMPAT=1` is set,
//! catching divergences). This file is the home for behaviors that are
//! kaish-only by design or otherwise can't be directly compared:
//!
//! - `local x = inner` — kaish syntax with surrounding spaces; bash uses
//!   `local x=inner` and rejects the spaced form.
//! - `$$` / `${$}` — process IDs differ across processes, so kaish vs.
//!   `bash -c` can't agree on a value.
//! - Structured iteration: `split`, `seq` returning arrays.
//! - Stderr redirects (`>&2`, `1>&2`) — the compat harness only inspects
//!   stdout today.
//! - VFS-only paths (`/v/...`) and the `find` builtin's filtering through
//!   the parser.
//! - Short flags-with-value tests that depend on a real tempfile.
//! - Command-substitution cwd isolation, which depends on the host process's
//!   starting cwd (hard to make deterministic across two runners).

use kaish_kernel::Kernel;

// ============================================================================
// Within-kaish equivalence: $? braced vs unbraced
// ============================================================================

#[tokio::test]
async fn test_braced_vs_unbraced_exit_code_equivalence() {
    let kernel = Kernel::transient().unwrap();
    // Both forms should give the same result
    let result1 = kernel.execute("false; echo $?").await.unwrap();
    let result2 = kernel.execute("false; echo ${?}").await.unwrap();
    assert_eq!(
        result1.text_out().trim(),
        result2.text_out().trim(),
        "Braced and unbraced $? should be equivalent"
    );
}

// ============================================================================
// $$ / ${$} — kaish-internal session identifier (monotonic u64 counter)
//
// kaish exposes $$ as a per-Kernel counter, *not* the OS PID. Compat with
// bash via `bash -c` would always disagree (different processes), so these
// live here rather than in the compat suite. See
// memory/lang_dollar_dollar_identifier.md for the rationale.
// ============================================================================

#[tokio::test]
async fn test_pid_in_arithmetic() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel.execute("echo $(( $$ % 100000 ))").await.unwrap();
    let val: i64 = result.text_out().trim().parse().expect("Should be a number");
    assert!(val >= 0, "PID mod should be non-negative");
}

#[tokio::test]
async fn test_braced_current_pid() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel.execute("echo ${$}").await.unwrap();
    let pid: u64 = result
        .text_out()
        .trim()
        .parse()
        .expect("${$} should be a number");
    assert!(pid > 0, "PID should be positive: {}", pid);
}

#[tokio::test]
async fn test_braced_vs_unbraced_pid_equivalence() {
    let kernel = Kernel::transient().unwrap();
    let result1 = kernel.execute("echo $$").await.unwrap();
    let result2 = kernel.execute("echo ${$}").await.unwrap();
    assert_eq!(
        result1.text_out().trim(),
        result2.text_out().trim(),
        "Braced and unbraced $$ should be equivalent"
    );
}

#[tokio::test]
async fn test_two_kernels_have_distinct_pids() {
    // Each Kernel construction takes the next counter value, so two
    // kernels created in the same test run must report different $$.
    let k1 = Kernel::transient().unwrap();
    let k2 = Kernel::transient().unwrap();
    let p1 = k1.execute("echo $$").await.unwrap().text_out().trim().to_string();
    let p2 = k2.execute("echo $$").await.unwrap().text_out().trim().to_string();
    assert_ne!(p1, p2, "two kernels should have different $$, got {p1} and {p2}");
}

#[tokio::test]
async fn test_fork_inherits_parent_pid() {
    // A forked subkernel must share its parent's $$ — matches bash's
    // "subshell keeps parent's $$" semantics.
    let parent = Kernel::transient().unwrap();
    let parent_pid = parent
        .execute("echo $$")
        .await
        .unwrap()
        .text_out()
        .trim()
        .to_string();
    let fork = parent.fork().await;
    let fork_pid = fork
        .execute("echo $$")
        .await
        .unwrap()
        .text_out()
        .trim()
        .to_string();
    assert_eq!(parent_pid, fork_pid, "fork should inherit parent $$");
}

#[tokio::test]
async fn test_kaish_clear_preserves_pid() {
    // kaish-clear resets variables/cwd but the kernel hasn't restarted —
    // $$ should be the same identifier before and after.
    let kernel = Kernel::transient().unwrap();
    let before = kernel.execute("echo $$").await.unwrap().text_out().trim().to_string();
    kernel.execute("kaish-clear").await.unwrap();
    let after = kernel.execute("echo $$").await.unwrap().text_out().trim().to_string();
    assert_eq!(before, after, "kaish-clear should preserve $$");
}

// ============================================================================
// `local x = value` — kaish syntax with surrounding spaces (bash uses `x=v`)
// ============================================================================

#[tokio::test]
async fn test_local_variable_scoping() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
x=outer
f() {
    local x = inner
    echo "in func: $x"
}
f
echo "after func: $x"
"#,
        )
        .await
        .unwrap();
    assert!(
        result.text_out().contains("in func: inner"),
        "Local var should be 'inner' inside function: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("after func: outer"),
        "Outer var should be 'outer' after function: {}",
        result.text_out()
    );
}

#[tokio::test]
async fn test_local_does_not_affect_outer_scope() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
count=0
increment() {
    local count = 99
}
increment
echo $count
"#,
        )
        .await
        .unwrap();
    assert_eq!(
        result.text_out().trim(),
        "0",
        "Outer 'count' should still be 0: {}",
        result.text_out()
    );
}

#[tokio::test]
async fn test_non_local_modifies_outer_scope() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
count=0
increment() {
    count=99
}
increment
echo $count
"#,
        )
        .await
        .unwrap();
    assert_eq!(
        result.text_out().trim(),
        "99",
        "Without local, 'count' should be modified: {}",
        result.text_out()
    );
}

#[tokio::test]
async fn test_local_with_command_substitution() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
val=original
f() {
    local val = $(echo "from_cmd")
    echo "local: $val"
}
f
echo "outer: $val"
"#,
        )
        .await
        .unwrap();
    assert!(
        result.text_out().contains("local: from_cmd"),
        "Local with cmd subst: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("outer: original"),
        "Outer unchanged: {}",
        result.text_out()
    );
}

#[tokio::test]
async fn test_positional_params_arithmetic_with_variable() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
calc() {
    local base = 10
    echo $(($base + $1))
}
calc 5
"#,
        )
        .await
        .unwrap();
    assert_eq!(
        result.text_out().trim(),
        "15",
        "$(($base + $1)) with base=10 and $1=5 should be 15: {}",
        result.text_out()
    );
}

// ============================================================================
// Structured iteration: kaish split / seq return arrays (no implicit splitting)
// ============================================================================

#[tokio::test]
async fn test_command_subst_with_explicit_split() {
    // Use split for explicit word splitting
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
for x in $(split "a b c"); do
    echo "item: $x"
done
"#,
        )
        .await
        .unwrap();
    assert!(
        result.text_out().contains("item: a"),
        "Should have item a: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("item: b"),
        "Should have item b: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("item: c"),
        "Should have item c: {}",
        result.text_out()
    );
}

#[tokio::test]
async fn test_for_loop_with_seq_returns_array() {
    // seq returns a JSON array, which iterates properly
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(
            r#"
for num in $(seq 1 3); do
    echo "number $num"
done
"#,
        )
        .await
        .unwrap();
    assert!(
        result.text_out().contains("number 1"),
        "Should have number 1: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("number 2"),
        "Should have number 2: {}",
        result.text_out()
    );
    assert!(
        result.text_out().contains("number 3"),
        "Should have number 3: {}",
        result.text_out()
    );
}

// ============================================================================
// Stderr redirects: 1>&2 and >&2 — compat harness only inspects stdout today
// ============================================================================

#[tokio::test]
async fn test_stdout_to_stderr_redirect_1_ampersand_2() {
    let kernel = Kernel::transient().unwrap();
    // This should parse and execute without error
    let result = kernel.execute("echo error 1>&2").await.unwrap();
    // Output should go to stderr, not stdout
    assert!(
        result.err.contains("error"),
        "Expected 'error' in stderr: stdout={}, stderr={}",
        result.text_out(),
        result.err
    );
}

#[tokio::test]
async fn test_stdout_to_stderr_redirect_ampersand_2() {
    let kernel = Kernel::transient().unwrap();
    // Shorthand form: >&2 is equivalent to 1>&2
    let result = kernel.execute("echo warning >&2").await.unwrap();
    assert!(
        result.err.contains("warning"),
        "Expected 'warning' in stderr: stdout={}, stderr={}",
        result.text_out(),
        result.err
    );
}

// ============================================================================
// VFS file tests — [[ -d / -f / -e ]] against `/v/...` paths
// ============================================================================

#[tokio::test]
async fn test_file_test_sees_vfs_dirs() {
    let kernel = Kernel::transient().unwrap();
    kernel.execute("mkdir -p /v/testdir").await.unwrap();
    let result = kernel.execute(r#"[[ -d /v/testdir ]] && echo "found" || echo "missing""#).await.unwrap();
    assert_eq!(result.text_out().trim(), "found", "[[ -d ]] should see VFS dirs: {}", result.text_out());
}

#[tokio::test]
async fn test_file_test_sees_vfs_files() {
    let kernel = Kernel::transient().unwrap();
    kernel.execute("write /v/testfile 'hello'").await.unwrap();
    let result = kernel.execute(r#"[[ -f /v/testfile ]] && echo "found" || echo "missing""#).await.unwrap();
    assert_eq!(result.text_out().trim(), "found", "[[ -f ]] should see VFS files: {}", result.text_out());
}

#[tokio::test]
async fn test_file_test_exists_vfs() {
    let kernel = Kernel::transient().unwrap();
    kernel.execute("write /v/somefile 'data'").await.unwrap();
    let result = kernel.execute(r#"[[ -e /v/somefile ]] && echo "found" || echo "missing""#).await.unwrap();
    assert_eq!(result.text_out().trim(), "found", "[[ -e ]] should see VFS entries: {}", result.text_out());
}

// ============================================================================
// Short flags with values (head -n N, tail -n N) — depend on a real tempfile
// ============================================================================

#[tokio::test]
async fn test_short_flag_with_value_head() {
    let kernel = Kernel::transient().unwrap();
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let path = tmp.path().display();
    kernel.execute(&format!(r#"printf "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" > {path}"#)).await.unwrap();

    // head -n 3 should return first 3 lines
    let result = kernel.execute(&format!("head -n 3 {path}")).await.unwrap();
    assert!(result.ok(), "head -n 3 should succeed: err={}", result.err);
    let text = result.text_out();
    let lines: Vec<&str> = text.trim().lines().collect();
    assert_eq!(lines, vec!["1", "2", "3"], "head -n 3 should return first 3 lines, got: {:?}", lines);
}

#[tokio::test]
async fn test_short_flag_with_value_tail() {
    let kernel = Kernel::transient().unwrap();
    let tmp = tempfile::NamedTempFile::new().unwrap();
    let path = tmp.path().display();
    kernel.execute(&format!(r#"printf "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" > {path}"#)).await.unwrap();

    // tail -n 3 should return last 3 lines
    let result = kernel.execute(&format!("tail -n 3 {path}")).await.unwrap();
    assert!(result.ok(), "tail -n 3 should succeed: err={}", result.err);
    let text = result.text_out();
    let lines: Vec<&str> = text.trim().lines().collect();
    assert_eq!(lines, vec!["8", "9", "10"], "tail -n 3 should return last 3 lines, got: {:?}", lines);
}

// ============================================================================
// Command-substitution cwd isolation — depends on host process cwd
// ============================================================================

#[tokio::test]
async fn test_cmd_subst_cwd_isolation() {
    let kernel = Kernel::transient().unwrap();
    // Define a function that changes cwd and prints it.
    // The captured output should be "/" but pwd after should be the original cwd.
    let result = kernel
        .execute(
            r#"
go_root() { cd /; pwd; }
X=$(go_root)
pwd
"#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "Should succeed: err={}", result.err);
    // pwd should NOT be "/", it should be the original working dir
    let text = result.text_out();
    let pwd_output = text.trim();
    assert_ne!(
        pwd_output, "/",
        "CWD should not leak from command substitution, got: {}",
        pwd_output
    );
}

#[tokio::test]
async fn test_cmd_subst_in_string_cwd_isolation() {
    let kernel = Kernel::transient().unwrap();
    // Command substitution in string interpolation should also be isolated
    let result = kernel
        .execute(
            r#"
go_root() { cd /; pwd; }
echo "dir: $(go_root)"
pwd
"#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "Should succeed: err={}", result.err);
    let text = result.text_out();
    let lines: Vec<&str> = text.trim().lines().collect();
    assert!(lines.len() >= 2, "Expected at least 2 lines: {:?}", lines);
    assert!(
        lines[0].contains("dir: /"),
        "Captured output should contain '/': {}",
        lines[0]
    );
    // The second line (pwd) should NOT be "/"
    assert_ne!(
        lines[1], "/",
        "CWD should not leak from string command substitution: {}",
        lines[1]
    );
}

#[tokio::test]
async fn test_cmd_subst_captures_output_correctly() {
    let kernel = Kernel::transient().unwrap();
    // Ensure the captured value is still correct despite isolation
    let result = kernel
        .execute(
            r#"
go_root() { cd /; pwd; }
X=$(go_root)
echo "captured: $X"
"#,
        )
        .await
        .unwrap();
    assert!(result.ok(), "Should succeed: err={}", result.err);
    assert!(
        result.text_out().contains("captured: /"),
        "Should capture '/' from subshell: {}",
        result.text_out()
    );
}

// ============================================================================
// find through the parser — VFS-only paths
// ============================================================================

#[tokio::test]
async fn test_find_name_filter_through_parser() {
    let kernel = Kernel::transient().unwrap();

    // Set up test files in /v/ (ephemeral memory VFS)
    kernel
        .execute("mkdir -p /v/proj/src; mkdir -p /v/proj/docs")
        .await
        .unwrap();
    kernel
        .execute(
            "write /v/proj/src/main.rs 'fn main() {}'; \
             write /v/proj/src/lib.rs 'pub mod lib;'; \
             write /v/proj/docs/README.md '# Docs'; \
             write /v/proj/Cargo.toml '[package]'",
        )
        .await
        .unwrap();

    // find with -name should only return .rs files
    let result = kernel
        .execute("find /v/proj -name '*.rs'")
        .await
        .unwrap();
    assert!(result.ok(), "find should succeed: {}", result.err);

    let out = result.text_out();
    assert!(out.contains("main.rs"), "should find main.rs: {out}");
    assert!(out.contains("lib.rs"), "should find lib.rs: {out}");
    assert!(
        !out.contains("README.md"),
        "-name '*.rs' should exclude README.md: {out}"
    );
    assert!(
        !out.contains("Cargo.toml"),
        "-name '*.rs' should exclude Cargo.toml: {out}"
    );
}

#[tokio::test]
async fn test_find_type_filter_through_parser() {
    let kernel = Kernel::transient().unwrap();

    kernel
        .execute("mkdir -p /v/proj/src; write /v/proj/src/main.rs 'fn main() {}'")
        .await
        .unwrap();

    // -type f: files only, no directories
    let files_result = kernel
        .execute("find /v/proj -type f")
        .await
        .unwrap();
    assert!(files_result.ok(), "find -type f should succeed: {}", files_result.err);
    let files_out = files_result.text_out();
    assert!(
        files_out.contains("main.rs"),
        "-type f should include files: {files_out}"
    );
    assert!(
        !files_out.contains("/src\n"),
        "-type f should exclude directories: {files_out}"
    );

    // -type d: directories only, no files
    let dirs_result = kernel
        .execute("find /v/proj -type d")
        .await
        .unwrap();
    assert!(dirs_result.ok(), "find -type d should succeed: {}", dirs_result.err);
    let dirs_out = dirs_result.text_out();
    assert!(
        dirs_out.contains("src"),
        "-type d should include directories: {dirs_out}"
    );
    assert!(
        !dirs_out.contains("main.rs"),
        "-type d should exclude files: {dirs_out}"
    );
}

// ============================================================================
// Bareword argv tokens: digit-leading and dot-prefixed strings
//
// These forms are common in real-world argv: SHA prefixes (`019dda1c`),
// hidden files (`.gitignore`), and context refs (`.parent`, `.parent.parent`).
// The lexer must produce a single bareword token for each so they aren't
// rejected (digit-leading) or misparsed as the POSIX `.` source alias
// (dot-prefixed).
// ============================================================================

#[tokio::test]
async fn test_argv_digit_leading_hex_passes_through() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(r#"echo 019dda1c "msg""#)
        .await
        .expect("parse + exec should succeed for digit-leading bareword");
    assert!(result.ok(), "echo failed: err={}", result.err);
    assert_eq!(result.text_out().trim(), "019dda1c msg");
}

#[tokio::test]
async fn test_argv_digit_leading_uuid_passes_through() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute("echo 019dda1c-5b3f-7000-abcd-0123456789ab")
        .await
        .expect("UUID-like bareword should lex");
    assert!(result.ok(), "echo failed: err={}", result.err);
    assert_eq!(
        result.text_out().trim(),
        "019dda1c-5b3f-7000-abcd-0123456789ab"
    );
}

#[tokio::test]
async fn test_argv_dot_prefixed_simple() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute(r#"echo .parent "msg""#)
        .await
        .expect("dot-prefixed bareword should lex");
    assert!(result.ok(), "echo failed: err={}", result.err);
    assert_eq!(result.text_out().trim(), ".parent msg");
}

#[tokio::test]
async fn test_argv_dot_prefixed_chained() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute("echo .parent.parent")
        .await
        .expect("chained .parent.parent should lex as one token");
    assert!(result.ok(), "echo failed: err={}", result.err);
    assert_eq!(result.text_out().trim(), ".parent.parent");
}

#[tokio::test]
async fn test_argv_dot_prefixed_hidden_file() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel
        .execute("echo .gitignore")
        .await
        .expect("hidden filename should not be parsed as source command");
    assert!(result.ok(), "echo failed: err={}", result.err);
    assert_eq!(result.text_out().trim(), ".gitignore");
}

// `. file` (with whitespace) must still be the source alias — POSIX behavior.
#[tokio::test]
async fn test_source_alias_with_space_still_works() {
    let kernel = Kernel::transient().unwrap();
    // Trying to source a non-existent file should hit the source builtin's
    // missing-file error, not silently succeed.
    let result = kernel
        .execute(". /nonexistent-kaish-source-test")
        .await
        .expect("`. file` should still be parsed as source command");
    assert!(
        !result.ok(),
        "source of nonexistent file should fail (proves source ran)"
    );
    assert!(
        result.err.contains("source") || result.err.contains("not found")
            || result.err.contains("No such file"),
        "expected source error, got: stdout={}, stderr={}",
        result.text_out(),
        result.err,
    );
}

// ============================================================================
// `!` precedence in `[[ ]]` — `!` binds tighter than `&&`/`||`
//
// Regression for the 2026-06-09 finding: the parser bound `!` to the entire
// rest of the expression (`!(A || B)`) instead of just the next term
// (`(!A) || B`), contradicting both LANGUAGE.md and the grammar comment in
// `parser.rs`. String tests keep these filesystem-independent.
// ============================================================================

/// Run `[[ <expr> ]]` and return true iff it evaluates true (if-branch taken).
async fn test_truthy(expr: &str) -> bool {
    let kernel = Kernel::transient().unwrap();
    let script = format!("if [[ {expr} ]]; then echo Y; else echo N; fi");
    let out = kernel.execute(&script).await.unwrap();
    match out.text_out().trim() {
        "Y" => true,
        "N" => false,
        other => panic!("unexpected output {other:?} for [[ {expr} ]]"),
    }
}

#[tokio::test]
async fn test_bang_binds_tighter_than_or() {
    // (!false) || true  == true.  Buggy `!(false || true)` == false.
    assert!(
        test_truthy(r#"! "a" == "b" || "a" == "a""#).await,
        "`! A || B` must parse as `(!A) || B`"
    );
    // (!true) || true == true.  Buggy `!(true || true)` == false.
    assert!(
        test_truthy(r#"! "a" == "a" || "b" == "b""#).await,
        "`! A || B` with A true must still be `(!A) || B`"
    );
}

#[tokio::test]
async fn test_bang_binds_tighter_than_and() {
    // (!true) && true == false.
    assert!(
        !test_truthy(r#"! "a" == "a" && "b" == "b""#).await,
        "`! A && B` must parse as `(!A) && B`"
    );
    // (!false) && true == true.
    assert!(
        test_truthy(r#"! "a" == "b" && "b" == "b""#).await,
        "`! A && B` with A false is `(!A) && B` == true"
    );
}

#[tokio::test]
async fn test_bang_single_term_unaffected() {
    assert!(test_truthy(r#"! "a" == "b""#).await, "!(a==b) is true");
    assert!(!test_truthy(r#"! "a" == "a""#).await, "!(a==a) is false");
    // Double negation still chains at the unary level.
    assert!(test_truthy(r#"! ! "a" == "a""#).await, "!!(a==a) is true");
}

// ============================================================================
// `--` end-of-flags protects dash-words with internal hyphens.
//
// `-not-a-flag` is one shell word; it used to fragment into three flag tokens
// (`-not` `-a` `-flag`) at the lexer, so `echo -- -not-a-flag` printed
// `-not -a -flag`. kaish consumes the `--` terminator (a deliberate divergence
// from bash's echo, which keeps it), so this is kaish-specific.
// ============================================================================

#[tokio::test]
async fn test_double_dash_protects_internal_hyphen_word() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel.execute("echo -- -not-a-flag").await.unwrap();
    assert_eq!(result.text_out().trim(), "-not-a-flag");
}

#[tokio::test]
async fn test_double_dash_protects_multiple_dash_words() {
    let kernel = Kernel::transient().unwrap();
    let result = kernel.execute("echo -- -a-b -c-d").await.unwrap();
    assert_eq!(result.text_out().trim(), "-a-b -c-d");
}