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
//! Task execution command implementation

mod arguments;
mod dag_export;
mod discovery;
pub mod list_builder;
mod rendering;
mod types;

// Re-export types for the public API. Some types may not be used externally yet.
#[allow(unused_imports)]
pub use types::{ExecutionMode, OutputConfig, TaskExecutionRequest, TaskSelection};

use arguments::{apply_args_to_task, resolve_task_args};
use discovery::{evaluate_manifest, find_tasks_with_labels, format_label_root, normalize_labels};
use list_builder::prepare_task_index;
use rendering::{format_task_detail, get_task_cli_help, render_task_tree};

use cuenv_core::Result;
use cuenv_core::environment::Environment;
use cuenv_core::lockfile::{LOCKFILE_NAME, LockedRuntime, Lockfile};
use cuenv_core::manifest::{Project, Runtime};
use cuenv_core::tasks::cache::TaskCacheConfig;
use cuenv_core::tasks::executor::{TASK_FAILURE_SNIPPET_LINES, summarize_task_failure};
use cuenv_core::tasks::{
    BackendFactory, ExecutorConfig, Task, TaskExecutor, TaskGraph, TaskNode, Tasks,
};
use cuenv_core::tools::apply_resolved_tool_activation;
use std::collections::BTreeMap;
use std::sync::Arc;

use super::env_file::find_cue_module_root;
use super::relative_path_from_root;
use super::tools::{ensure_tools_downloaded, resolve_tool_activation_steps};
use crate::tui::rich::RichTui;
use crate::tui::state::TaskInfo;
use cuenv_core::runtime::resolve_runtime_environment;

/// Get the dagger backend factory if the feature is enabled
#[cfg(feature = "dagger-backend")]
#[allow(clippy::unnecessary_wraps)] // Both cfg variants need same return type
fn get_dagger_factory() -> Option<BackendFactory> {
    Some(cuenv_dagger::create_dagger_backend)
}

#[cfg(not(feature = "dagger-backend"))]
fn get_dagger_factory() -> Option<BackendFactory> {
    None
}
use std::fmt::Write;
use std::path::{Path, PathBuf};

use super::export::get_environment_with_hooks;
use tracing::instrument;

/// Resolve the on-disk root for the local CAS + action cache.
///
/// Resolution order:
/// 1. `$CUENV_CACHE_DIR` (explicit override)
/// 2. `$XDG_CACHE_HOME/cuenv` or the platform default
/// 3. `<project>/.cuenv-cache`
fn resolve_cache_root(project_root: &Path) -> PathBuf {
    if let Some(env) = std::env::var_os("CUENV_CACHE_DIR")
        && !env.is_empty()
    {
        return PathBuf::from(env);
    }
    if let Some(d) = dirs::cache_dir() {
        return d.join("cuenv");
    }
    project_root.join(".cuenv-cache")
}

/// Construct the [`TaskCacheConfig`] used by the executor.
///
/// Returns `None` if the local CAS or action cache cannot be opened (e.g.
/// permissions). In that case the executor falls back to the no-cache code
/// path so the user's command still works — degraded, not broken.
fn build_task_cache(
    project_root: &Path,
    runtime_identity: RuntimeCacheIdentity,
) -> Option<TaskCacheConfig> {
    let root = resolve_cache_root(project_root);
    let cas = match cuenv_cas::LocalCas::open(&root) {
        Ok(c) => Arc::new(c) as Arc<dyn cuenv_cas::Cas>,
        Err(e) => {
            tracing::warn!(error = %e, root = %root.display(), "task cache disabled: cannot open CAS");
            return None;
        }
    };
    let action_cache = match cuenv_cas::LocalActionCache::open(&root) {
        Ok(ac) => Arc::new(ac) as Arc<dyn cuenv_cas::ActionCache>,
        Err(e) => {
            tracing::warn!(error = %e, root = %root.display(), "task cache disabled: cannot open action cache");
            return None;
        }
    };
    let vcs_hasher =
        Arc::new(cuenv_vcs::WalkHasher::new(project_root)) as Arc<dyn cuenv_vcs::VcsHasher>;
    Some(TaskCacheConfig {
        cas,
        action_cache,
        vcs_hasher,
        vcs_hasher_root: project_root.to_path_buf(),
        cuenv_version: env!("CARGO_PKG_VERSION").to_string(),
        runtime_identity_properties: runtime_identity.properties,
        cache_disabled_reason: runtime_identity.cache_disabled_reason,
    })
}

#[derive(Debug, Clone, Default)]
struct RuntimeCacheIdentity {
    properties: BTreeMap<String, String>,
    cache_disabled_reason: Option<String>,
}

fn resolve_runtime_cache_identity(
    module_root: &Path,
    project_root: &Path,
    runtime: Option<&Runtime>,
) -> RuntimeCacheIdentity {
    let mut identity = RuntimeCacheIdentity::default();
    let Some(runtime) = runtime else {
        return identity;
    };

    match runtime {
        Runtime::Nix(nix_runtime) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "nix".to_string());

            let lockfile_path = module_root.join(LOCKFILE_NAME);
            let lockfile = match Lockfile::load(&lockfile_path) {
                Ok(Some(lockfile)) => lockfile,
                Ok(None) => {
                    identity.cache_disabled_reason = Some(format!(
                        "runtime is nix but {} is missing",
                        lockfile_path.display()
                    ));
                    return identity;
                }
                Err(e) => {
                    identity.cache_disabled_reason = Some(format!(
                        "runtime is nix but {} could not be read: {}",
                        lockfile_path.display(),
                        e
                    ));
                    return identity;
                }
            };

            let project_path = relative_path_from_root(module_root, project_root);
            let project_key = project_path.to_string_lossy().into_owned();
            let Some(locked_runtime) = lockfile.find_runtime(&project_key) else {
                identity.cache_disabled_reason = Some(format!(
                    "runtime is nix but lockfile has no runtime entry for project '{}'",
                    project_key
                ));
                return identity;
            };

            let LockedRuntime::Nix(locked_nix) = locked_runtime;

            if locked_nix.flake != nix_runtime.flake || locked_nix.output != nix_runtime.output {
                identity.cache_disabled_reason = Some(format!(
                    "runtime lock mismatch for project '{}': expected flake='{}' output='{}', got flake='{}' output='{}'",
                    project_key,
                    nix_runtime.flake,
                    nix_runtime.output.as_deref().unwrap_or(""),
                    locked_nix.flake,
                    locked_nix.output.as_deref().unwrap_or("")
                ));
                return identity;
            }

            identity
                .properties
                .insert("runtime.nix.digest".to_string(), locked_nix.digest.clone());
            identity
                .properties
                .insert("runtime.nix.flake".to_string(), locked_nix.flake.clone());
            if let Some(output) = &locked_nix.output {
                identity
                    .properties
                    .insert("runtime.nix.output".to_string(), output.clone());
            }
            identity.properties.insert(
                "runtime.nix.lockfile".to_string(),
                locked_nix.lockfile.clone(),
            );
            identity
        }
        Runtime::Devenv(_) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "devenv".to_string());
            identity
        }
        Runtime::Container(_) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "container".to_string());
            identity
        }
        Runtime::Dagger(_) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "dagger".to_string());
            identity
        }
        Runtime::Oci(_) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "oci".to_string());
            identity
        }
        Runtime::Tools(_) => {
            identity
                .properties
                .insert("runtime.kind".to_string(), "tools".to_string());
            identity
        }
    }
}

/// Execute a task using the new structured request API.
///
/// This is the preferred entry point for task execution. It accepts a
/// `TaskExecutionRequest` which groups all parameters into a structured
/// format with type-safe selection modes.
///
/// # Errors
///
/// Returns an error if task resolution, validation, or execution fails.
///
/// # Example
///
/// ```ignore
/// let request = TaskExecutionRequest::named("./", "cuenv", "build")
///     .with_args(vec!["--release".to_string()])
///     .with_environment("prod");
///
/// let output = execute(request).await?;
/// ```
#[instrument(name = "task_execute", skip(request), fields(path = %request.path, package = %request.package))]
pub async fn execute(request: TaskExecutionRequest<'_>) -> Result<String> {
    execute_task_impl(&request).await
}

/// Resolved task context from either named-task or label-based resolution.
struct TaskResolution {
    display_name: String,
    node: TaskNode,
    tasks: Tasks,
    graph_root_name: String,
    output_ref_deps: Vec<(String, String)>,
}

fn current_instance_output_ref_deps(
    executor: &crate::commands::CommandExecutor,
    project_root: &Path,
) -> Result<Vec<(String, String)>> {
    let module = executor.get_module(project_root)?;
    let rel_path = relative_path_from_root(&module.root, project_root);

    Ok(module
        .get(&rel_path)
        .map_or_else(Vec::new, |instance| instance.output_ref_deps.clone()))
}

/// Internal implementation of task execution.
#[allow(clippy::too_many_lines)]
async fn execute_task_impl(request: &TaskExecutionRequest<'_>) -> Result<String> {
    // Extract derived values from the structured request
    let (task_name, labels, task_args, interactive) = match &request.selection {
        TaskSelection::Named { name, args } => {
            (Some(name.as_str()), &[][..], args.as_slice(), false)
        }
        TaskSelection::Labels(l) => (None, l.as_slice(), &[][..], false),
        TaskSelection::List => (None, &[][..], &[][..], false),
        TaskSelection::Interactive => (None, &[][..], &[][..], true),
    };

    let path = &request.path;
    let package = &request.package;
    let environment = request.environment.as_deref();
    let format: &str = &request.output.format;
    let capture_output = request.output.capture_output;
    let materialize_outputs = request
        .output
        .materialize_outputs
        .as_ref()
        .and_then(|p| p.to_str());
    let show_cache_path = request.output.show_cache_path;
    let backend = request.backend.as_deref();
    let tui = request.execution_mode == ExecutionMode::Tui;
    let help = request.output.help;
    let skip_dependencies = request.skip_dependencies;
    let dry_run = request.dry_run;
    let executor = request.executor;
    // Handle CLI help immediately if no task specified
    if task_name.is_none() && help {
        return Ok(get_task_cli_help());
    }

    tracing::info!(
        "Executing task from path: {}, package: {}, task: {:?}",
        path,
        package,
        task_name
    );

    // Evaluate CUE to get tasks and environment using module-wide evaluation
    let mut manifest: Project = evaluate_manifest(Path::new(path), package, executor)?;
    tracing::debug!("CUE evaluation successful");

    tracing::debug!(
        "Successfully parsed CUE evaluation, found {} tasks",
        manifest.tasks.len()
    );

    // Canonicalize project root for consistent paths
    let project_root =
        std::fs::canonicalize(path).unwrap_or_else(|_| Path::new(path).to_path_buf());
    let cue_module_root = find_cue_module_root(&project_root);

    // Build a canonical index to support nested task paths (with auto-detected workspace tasks)
    let task_index = prepare_task_index(&mut manifest, &project_root)?;
    let local_tasks = task_index.to_tasks();

    // Handle interactive mode: show picker and execute selected task
    if interactive && task_name.is_none() && labels.is_empty() {
        use super::task_picker::{PickerResult, SelectableTask, run_picker};

        let tasks = task_index.list();
        let selectable: Vec<SelectableTask> = tasks
            .iter()
            .map(|t| {
                let description = match &t.node {
                    TaskNode::Task(task) => task.description.clone(),
                    TaskNode::Group(g) => g.description.clone(),
                    TaskNode::Sequence(_) => None,
                };
                SelectableTask {
                    name: t.name.clone(),
                    description,
                }
            })
            .collect();

        match run_picker(selectable) {
            Ok(PickerResult::Selected(selected_task)) => {
                // Build a new request for the selected task
                let mut request =
                    TaskExecutionRequest::named(path, package, &selected_task, executor)
                        .with_format(format);

                if let Some(env) = environment {
                    request = request.with_environment(env);
                }
                if capture_output.should_capture() {
                    request = request.with_capture();
                }
                if let Some(mat_path) = materialize_outputs {
                    request = request.with_materialize_outputs(mat_path);
                }
                if show_cache_path {
                    request = request.with_show_cache_path();
                }
                if let Some(be) = backend {
                    request = request.with_backend(be);
                }
                if tui {
                    request = request.with_tui();
                }
                if help {
                    request = request.with_help();
                }
                if skip_dependencies {
                    request = request.with_skip_dependencies();
                }

                return Box::pin(execute(request)).await;
            }
            Ok(PickerResult::Cancelled) => {
                return Ok(String::new());
            }
            Err(e) => {
                return Err(cuenv_core::Error::configuration(format!(
                    "Interactive picker failed: {e}"
                )));
            }
        }
    }

    // If no task specified, list available tasks
    if task_name.is_none() && labels.is_empty() {
        use super::task_list::{
            DashboardFormatter, EmojiFormatter, RichFormatter, TablesFormatter, TaskListFormatter,
            TextFormatter, build_task_list,
        };
        use std::io::IsTerminal;

        tracing::debug!("Listing available tasks");
        let tasks = task_index.list();
        tracing::debug!("Found {} tasks to list", tasks.len());

        if format == "json" {
            return serde_json::to_string(&tasks).map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to serialize tasks: {e}"))
            });
        }

        if tasks.is_empty() {
            return Ok("No tasks defined in the configuration".to_string());
        }

        // Calculate current working directory relative to cue.mod root
        let project_root =
            std::fs::canonicalize(path).unwrap_or_else(|_| Path::new(path).to_path_buf());
        let cwd_relative = cue_module_root.as_ref().and_then(|root| {
            project_root
                .strip_prefix(root)
                .ok()
                .map(|p| p.to_string_lossy().to_string())
        });

        // Build task list data
        let task_data = build_task_list(&tasks, cwd_relative.as_deref(), &project_root);

        // Determine effective format: CLI flag > config > auto-detect
        let effective_format = if format.is_empty() {
            // No CLI flag provided, check config
            manifest
                .config
                .as_ref()
                .and_then(|c| c.task_list_format())
                .map(|f| f.as_str())
        } else {
            Some(format)
        };

        // Select formatter based on effective format
        let output = match effective_format {
            Some("rich") => {
                let formatter = RichFormatter::new();
                formatter.format(&task_data)
            }
            Some("text") => {
                let formatter = TextFormatter;
                formatter.format(&task_data)
            }
            Some("tables") => {
                let formatter = TablesFormatter::new();
                formatter.format(&task_data)
            }
            Some("dashboard") => {
                let formatter = DashboardFormatter::new();
                formatter.format(&task_data)
            }
            Some("emoji") => {
                let formatter = EmojiFormatter;
                formatter.format(&task_data)
            }
            _ => {
                // Auto-detect: rich for TTY, text otherwise
                if std::io::stdout().is_terminal() {
                    let formatter = RichFormatter::new();
                    formatter.format(&task_data)
                } else {
                    let formatter = TextFormatter;
                    formatter.format(&task_data)
                }
            }
        };

        return Ok(output);
    }

    if !labels.is_empty() && task_name.is_some() {
        return Err(cuenv_core::Error::configuration(
            "Cannot specify both a task name and --label",
        ));
    }
    if !labels.is_empty() && !task_args.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "Task arguments are not supported when selecting tasks by label",
        ));
    }

    // Validate that labels are non-empty after normalization
    let normalized_labels = normalize_labels(labels);
    if !labels.is_empty() && normalized_labels.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "Labels cannot be empty or whitespace-only",
        ));
    }

    let resolution = if normalized_labels.is_empty() {
        // Execute a named task
        let requested_task = task_name.ok_or_else(|| {
            cuenv_core::Error::configuration("task name required when no labels provided")
        })?;
        tracing::debug!("Looking for specific task: {}", requested_task);

        // If help requested for specific task/group
        if help {
            let tasks = task_index.list();
            let prefix = format!("{requested_task}.");
            let subtasks: Vec<&cuenv_core::tasks::IndexedTask> = tasks
                .iter()
                .filter(|t| t.name == requested_task || t.name.starts_with(&prefix))
                .copied()
                .collect();

            if subtasks.is_empty() {
                return Err(cuenv_core::Error::configuration(format!(
                    "Task '{requested_task}' not found",
                )));
            }

            // If it's a single task without subtasks
            if subtasks.len() == 1 && subtasks[0].name == requested_task {
                return Ok(format_task_detail(subtasks[0]));
            }

            // It's a group or task with subtasks
            // Note: For help on specific groups, we don't need cwd-relative sorting
            return Ok(render_task_tree(subtasks, None));
        }

        // Resolve task via canonical index (supports nested paths and ':' alias)
        let task_entry = task_index.resolve(requested_task)?;
        let canonical_task_name = task_entry.name.clone();
        tracing::debug!(
            "Task index entries: {:?}",
            task_index
                .list()
                .iter()
                .map(|t| t.name.as_str())
                .collect::<Vec<_>>()
        );
        tracing::debug!(
            "Indexed tasks for execution: {:?}",
            local_tasks.list_tasks()
        );
        tracing::debug!(
            "Requested task '{}' present: {}",
            requested_task,
            local_tasks.get(requested_task).is_some()
        );
        let original_task_node = local_tasks.get(&canonical_task_name).ok_or_else(|| {
            cuenv_core::Error::configuration(format!("Task '{canonical_task_name}' not found"))
        })?;
        let display_task_name = canonical_task_name;

        tracing::debug!("Found task node: {:?}", original_task_node);

        let mut tasks_in_scope = local_tasks.clone();
        let output_ref_deps = current_instance_output_ref_deps(executor, &project_root)?;

        // If args were provided, apply them to the selected task definition in the
        // local task registry so graph build uses the interpolated version.
        let selected_task_node = if task_args.is_empty() {
            tasks_in_scope
                .get(&display_task_name)
                .cloned()
                .ok_or_else(|| {
                    cuenv_core::Error::configuration(format!(
                        "Task '{display_task_name}' not found in local tasks"
                    ))
                })?
        } else {
            let node = tasks_in_scope
                .get(&display_task_name)
                .cloned()
                .ok_or_else(|| {
                    cuenv_core::Error::configuration(format!(
                        "Task '{display_task_name}' not found in local tasks"
                    ))
                })?;
            if let TaskNode::Task(task) = node {
                let resolved_args = resolve_task_args(task.params.as_ref(), task_args)?;
                tracing::debug!("Resolved task args: {:?}", resolved_args);

                let modified_task = apply_args_to_task(&task, &resolved_args);
                let modified_node = TaskNode::Task(Box::new(modified_task.clone()));
                tasks_in_scope
                    .tasks
                    .insert(display_task_name.clone(), modified_node.clone());
                modified_node
            } else {
                return Err(cuenv_core::Error::configuration(
                    "Task arguments are not supported for task groups or lists".to_string(),
                ));
            }
        };

        TaskResolution {
            display_name: display_task_name.clone(),
            node: selected_task_node,
            tasks: tasks_in_scope,
            graph_root_name: display_task_name,
            output_ref_deps,
        }
    } else {
        let mut tasks_in_scope = local_tasks.clone();
        let matching_tasks = find_tasks_with_labels(&local_tasks, &normalized_labels);

        if matching_tasks.is_empty() {
            return Err(cuenv_core::Error::configuration(format!(
                "No tasks with labels {normalized_labels:?} were found in this scope"
            )));
        }

        let display_task_name = format_label_root(&normalized_labels);
        let synthetic = Task {
            script: Some("true".to_string()),
            hermetic: false,
            depends_on: matching_tasks
                .into_iter()
                .map(cuenv_core::tasks::TaskDependency::from_name)
                .collect(),
            project_root: Some(project_root.clone()),
            description: Some(format!(
                "Run all tasks matching labels: {}",
                normalized_labels.join(", ")
            )),
            ..Default::default()
        };

        tasks_in_scope.tasks.insert(
            display_task_name.clone(),
            TaskNode::Task(Box::new(synthetic)),
        );

        let resolved_node = tasks_in_scope
            .get(&display_task_name)
            .cloned()
            .ok_or_else(|| {
                cuenv_core::Error::execution("synthetic task missing after insertion")
            })?;

        TaskResolution {
            display_name: display_task_name.clone(),
            node: resolved_node,
            tasks: tasks_in_scope,
            graph_root_name: display_task_name,
            output_ref_deps: current_instance_output_ref_deps(executor, &project_root)?,
        }
    };

    // Build task graph for dependency-aware execution
    tracing::debug!(
        "Building task graph for task: {}",
        resolution.graph_root_name
    );
    let mut task_graph = TaskGraph::new();

    if skip_dependencies {
        // When skipping dependencies, just add the target task without its dependency tree.
        // This is used by CI orchestrators (like GitHub Actions) that handle dependencies externally.
        tracing::debug!("Skipping dependencies - adding only the target task");
        if let Some(TaskNode::Task(task)) = resolution.tasks.get(&resolution.graph_root_name) {
            task_graph.add_task(&resolution.graph_root_name, (**task).clone())?;
        }
    } else {
        task_graph
            .build_for_task(&resolution.graph_root_name, &resolution.tasks)
            .map_err(|e| {
                tracing::error!("Failed to build task graph: {}", e);
                e
            })?;
    }

    // Inject implicit dependency edges from task output references.
    // Output ref deps are collected during CUE JSON processing for the selected
    // instance and use the same canonical local task names as `tasks_in_scope`.
    if !resolution.output_ref_deps.is_empty() {
        task_graph.add_output_ref_deps(&resolution.output_ref_deps, &resolution.tasks)?;
    }

    tracing::debug!(
        "Successfully built task graph with {} tasks",
        task_graph.task_count()
    );

    // Handle dry-run mode: export DAG as JSON without executing
    if dry_run.is_dry_run() {
        let dag_export = dag_export::DagExport::from_task_graph(&task_graph)?;
        return serde_json::to_string_pretty(&dag_export).map_err(|e| {
            cuenv_core::Error::configuration(format!("Failed to serialize DAG: {e}"))
        });
    }

    // Get environment with hook-generated vars merged in
    // Note: This may spawn a hook supervisor subprocess, so it must happen
    // AFTER the dry-run check to avoid fork-safety issues.
    let directory = project_root.clone();
    let base_env_vars =
        get_environment_with_hooks(&directory, &manifest, package, Some(executor)).await?;

    // Apply task-specific policies and secret resolvers on top of the merged environment
    let mut runtime_env = Environment::new();
    let runtime_env_vars =
        resolve_runtime_environment(&project_root, manifest.runtime.as_ref()).await?;
    for (key, value) in runtime_env_vars {
        runtime_env.set(key, value);
    }

    if let Some(env) = &manifest.env {
        // First apply the base environment (static + hooks)
        for (key, value) in &base_env_vars {
            runtime_env.set(key.clone(), value.clone());
        }

        // Get environment variables, applying environment-specific overrides if specified
        let env_vars = if let Some(env_name) = environment {
            env.for_environment(env_name)
        } else {
            env.base.clone()
        };

        // Then apply task-specific overrides with policies and secret resolution
        let (task_env_vars, secrets) =
            cuenv_core::environment::Environment::resolve_for_task_with_secrets(
                resolution.display_name.as_str(),
                &env_vars,
            )
            .await?;

        // Register resolved secrets for global redaction in the events system.
        // This ensures they're redacted from ALL output, not just this task's output.
        cuenv_events::register_secrets(secrets.into_iter());

        for (key, value) in task_env_vars {
            runtime_env.set(key, value);
        }
    } else {
        // No manifest env, just use hook-generated environment
        for (key, value) in base_env_vars {
            runtime_env.set(key, value);
        }
    }

    if should_activate_lockfile_tools(&manifest) {
        // Download and activate tools from lockfile by prepending to PATH and library path.
        // This happens automatically without requiring hook approval since tool
        // activation is a controlled, safe operation (just adds paths to the environment).
        // Use project_root to scope tool activation to this project only.
        // Tool activation failures are fatal - tasks require their tools to run.
        ensure_tools_downloaded(Some(&project_root))
            .await
            .map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to download tools: {e}"))
            })?;
        if let Some(activation_steps) =
            resolve_tool_activation_steps(Some(&project_root)).map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to resolve tools activation: {e}"))
            })?
        {
            tracing::debug!(
                steps = activation_steps.len(),
                "Applying configured tool activation operations for task execution"
            );

            for step in activation_steps {
                let current = runtime_env.get(&step.var);
                if let Some(new_value) = apply_resolved_tool_activation(current, &step) {
                    runtime_env.set(step.var.clone(), new_value);
                }
            }
        }
    }

    // Build the task cache (CAS + ActionCache + VcsHasher) once and share it
    // between the regular and TUI executor configs. Cache writes are
    // best-effort, so failure to open the local store degrades to "no
    // caching" rather than aborting the user's command.
    let module_root = cue_module_root.as_deref().unwrap_or(project_root.as_path());
    let runtime_identity = resolve_runtime_cache_identity(
        module_root,
        project_root.as_path(),
        manifest.runtime.as_ref(),
    );
    if let Some(reason) = &runtime_identity.cache_disabled_reason {
        tracing::warn!(reason, "task cache disabled for this invocation");
    }
    let task_cache = build_task_cache(&project_root, runtime_identity);

    // Create executor with environment
    let config = ExecutorConfig {
        capture_output,
        max_parallel: 0,
        environment: runtime_env.clone(),
        working_dir: None,
        cue_module_root: cue_module_root.clone(),
        project_root: project_root.clone(),
        materialize_outputs: materialize_outputs.map(|s| Path::new(s).to_path_buf()),
        cache_dir: None,
        show_cache_path,
        backend_config: manifest.config.as_ref().and_then(|c| c.backend.clone()),
        cli_backend: backend.map(ToString::to_string),
        cache: task_cache.clone(),
    };

    let executor = TaskExecutor::with_dagger_factory(config, get_dagger_factory());

    // If TUI is requested and we have a task graph, launch the rich TUI
    if tui && task_graph.task_count() > 0 {
        // For TUI mode, we MUST capture output so it goes through the event system
        // rather than directly to stdout/stderr (which would corrupt the TUI display).
        let tui_config = ExecutorConfig {
            capture_output: cuenv_core::OutputCapture::Capture, // Force capture for TUI mode
            max_parallel: 0,
            environment: runtime_env.clone(),
            working_dir: None,
            cue_module_root: cue_module_root.clone(),
            project_root: project_root.clone(),
            materialize_outputs: materialize_outputs.map(|s| Path::new(s).to_path_buf()),
            cache_dir: None,
            show_cache_path,
            backend_config: manifest.config.as_ref().and_then(|c| c.backend.clone()),
            cli_backend: backend.map(ToString::to_string),
            cache: task_cache.clone(),
        };
        let tui_executor = TaskExecutor::with_dagger_factory(tui_config, get_dagger_factory());

        return execute_with_rich_tui(&tui_executor, resolution.display_name.as_str(), &task_graph)
            .await;
    }

    // Execute using the appropriate method
    let results = execute_task_with_strategy(
        &executor,
        resolution.display_name.as_str(),
        &resolution.node,
        &task_graph,
        &resolution.tasks,
    )
    .await?;

    // Check for any failed tasks first and return a rich summary
    if let Some(failed) = results.iter().find(|r| !r.success) {
        return Err(cuenv_core::Error::configuration(summarize_task_failure(
            failed,
            TASK_FAILURE_SNIPPET_LINES,
        )));
    }

    // Format results
    let output = format_task_results(results, capture_output, resolution.display_name.as_str());
    Ok(output)
}

fn should_activate_lockfile_tools(project: &Project) -> bool {
    matches!(project.runtime, Some(Runtime::Tools(_)))
}

/// Execute task with rich TUI interface
///
/// Note: The executor MUST have `capture_output: true` to ensure task output
/// goes through the event system rather than directly to stdout/stderr.
async fn execute_with_rich_tui(
    executor: &TaskExecutor,
    task_name: &str,
    task_graph: &TaskGraph,
) -> Result<String> {
    // Subscribe to the global event bus.
    // The global bus is set up during CLI initialization and receives all events
    // emitted via the emit_task_*! macros through the global tracing subscriber.
    let event_rx = crate::tracing::subscribe_global_events().ok_or_else(|| {
        cuenv_core::Error::configuration(
            "Global event bus not initialized - TUI requires event-based tracing".to_string(),
        )
    })?;

    // Create oneshot channel for TUI readiness signaling.
    // This prevents a race condition where task execution starts
    // before the TUI event loop is ready to receive events.
    let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();

    // Create and initialize TUI
    let mut tui = RichTui::new(event_rx, ready_tx)
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to initialize TUI: {e}")))?;

    // Build TaskInfo structs from the task graph
    let mut task_infos = Vec::new();
    let sorted_tasks = task_graph
        .topological_sort()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to sort task graph: {e}")))?;

    // Calculate levels based on dependencies
    let mut levels: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for node in &sorted_tasks {
        let max_dep_level = node
            .task
            .depends_on
            .iter()
            .filter_map(|dep| levels.get(dep.task_name()).copied())
            .max()
            .unwrap_or(0);
        let increment = usize::from(!node.task.depends_on.is_empty());
        levels.insert(node.name.clone(), max_dep_level.saturating_add(increment));
    }

    for node in sorted_tasks {
        let task_name = node.name.clone();
        let dependencies: Vec<String> = node
            .task
            .depends_on
            .iter()
            .map(|d| d.task_name().to_string())
            .collect();
        let level = levels.get(&task_name).copied().unwrap_or(0);

        task_infos.push(TaskInfo::new(task_name, dependencies, level));
    }

    tui.init_tasks(task_infos);

    // Run TUI and task execution concurrently
    // Note: TUI run() is blocking (uses crossterm::event::poll), so we spawn_blocking
    let tui_handle = tokio::task::spawn_blocking(move || tui.run());

    // Wait for TUI to signal it's ready before starting task execution.
    // This prevents a race condition where early events are missed.
    if ready_rx.await.is_err() {
        // TUI failed to start or was dropped before signaling ready
        return Err(cuenv_core::Error::configuration(
            "TUI failed to initialize - event loop did not start".to_string(),
        ));
    }

    // Execute tasks
    let results = executor.execute_graph(task_graph).await?;

    // Determine overall success
    let all_succeeded = results.iter().all(|r| r.success);

    // Emit completion event so the TUI knows execution is done.
    // This must happen BEFORE the event bus sender is dropped.
    cuenv_events::emit_command_completed!("task", all_succeeded, 0_u64);

    // Wait for TUI to finish and handle any errors.
    // Note: No sleep is needed here because:
    // 1. The TUI polls for events every 50ms
    // 2. We're waiting for the user to dismiss the TUI (via tui_handle.await)
    // 3. The channel stays open until this function returns (after TUI finishes)
    // Note: By this point, the TUI's TerminalGuard has been dropped,
    // so the terminal is restored and stderr output will be visible.
    match tui_handle.await {
        Ok(Ok(())) => {
            // TUI completed successfully
        }
        Ok(Err(e)) => {
            // TUI returned an error - log it but don't fail the task execution
            // since the tasks themselves may have succeeded
            tracing::warn!(error = %e, "TUI error (task execution may have succeeded)");
            cuenv_events::emit_stderr!(format!("Warning: TUI encountered an error: {e}"));
            cuenv_events::emit_stderr!(
                "Task output may not have been fully displayed. Check logs for details."
            );
        }
        Err(e) => {
            // TUI task panicked or was cancelled
            tracing::error!(error = %e, "TUI task failed");
            cuenv_events::emit_stderr!(format!("Warning: TUI terminated unexpectedly: {e}"));
        }
    }

    // Check for failures
    if let Some(failed) = results.iter().find(|r| !r.success) {
        return Err(cuenv_core::Error::configuration(summarize_task_failure(
            failed,
            TASK_FAILURE_SNIPPET_LINES,
        )));
    }

    // Return success message
    Ok(format!(
        "Task '{task_name}' completed successfully in TUI mode"
    ))
}

/// Execute a task using the appropriate strategy based on task type and dependencies.
async fn execute_task_with_strategy(
    executor: &TaskExecutor,
    task_name: &str,
    task_node: &TaskNode,
    task_graph: &TaskGraph,
    all_tasks: &Tasks,
) -> Result<Vec<cuenv_core::tasks::TaskResult>> {
    match task_node {
        TaskNode::Group(_) | TaskNode::Sequence(_) => {
            // For groups (parallel) and lists (sequential), use the original execution
            executor.execute_node(task_name, task_node, all_tasks).await
        }
        TaskNode::Task(_) => {
            // The task graph is built from `all_tasks` and is the authoritative
            // dependency view for execution.
            if task_graph.task_count() <= 1 {
                executor.execute_node(task_name, task_node, all_tasks).await
            } else {
                executor.execute_graph(task_graph).await
            }
        }
    }
}

fn format_task_results(
    results: Vec<cuenv_core::tasks::TaskResult>,
    capture_output: cuenv_core::OutputCapture,
    task_name: &str,
) -> String {
    let mut output = String::new();
    for result in results {
        if capture_output.should_capture() {
            write!(output, "Task '{}' ", result.name).expect("write to string");
            if result.success {
                output.push_str("succeeded\n");
                if !result.stdout.is_empty() {
                    output.push_str("Output:\n");
                    output.push_str(&result.stdout);
                    output.push('\n');
                }
            } else {
                writeln!(output, "failed with exit code {:?}", result.exit_code)
                    .expect("write to string");
                if !result.stderr.is_empty() {
                    output.push_str("Error:\n");
                    output.push_str(&result.stderr);
                    output.push('\n');
                }
            }
        } else {
            // When not capturing output, logs are streamed directly by the executor
            // or printed from cache by the executor (if modified).
            // We do NOT print them again here to avoid duplication.
        }
    }

    if capture_output.should_capture() && output.is_empty() {
        output = format!("Task '{task_name}' completed");
    } else if !capture_output.should_capture() {
        // In non-capturing mode, ensure we always include a clear completion
        // message even if we printed cached logs above.
        if output.is_empty() {
            output = format!("Task '{task_name}' completed");
        } else {
            let _ = writeln!(output, "Task '{task_name}' completed");
        }
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::CommandExecutor;
    use cuenv_core::tasks::TaskNode;
    use tokio::sync::mpsc;

    use std::fs;
    use tempfile::TempDir;

    /// Create a test executor for unit tests.
    fn create_test_executor() -> CommandExecutor {
        let (sender, _receiver) = mpsc::unbounded_channel();
        CommandExecutor::new(sender, "cuenv".to_string())
    }

    #[tokio::test]
    async fn test_list_tasks_empty() {
        let temp_dir = TempDir::new().expect("write to string");
        let cue_content = r#"package test
env: {
    FOO: "bar"
}"#;
        fs::write(temp_dir.path().join("env.cue"), cue_content).expect("write to string");

        let executor = create_test_executor();
        let request =
            TaskExecutionRequest::list(temp_dir.path().to_str().unwrap(), "test", &executor);
        let result = execute(request).await;

        // The result depends on FFI availability
        if let Ok(output) = result {
            assert!(output.contains("No tasks") || output.contains("Available tasks"));
        } else {
            // FFI not available in test environment
        }
    }

    #[test]
    fn test_format_task_results_variants() {
        let r_ok = cuenv_core::tasks::TaskResult {
            name: "t".into(),
            exit_code: Some(0),
            stdout: "hello".into(),
            stderr: String::new(),
            success: true,
        };
        let r_fail = cuenv_core::tasks::TaskResult {
            name: "t".into(),
            exit_code: Some(1),
            stdout: String::new(),
            stderr: "boom".into(),
            success: false,
        };

        // capture on: show status and fields
        let s = format_task_results(vec![r_ok.clone(), r_fail.clone()], true.into(), "t");
        assert!(s.contains("succeeded"));
        assert!(s.contains("Output:"));
        assert!(s.contains("failed with exit code"));
        assert!(s.contains("Error:"));

        // capture off: logs passed through + completion line
        let s2 = format_task_results(vec![r_ok], false.into(), "t");
        assert!(!s2.contains("hello")); // Output handled by executor now
        assert!(s2.contains("Task 't' completed"));

        // capture on with empty output -> default completion
        let s3 = format_task_results(vec![], true.into(), "abc");
        assert_eq!(s3, "Task 'abc' completed");
    }

    #[test]
    fn test_render_task_tree() {
        use cuenv_core::tasks::IndexedTask;
        // Helper to create a dummy task
        let make_task = |desc: Option<&str>| Task {
            command: "echo".into(),
            description: desc.map(ToString::to_string),
            ..Default::default()
        };

        let t_build = IndexedTask {
            name: "build".into(),
            original_name: "build".into(),
            node: TaskNode::Task(Box::new(make_task(Some("Build the project")))),
            is_group: false,
            source_file: None, // Root env.cue
        };
        let t_fmt_check = IndexedTask {
            name: "fmt.check".into(),
            original_name: "fmt.check".into(),
            node: TaskNode::Task(Box::new(make_task(Some("Check formatting")))),
            is_group: false,
            source_file: None,
        };
        let t_fmt_fix = IndexedTask {
            name: "fmt.fix".into(),
            original_name: "fmt.fix".into(),
            node: TaskNode::Task(Box::new(make_task(Some("Fix formatting")))),
            is_group: false,
            source_file: None,
        };

        // Provide them in mixed order to verify sorting
        let tasks = vec![&t_fmt_fix, &t_build, &t_fmt_check];
        let output = render_task_tree(tasks, None);

        // We can't match exact lines easily because of dot padding calculation,
        // but we can check structure and presence of content.

        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines[0], "Tasks:");

        // build is first alphabetically
        assert!(lines[1].starts_with("├─ build"));
        assert!(lines[1].contains("Build the project"));

        // fmt is second/last
        assert!(lines[2].starts_with("└─ fmt"));

        // children of fmt
        // fmt is last, so children have "   " prefix
        assert!(lines[3].starts_with("   ├─ check"));
        assert!(lines[3].contains("Check formatting"));

        assert!(lines[4].starts_with("   └─ fix"));
        assert!(lines[4].contains("Fix formatting"));
    }
}