cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
//! Integration tests for task and exec commands

// Integration tests can use unwrap/expect for cleaner assertions
#![allow(
    clippy::print_stderr,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic
)]

use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Create a Command with a clean environment (no CI vars leaking).
fn clean_environment_command(bin: impl AsRef<OsStr>) -> Command {
    let mut cmd = Command::new(bin);
    cmd.env_clear()
        .env("PATH", std::env::var("PATH").unwrap_or_default())
        .env("HOME", std::env::var("HOME").unwrap_or_default())
        .env("USER", std::env::var("USER").unwrap_or_default());
    cmd
}

/// Create a test directory with proper prefix (non-hidden) for CUE loader compatibility.
///
/// CUE's `load.Instances` ignores directories starting with `.` (hidden directories).
/// The default `TempDir::new()` creates hidden directories like `.tmpXXXXX`, which causes
/// CUE evaluation to fail with "No instances could be evaluated".
fn create_test_dir() -> TempDir {
    tempfile::Builder::new()
        .prefix("cuenv_test_")
        .tempdir()
        .expect("Failed to create temp directory")
}

/// Initialize a CUE module in the given directory.
fn init_cue_module(dir: &Path) {
    fs::create_dir_all(dir.join("cue.mod")).unwrap();
    fs::write(
        dir.join("cue.mod/module.cue"),
        r#"module: "test.example/test"
language: version: "v0.9.0"
"#,
    )
    .unwrap();
}

/// Find a binary by name in the current PATH, returning its absolute path.
/// This avoids hardcoding paths like `/usr/bin/printenv` which don't exist in Nix sandboxes.
fn find_in_path(name: &str) -> String {
    let path_var = std::env::var("PATH").unwrap_or_default();
    for dir in path_var.split(':') {
        let candidate = std::path::PathBuf::from(dir).join(name);
        if candidate.is_file() {
            return candidate.to_string_lossy().to_string();
        }
    }
    panic!("Could not find `{name}` in PATH");
}

/// Helper to run cuenv command and capture output
fn run_cuenv(args: &[&str]) -> (String, String, bool) {
    let cuenv_bin = env!("CARGO_BIN_EXE_cuenv");
    let output = clean_environment_command(cuenv_bin)
        .args(args)
        .output()
        .expect("Failed to run cuenv");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let success = output.status.success();

    (stdout, stderr, success)
}

#[test]
fn test_task_list_with_shorthand() {
    // Create a temporary directory with test CUE files
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    TEST_VAR: "test_value"
}

tasks: {
    test_task: {
        command: "echo"
        args: ["test"]
    }
    another_task: {
        command: "echo"
        args: ["another"]
    }
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test listing tasks with 't' shorthand
    let (stdout, _stderr, success) = run_cuenv(&[
        "t",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
    ]);

    assert!(success, "Command should succeed");
    assert!(stdout.contains("Tasks:"), "Should show tasks header");
    assert!(stdout.contains("test_task"), "Should list test_task");
    assert!(stdout.contains("another_task"), "Should list another_task");
}

#[test]
fn test_task_execution() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    GREETING: "Hello"
    NAME: "World"
}

tasks: {
    greet: {
        command: "echo"
        args: ["Hello from task"]
    }
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test running a task with 'task' command
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "greet",
    ]);

    assert!(success, "Command should succeed");
    assert!(
        stdout.contains("Hello from task"),
        "Should execute the task"
    );
    assert!(
        stdout.contains("Task 'greet' succeeded"),
        "Should show completion message"
    );
}

#[test]
fn test_task_with_environment_propagation() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    TEST_ENV_VAR: "propagated_value"
}

tasks: {
    check_env: {
        command: "printenv"
        args: ["TEST_ENV_VAR"]
    }
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test that environment variables are propagated to tasks
    let (stdout, _, success) = run_cuenv(&[
        "t", // Using shorthand
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "check_env",
    ]);

    assert!(success, "Command should succeed");
    assert!(
        stdout.contains("propagated_value"),
        "Environment variable should be propagated"
    );
}

#[test]
fn test_exec_command_with_shorthand() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    EXEC_TEST: "exec_value"
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test exec with 'x' shorthand (changed from 'e' to avoid conflict with -e global flag)
    let (stdout, _, success) = run_cuenv(&[
        "x",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "printenv",
        "EXEC_TEST",
    ]);

    assert!(success, "Command should succeed");
    assert!(
        stdout.contains("exec_value"),
        "Environment variable should be available to exec command"
    );
}

#[test]
fn test_exec_with_arguments() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    PREFIX: "Test"
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test exec with multiple arguments
    let (stdout, _, success) = run_cuenv(&[
        "exec",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "echo",
        "arg1",
        "arg2",
        "arg3",
    ]);

    assert!(success, "Command should succeed");
    assert!(
        stdout.contains("arg1 arg2 arg3"),
        "All arguments should be passed"
    );
}

#[test]
fn test_task_sequential_list() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {
    COUNTER: "0"
}

tasks: {
    sequence: [
        {
            command: "echo"
            args: ["First"]
        },
        {
            command: "echo"
            args: ["Second"]
        },
        {
            command: "echo"
            args: ["Third"]
        }
    ]
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test running a sequential task list
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "sequence",
    ]);

    assert!(success, "Command should succeed");
    // Check that all tasks ran in sequence
    assert!(stdout.contains("First"), "First task should run");
    assert!(stdout.contains("Second"), "Second task should run");
    assert!(stdout.contains("Third"), "Third task should run");

    // Verify order by checking positions
    let first_pos = stdout.find("First").unwrap();
    let second_pos = stdout.find("Second").unwrap();
    let third_pos = stdout.find("Third").unwrap();
    assert!(first_pos < second_pos, "First should come before Second");
    assert!(second_pos < third_pos, "Second should come before Third");
}

#[test]
fn test_task_nested_groups() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {}

tasks: {
    nested: {
        type: "group"
        subtask1: {
            command: "echo"
            args: ["Subtask 1"]
        }
        subtask2: {
            command: "echo"
            args: ["Subtask 2"]
        }
    }
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test running nested task groups
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "nested",
    ]);

    assert!(success, "Command should succeed");
    assert!(
        stdout.contains("Subtask 1") || stdout.contains("Subtask 2"),
        "At least one subtask should run"
    );
}

#[test]
fn test_nested_task_paths_and_aliases() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {}

let _t = tasks

tasks: {
    bun: {
        type: "group"
        install: {
            command: "echo"
            args: ["bun install"]
        }
        test: {
            command: "echo"
            args: ["bun test"]
            dependsOn: [_t.bun.install]
        }
    }
}
"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Listing should include canonical dotted paths
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
    ]);
    assert!(success, "Listing nested tasks should succeed");
    assert!(stdout.contains("bun"), "Should list parent group");
    assert!(
        stdout.contains("install"),
        "Should list nested task install"
    );
    // Tree view doesn't show full dotted path "bun.install"
    // assert!(
    //     stdout.contains("bun.install"),
    //     "Should list nested task with dotted name"
    // );

    // Execute using dotted path
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "bun.install",
    ]);
    assert!(success, "Should run nested task via dotted syntax");
    assert!(stdout.contains("bun install"));

    // Execute using colon alias
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "bun:install",
    ]);
    assert!(success, "Should run nested task via colon syntax");
    assert!(stdout.contains("bun install"));

    // Dependency should resolve to canonical nested name
    let (stdout, _, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "bun.test",
    ]);
    assert!(success, "Dependent nested task should run");
    assert!(
        stdout.contains("bun install"),
        "Dependency should execute using canonical path"
    );
    assert!(stdout.contains("bun test"));
}

#[test]
fn test_nonexistent_task_error() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r#"package test

name: "test"

env: {}

tasks: {
    existing: {
        command: "echo"
        args: ["test"]
    }
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test running a nonexistent task
    let (_, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "nonexistent",
    ]);

    assert!(!success, "Command should fail");
    assert!(
        stderr.contains("not found") || stderr.contains("Task execution failed"),
        "Should report task not found"
    );
}

#[test]
fn test_exec_command_exit_code() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    let cue_content = r"package test

env: {}";

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Test that exec propagates exit codes correctly
    let (_, _, success) = run_cuenv(&[
        "exec",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "false", // Command that always fails
    ]);

    assert!(!success, "Command should fail when executed command fails");
}

#[cfg(test)]
mod testexamples {
    use super::*;

    #[test]
    fn test_task_basic_example() {
        // Get the project root
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let project_root = Path::new(manifest_dir).parent().unwrap().parent().unwrap();
        let example_path = project_root.join("examples/task-basic");

        // Skip if example doesn't exist
        if !example_path.exists() {
            eprintln!("Skipping test - example path doesn't exist: {example_path:?}");
            return;
        }

        // Test listing tasks
        let (stdout, _, success) = run_cuenv(&[
            "t",
            "-p",
            example_path.to_str().unwrap(),
            "--package",
            "examples",
        ]);

        assert!(success, "Should list tasks successfully");
        assert!(
            stdout.contains("interpolate"),
            "Should list interpolate task"
        );
        assert!(stdout.contains("propagate"), "Should list propagate task");
        assert!(stdout.contains("greetAll"), "Should list greetAll task");

        // Test running interpolate task
        let (stdout, _, success) = run_cuenv(&[
            "t",
            "-p",
            example_path.to_str().unwrap(),
            "--package",
            "examples",
            "interpolate",
        ]);

        assert!(success, "Should run interpolate task");
        assert!(
            stdout.contains("Jack O'Neill"),
            "Should interpolate environment variable"
        );

        // Test running propagate task
        let (stdout, _, success) = run_cuenv(&[
            "t",
            "-p",
            example_path.to_str().unwrap(),
            "--package",
            "examples",
            "propagate",
        ]);

        assert!(success, "Should run propagate task");
        assert!(
            stdout.contains("Jack O'Neill"),
            "Should propagate environment variable"
        );

        // Test exec with example environment (using 'x' shorthand)
        let (stdout, _, success) = run_cuenv(&[
            "x",
            "-p",
            example_path.to_str().unwrap(),
            "--package",
            "examples",
            "printenv",
            "NAME",
        ]);

        assert!(success, "Should run exec command");
        assert!(
            stdout.contains("Jack O'Neill"),
            "Should have environment variable available"
        );
    }

    #[test]
    fn test_complex_task_dependency_chain() {
        let temp_dir = create_test_dir();
        init_cue_module(temp_dir.path());
        let cue_content = r#"package test

name: "test"

env: {
    COUNTER: "0"
}

let _t = tasks

tasks: {
    init: {
        command: "echo"
        args: ["Initializing..."]
    }

    build: {
        command: "echo"
        args: ["Building after init"]
        dependsOn: [_t.init]
    }

    test: {
        command: "echo"
        args: ["Testing after build"]
        dependsOn: [_t.build]
    }

    deploy: {
        command: "echo"
        args: ["Deploying after test"]
        dependsOn: [_t.test]
    }
}"#;

        fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

        // Test running the final task should execute all dependencies
        let (stdout, stderr, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "deploy",
        ]);

        assert!(
            success,
            "Command should succeed, stdout: {stdout}, stderr: {stderr}"
        );
        assert!(
            stdout.contains("Initializing"),
            "Init task should run, stdout: {stdout}"
        );
        assert!(stdout.contains("Building"), "Build task should run");
        assert!(stdout.contains("Testing"), "Test task should run");
        assert!(stdout.contains("Deploying"), "Deploy task should run");

        // Verify execution order
        let init_pos = stdout.find("Initializing").unwrap();
        let build_pos = stdout.find("Building").unwrap();
        let test_pos = stdout.find("Testing").unwrap();
        let deploy_pos = stdout.find("Deploying").unwrap();

        assert!(init_pos < build_pos, "Init should run before build");
        assert!(build_pos < test_pos, "Build should run before test");
        assert!(test_pos < deploy_pos, "Test should run before deploy");
    }

    #[test]
    fn test_task_failure_handling() {
        let temp_dir = create_test_dir();
        init_cue_module(temp_dir.path());
        let cue_content = r#"package test

name: "test"

env: {}

tasks: {
    failing_task: {
        command: "false"  // Command that always fails
        args: []
    }
}"#;

        fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

        // Test that task failure is properly handled
        let (_, stderr, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "failing_task",
        ]);

        assert!(!success, "Command should fail");
        assert!(
            stderr.contains("failed") || stderr.contains("error"),
            "Should report failure"
        );
    }

    #[test]
    fn test_mixed_task_types() {
        let temp_dir = create_test_dir();
        init_cue_module(temp_dir.path());
        let cue_content = r#"package test

name: "test"

env: {
    PREFIX: "MIX"
}

tasks: {
    single_task: {
        command: "echo"
        args: [env.PREFIX, "single"]
    }

    sequential_tasks: [
        {
            command: "echo"
            args: [env.PREFIX, "seq1"]
        },
        {
            command: "echo"
            args: [env.PREFIX, "seq2"]
        }
    ]

    parallel_tasks: {
        type: "group"
        par1: {
            command: "echo"
            args: [env.PREFIX, "par1"]
        }
        par2: {
            command: "echo"
            args: [env.PREFIX, "par2"]
        }
    }
}"#;

        fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

        // Test single task
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "single_task",
        ]);
        assert!(success);
        assert!(stdout.contains("MIX single"));

        // Test sequential tasks
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "sequential_tasks",
        ]);
        assert!(success);
        assert!(stdout.contains("MIX seq1"));
        assert!(stdout.contains("MIX seq2"));

        // Test parallel tasks
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "parallel_tasks",
        ]);
        assert!(success);
        // Both parallel tasks should execute
        assert!(stdout.contains("MIX par1") || stdout.contains("MIX par2"));
    }

    #[test]
    fn test_special_characters_in_environment() {
        let temp_dir = create_test_dir();
        init_cue_module(temp_dir.path());
        let cue_content = r#"package test

name: "test"

env: {
    SPECIAL_CHARS: "Hello $USER & $(whoami) | `date` > /dev/null"
    QUOTES: "He said \"Hello world\" and 'goodbye'"
    SPACES: "Value with spaces"
}

tasks: {
    test_special: {
        command: "printenv"
        args: ["SPECIAL_CHARS"]
    }

    test_quotes: {
        command: "printenv"
        args: ["QUOTES"]
    }

    test_spaces: {
        command: "printenv"
        args: ["SPACES"]
    }
}"#;

        fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

        // Test special characters are passed literally
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "test_special",
        ]);
        assert!(success);
        assert!(stdout.contains("Hello $USER & $(whoami)"));

        // Test quotes are preserved
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "test_quotes",
        ]);
        assert!(success);
        assert!(stdout.contains("\"Hello world\""));

        // Test spaces work correctly
        let (stdout, _, success) = run_cuenv(&[
            "task",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "test_spaces",
        ]);
        assert!(success);
        assert!(stdout.contains("Value with spaces"));
    }

    #[test]
    fn test_exec_with_complex_args() {
        let temp_dir = create_test_dir();
        init_cue_module(temp_dir.path());
        let cue_content = r#"package test

name: "test"

env: {
    TEST_VAR: "test_value"
}"#;

        fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

        // Test exec with arguments containing special characters
        let (stdout, _, success) = run_cuenv(&[
            "exec",
            "-p",
            temp_dir.path().to_str().unwrap(),
            "--package",
            "test",
            "echo",
            "arg with spaces",
            "arg\"with\"quotes",
            "arg'with'single'quotes",
            "$TEST_VAR",
            "$(echo 'command substitution')",
        ]);

        assert!(success, "Command should succeed");
        // All arguments should be treated literally
        assert!(stdout.contains("arg with spaces"));
        assert!(stdout.contains("arg\"with\"quotes"));
        assert!(stdout.contains("arg'with'single'quotes"));
        assert!(stdout.contains("$TEST_VAR"));
        assert!(stdout.contains("$(echo 'command substitution')"));
    }
}

#[test]
fn test_task_label_execution_is_path_scoped() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());

    // All projects must use `package cuenv` - this is enforced by cuenv
    let project_a = temp_dir.path().join("project-a");
    fs::create_dir_all(&project_a).unwrap();
    fs::write(
        project_a.join("env.cue"),
        r#"package cuenv

name: "project-a"

env: {}

tasks: {
  projen: {
    command: "sh"
    args: ["-c", "echo A-PROJEN"]
    labels: ["projen"]
  }
}
"#,
    )
    .unwrap();

    let project_b = temp_dir.path().join("project-b");
    fs::create_dir_all(&project_b).unwrap();
    fs::write(
        project_b.join("env.cue"),
        r#"package cuenv

name: "project-b"

env: {}

tasks: {
  generate: {
    command: "sh"
    args: ["-c", "echo B-PROJEN"]
    labels: ["projen"]
  }
}
"#,
    )
    .unwrap();

    let (stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        project_a.to_str().unwrap(),
        "--package",
        "cuenv",
        "-l",
        "projen",
    ]);

    assert!(
        success,
        "Expected success.\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
    );
    assert!(stdout.contains("A-PROJEN"));
    assert!(
        !stdout.contains("B-PROJEN"),
        "Label execution must be scoped to the selected path"
    );
}

#[test]
fn test_task_label_multiple_labels_and_semantics() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());

    // Create a project with multiple tasks having different label combinations
    fs::write(
        temp_dir.path().join("env.cue"),
        r#"package test

name: "test"

env: {}

tasks: {
  unit_tests: {
    command: "sh"
    args: ["-c", "echo UNIT-TESTS"]
    labels: ["test", "unit"]
  }
  e2e_tests: {
    command: "sh"
    args: ["-c", "echo E2E-TESTS"]
    labels: ["test"]
  }
  build: {
    command: "sh"
    args: ["-c", "echo BUILD"]
    labels: ["build"]
  }
}
"#,
    )
    .unwrap();

    // Test: Multiple labels with AND semantics - only unit_tests has both "test" AND "unit"
    let (stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "-l",
        "test",
        "-l",
        "unit",
    ]);

    assert!(
        success,
        "Expected success.\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
    );
    // Only unit_tests should match (has both "test" and "unit" labels)
    assert!(
        stdout.contains("UNIT-TESTS"),
        "Should execute unit_tests (has both labels)"
    );
    // e2e_tests only has "test" label, not "unit", so it shouldn't match
    assert!(
        !stdout.contains("E2E-TESTS"),
        "Should NOT execute e2e_tests (missing 'unit' label)"
    );
    assert!(
        !stdout.contains("BUILD"),
        "Should NOT execute build (has neither label)"
    );
}

#[test]
fn test_task_label_error_conflicting_task_name_and_label() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    fs::write(
        temp_dir.path().join("env.cue"),
        r#"package test
name: "test"
env: {}
tasks: {
  mytask: {
    command: "echo"
    args: ["hello"]
    labels: ["test"]
  }
}
"#,
    )
    .unwrap();

    // Test: Cannot specify both task name and --label
    let (_stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "mytask",
        "-l",
        "test",
    ]);

    assert!(
        !success,
        "Expected failure when specifying both task name and label"
    );
    // Note: miette may line-wrap the message, so check for key parts separately
    assert!(
        stderr.contains("Cannot specify both a task name") && stderr.contains("--label"),
        "Error message should mention conflict. Got: {stderr}"
    );
}

#[test]
fn test_task_label_error_trailing_args_become_task_name() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    fs::write(
        temp_dir.path().join("env.cue"),
        r#"package test
name: "test"
env: {}
tasks: {
  mytask: {
    command: "echo"
    labels: ["test"]
  }
}
"#,
    )
    .unwrap();

    // Test: Trailing args after -- are interpreted as task name (first positional)
    // Since task name conflicts with --label, we get the conflict error
    let (_stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "-l",
        "test",
        "--",
        "arg1",
        "arg2",
    ]);

    assert!(
        !success,
        "Expected failure when using trailing args with label selection"
    );
    // With trailing_var_arg, "arg1" becomes the task name, triggering the conflict error
    // Note: miette may line-wrap the message, so check for key parts separately
    assert!(
        stderr.contains("Cannot specify both a task name") && stderr.contains("--label"),
        "Error message should mention conflict (trailing arg becomes task name). Got: {stderr}"
    );
}

#[test]
fn test_task_label_error_no_matching_tasks() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    fs::write(
        temp_dir.path().join("env.cue"),
        r#"package test
name: "test"
env: {}
tasks: {
  mytask: {
    command: "echo"
    args: ["hello"]
    labels: ["existing"]
  }
}
"#,
    )
    .unwrap();

    // Test: No tasks match the given label
    let (_stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "-l",
        "nonexistent",
    ]);

    assert!(!success, "Expected failure when no tasks match label");
    assert!(
        stderr.contains("No tasks with labels") && stderr.contains("nonexistent"),
        "Error message should mention no matching tasks. Got: {stderr}"
    );
}

#[test]
fn test_task_label_error_empty_labels() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());
    fs::write(
        temp_dir.path().join("env.cue"),
        r#"package test
name: "test"
env: {}
tasks: {
  mytask: {
    command: "echo"
    labels: ["test"]
  }
}
"#,
    )
    .unwrap();

    // Test: Empty/whitespace-only labels should error
    let (_stdout, stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "-l",
        "   ",
    ]);

    assert!(!success, "Expected failure with empty/whitespace labels");
    assert!(
        stderr.contains("empty") || stderr.contains("whitespace"),
        "Error message should mention empty/whitespace labels. Got: {stderr}"
    );
}

#[test]
fn test_exec_hermetic_path_no_host_pollution() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());

    // Create a minimal project with a custom PATH in env
    let cue_content = r#"package test

name: "test"

env: {
    PATH: "/cuenv/tools/bin"
}"#;

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Run printenv PATH via exec - use absolute path since PATH is hermetic
    let printenv = find_in_path("printenv");
    let (stdout, _stderr, success) = run_cuenv(&[
        "exec",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        &printenv,
        "PATH",
    ]);

    assert!(success, "Command should succeed");

    // PATH should be exactly what we set, not polluted with host paths
    let path = stdout.trim();
    assert_eq!(
        path, "/cuenv/tools/bin",
        "PATH should be exactly what was set in env.cue, not polluted with host PATH. Got: {path}"
    );

    // Verify it does NOT contain common host paths
    assert!(
        !path.contains("/usr/bin"),
        "PATH should not contain /usr/bin (host pollution)"
    );
    assert!(
        !path.contains("/usr/local"),
        "PATH should not contain /usr/local (host pollution)"
    );
    assert!(
        !path.contains("/opt/homebrew"),
        "PATH should not contain /opt/homebrew (host pollution)"
    );
}

#[test]
fn test_task_hermetic_path_no_host_pollution() {
    let temp_dir = create_test_dir();
    init_cue_module(temp_dir.path());

    // Create a project with a task that prints PATH
    // Use absolute path since PATH is hermetic
    let printenv = find_in_path("printenv");
    let cue_content = format!(
        r#"package test

name: "test"

env: {{
    PATH: "/cuenv/tools/bin"
}}

tasks: {{
    show_path: {{
        command: "{printenv}"
        args: ["PATH"]
    }}
}}"#
    );

    fs::write(temp_dir.path().join("env.cue"), cue_content).unwrap();

    // Run the task
    let (stdout, _stderr, success) = run_cuenv(&[
        "task",
        "-p",
        temp_dir.path().to_str().unwrap(),
        "--package",
        "test",
        "show_path",
    ]);

    assert!(success, "Command should succeed");

    // Extract PATH from output (task output includes other info)
    let path_line = stdout
        .lines()
        .find(|line| line.starts_with("/cuenv/tools/bin") || line.contains("PATH"))
        .unwrap_or("");

    // PATH should be exactly what we set
    assert!(
        path_line.contains("/cuenv/tools/bin"),
        "PATH should contain our custom path. Got output: {stdout}"
    );
    assert!(
        !path_line.contains("/usr/bin"),
        "PATH should not contain /usr/bin (host pollution). Got: {path_line}"
    );
    assert!(
        !path_line.contains("/usr/local"),
        "PATH should not contain /usr/local (host pollution). Got: {path_line}"
    );
}