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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
//! cuenv CLI Application
//!
//! Production-grade CUE environment toolchain providing command-line interface
//! for CUE package evaluation, environment variable management, and task orchestration.
//!
//! ## Future Direction
//!
//! This binary is transitioning to a library-first architecture (ADR-0006).
//! The eventual goal is:
//!
//! ```ignore
//! fn main() -> cuenv::Result<()> {
//!     cuenv::Cuenv::builder()
//!         .with_defaults()
//!         .build()
//!         .run()
//! }
//! ```
//!
//! Currently, the CLI logic remains here while the library infrastructure
//! is being developed. See `cuenv::Cuenv` for the library API.

// expect_used is allowed for infallible operations like writing to strings
#![allow(clippy::expect_used)]

// Import everything from the library
use crossterm::ExecutableCommand;
use cuenv::cli::{
    self, CliError, EXIT_OK, OkEnvelope, OutputFormat, exit_code_for, parse, render_error,
};
use cuenv::commands::{self, Command, CommandExecutor};
use cuenv::tracing::{self, Level, TracingConfig, TracingFormat};
use cuenv::{coordinator, tui};
use cuenv_events::renderers::{CliRenderer, JsonRenderer};
use cuenv_hooks::{ExecutionStatus, Hook, HookExecutionConfig, StateManager, execute_hooks};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::instrument;

/// Exit code for SIGINT (128 + signal number 2)
const EXIT_SIGINT: i32 = 130;

/// LLM context content (llms.txt + CUE schemas concatenated at build time)
const LLMS_CONTENT: &str = include_str!(concat!(env!("OUT_DIR"), "/llms-full.txt"));

/// Main entry point - determines sync vs async execution path
fn main() {
    // Install the rustls crypto provider before any HTTP clients are created.
    // Required because reqwest uses `rustls-no-provider` to avoid bundling aws-lc-sys.
    rustls::crypto::ring::default_provider()
        .install_default()
        .expect("Failed to install default rustls crypto provider");

    // Set up error handling first
    // NOTE: Using eprintln! in panic hook is intentional - tracing infrastructure
    // may be corrupted during a panic, so we use the most reliable output method.
    #[allow(clippy::print_stderr)]
    std::panic::set_hook(Box::new(|panic_info| {
        eprintln!("Application panicked: {panic_info}");
        eprintln!("Internal error occurred. Run with RUST_LOG=debug for more information.");
    }));

    // Register known credential environment variables for redaction.
    // This ensures any output containing these values is automatically redacted.
    if let Ok(token) = std::env::var("OP_SERVICE_ACCOUNT_TOKEN") {
        cuenv_events::register_secret(token);
    }

    // Handle shell completion requests first (before any other processing)
    if cli::try_complete() {
        std::process::exit(EXIT_OK);
    }

    // Check for special internal commands that always need async
    let args: Vec<String> = std::env::args().collect();

    // Hidden process-babysitter wrapper (primarily for macOS where
    // PR_SET_PDEATHSIG is unavailable). Exits directly without touching
    // the main CLI machinery.
    #[cfg(unix)]
    if args.len() > 1 && args[1] == "__supervise" {
        let rest: Vec<String> = args.iter().skip(2).cloned().collect();
        let code = commands::supervise::run(&rest);
        std::process::exit(code);
    }

    if args.len() > 1 && (args[1] == "__hook-supervisor" || args[1] == "__coordinator") {
        // For supervisor, detach from controlling terminal if on Unix
        // This is done here instead of via pre_exec in the parent to avoid
        // fork-safety issues when the parent is multi-threaded (Go runtime)
        #[cfg(unix)]
        if args[1] == "__hook-supervisor" {
            // SAFETY: setsid() creates a new session and process group.
            // This is safe to call at startup. We ignore errors (e.g. if already leader).
            #[expect(
                unsafe_code,
                reason = "Required for POSIX process detachment via setsid()"
            )]
            unsafe {
                libc::setsid();
            }
        }

        // These internal commands always need tokio
        let exit_code = run_with_tokio();
        std::process::exit(exit_code);
    }

    // Parse CLI arguments synchronously to determine execution path
    let cli = cli::parse();

    // Check if command needs async runtime
    if requires_async_runtime(&cli) {
        let exit_code = run_with_tokio();
        std::process::exit(exit_code);
    } else {
        let exit_code = run_sync(cli);
        std::process::exit(exit_code);
    }
}

/// Create tokio runtime and run async path
fn run_with_tokio() -> i32 {
    let rt = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => {
            // NOTE: Using eprintln! here is intentional - tracing/event system
            // is not yet initialized at this point in startup.
            #[allow(clippy::print_stderr)]
            {
                eprintln!("Fatal error: Failed to create tokio runtime: {e}");
            }
            return 1;
        }
    };

    rt.block_on(run())
}

/// Determine if a command requires the async runtime
const fn requires_async_runtime(cli: &cli::Cli) -> bool {
    // Handle --llms flag (doesn't need async)
    if cli.llms {
        return false;
    }

    match &cli.command {
        None => false, // No subcommand - will show help/error
        Some(cmd) => match cmd {
            // Commands that DON'T need tokio (fast path)
            // Export uses sync fast path with lightweight runtime for performance
            // (shell prompt integration requires sub-10ms response time)
            cli::Commands::Version { .. }
            | cli::Commands::Info { .. }
            | cli::Commands::Build { .. }
            | cli::Commands::Completions { .. }
            | cli::Commands::Changeset { .. }
            | cli::Commands::Secrets { .. }
            | cli::Commands::Export { .. }
            | cli::Commands::Fmt { .. } => false,
            cli::Commands::Shell { subcommand } => match subcommand {
                cli::ShellCommands::Init { .. } => false,
            },
            cli::Commands::Release { subcommand } => match subcommand {
                // Version, Publish, and Prepare are sync (CUE/cargo/git operations)
                cli::ReleaseCommands::Version { .. }
                | cli::ReleaseCommands::Publish { .. }
                | cli::ReleaseCommands::Prepare { .. } => false,
                // Binaries needs async for HTTP/process execution
                cli::ReleaseCommands::Binaries { .. } => true,
            },
            cli::Commands::Env { subcommand } => match subcommand {
                // env status without --wait, print, and list are sync (CUE evaluation is sync FFI)
                cli::EnvCommands::Status { wait: false, .. }
                | cli::EnvCommands::Print { .. }
                | cli::EnvCommands::List { .. } => false,
                // Other env commands need async
                _ => true,
            },

            // Commands that NEED tokio
            cli::Commands::Task { .. }
            | cli::Commands::Exec { .. }
            | cli::Commands::Ci { .. }
            | cli::Commands::Tui
            | cli::Commands::Web { .. }
            | cli::Commands::Allow { .. }
            | cli::Commands::Deny { .. }
            | cli::Commands::Sync { .. }
            | cli::Commands::Runtime { .. }
            | cli::Commands::Up { .. }
            | cli::Commands::Down { .. }
            | cli::Commands::Logs { .. }
            | cli::Commands::Ps { .. }
            | cli::Commands::Restart { .. } => true,
            // Tools commands - download/activate need async, list is sync
            cli::Commands::Tools { subcommand } => match subcommand {
                cli::ToolsCommands::Download | cli::ToolsCommands::Activate => true,
                cli::ToolsCommands::List => false,
            },
        },
    }
}

/// Run synchronous commands without tokio runtime
/// This is the fast path for commands that don't need async
fn run_sync(cli: cli::Cli) -> i32 {
    // Set up signal handler for sync path
    let _ = ctrlc::set_handler(|| {
        // Terminate all child processes gracefully before exiting.
        // Need a mini runtime since terminate_all is async.
        if let Ok(rt) = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            rt.block_on(async {
                let registry = cuenv_core::tasks::global_registry();
                registry
                    .terminate_all(std::time::Duration::from_secs(3))
                    .await;
            });
        }

        cleanup_terminal();
        std::process::exit(EXIT_SIGINT);
    });

    // Initialize tracing for sync path (simpler than async path, no event bus needed)
    let log_level = match cli.level {
        tracing::LogLevel::Trace => Level::TRACE,
        tracing::LogLevel::Debug => Level::DEBUG,
        tracing::LogLevel::Info => Level::INFO,
        tracing::LogLevel::Warn => Level::WARN,
        tracing::LogLevel::Error => Level::ERROR,
    };
    let tracing_config = tracing::TracingConfig {
        format: if cli.json {
            tracing::TracingFormat::Json
        } else {
            tracing::TracingFormat::Pretty
        },
        level: log_level,
        ..Default::default()
    };
    // Ignore error if tracing already initialized (e.g., in tests)
    let _ = tracing::init_tracing(tracing_config);

    // Handle --llms flag
    if cli.llms {
        #[allow(clippy::print_stdout)] // LLMS_CONTENT is static documentation, no secrets
        {
            print!("{LLMS_CONTENT}");
        }
        return EXIT_OK;
    }

    let json_format = OutputFormat::from_json_flag(cli.json);

    // Ensure a subcommand was provided
    let Some(cli_command) = cli.command else {
        render_error(
            &CliError::config_with_help(
                "No subcommand provided",
                "Run 'cuenv --help' for usage information",
            ),
            json_format,
        );
        return exit_code_for(&CliError::config("No subcommand provided"));
    };

    // Handle completions command
    if let cli::Commands::Completions { shell } = &cli_command {
        cli::generate_completions(*shell);
        return EXIT_OK;
    }

    // Convert CLI command to internal command
    let command: Command = cli_command.into_command(cli.environment.clone());

    // Execute synchronously
    match execute_sync_command(command, json_format) {
        Ok(()) => EXIT_OK,
        Err(err) => {
            render_error(&err, json_format);
            exit_code_for(&err)
        }
    }
}

/// Execute commands synchronously (no tokio runtime)
#[allow(clippy::too_many_lines)] // Command dispatcher naturally has many cases
fn execute_sync_command(command: Command, json_format: cli::OutputFormat) -> Result<(), CliError> {
    match command {
        Command::Version { format: _ } => {
            let version_info = commands::version::get_version_info();
            #[allow(clippy::print_stdout)] // Version info contains no secrets
            {
                println!("{version_info}");
            }
            Ok(())
        }

        Command::Info {
            path,
            package,
            meta,
        } => {
            let options = commands::info::InfoOptions {
                path: path.as_deref(),
                package: &package,
                json_output: json_format.is_json(),
                with_meta: meta,
            };
            match commands::info::execute_info(options) {
                Ok(output) => {
                    cuenv_events::print_redacted(&output);
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Info command failed: {e}"),
                    "Check that you are in a CUE module with valid env.cue files",
                )),
            }
        }

        Command::ShellInit { shell } => execute_shell_init_command_safe(shell, json_format),

        Command::EnvStatus {
            path,
            package,
            wait: false,
            format,
            ..
        } => match commands::hooks::execute_env_status_sync(&path, &package, format) {
            Ok(output) => {
                if json_format.is_json() {
                    let envelope = OkEnvelope::new(serde_json::json!({
                        "status": output
                    }));
                    match serde_json::to_string(&envelope) {
                        Ok(json) => cuenv_events::println_redacted(&json),
                        Err(e) => {
                            return Err(CliError::other(format!("JSON serialization failed: {e}")));
                        }
                    }
                } else {
                    cuenv_events::println_redacted(&output);
                }
                Ok(())
            }
            Err(e) => Err(CliError::eval_with_help(
                format!("Env status failed: {e}"),
                "Check that your env.cue file exists",
            )),
        },

        Command::EnvPrint {
            path,
            package,
            format,
            environment,
        } => {
            // CUE evaluation is sync FFI, so we can call the async function via a mini runtime
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| CliError::other(format!("Runtime error: {e}")))?;

            let executor = create_executor(&package);
            rt.block_on(async {
                match commands::env::execute_env_print(
                    &path,
                    &format,
                    environment.as_deref(),
                    &executor,
                )
                .await
                {
                    Ok(result) => {
                        cuenv_events::println_redacted(&result);
                        Ok(())
                    }
                    Err(e) => {
                        let cli_err: CliError = e.into();
                        Err(cli_err.with_help("Check your CUE files and package configuration"))
                    }
                }
            })
        }

        Command::EnvList {
            path,
            package,
            format,
        } => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| CliError::other(format!("Runtime error: {e}")))?;

            let executor = create_executor(&package);
            rt.block_on(async {
                match commands::env::execute_env_list(&path, &format, &executor).await {
                    Ok(result) => {
                        cuenv_events::println_redacted(&result);
                        Ok(())
                    }
                    Err(e) => {
                        let cli_err: CliError = e.into();
                        Err(cli_err.with_help("Check your CUE files and package configuration"))
                    }
                }
            })
        }

        Command::ChangesetAdd {
            path,
            summary,
            description,
            packages,
        } => match commands::release::execute_changeset_add(
            &path,
            &packages,
            summary.as_deref(),
            description.as_deref(),
        ) {
            Ok(output) => {
                if json_format.is_json() {
                    let envelope = OkEnvelope::new(serde_json::json!({ "message": output }));
                    match serde_json::to_string(&envelope) {
                        Ok(json) => cuenv_events::println_redacted(&json),
                        Err(e) => {
                            return Err(CliError::other(format!("JSON serialization failed: {e}")));
                        }
                    }
                } else {
                    cuenv_events::println_redacted(&output);
                }
                Ok(())
            }
            Err(e) => Err(CliError::eval_with_help(
                format!("Changeset add failed: {e}"),
                "Check package names and bump types (major, minor, patch)",
            )),
        },

        Command::ChangesetStatus { path, json } => {
            let merged_format = OutputFormat::from_json_flag(json || json_format.is_json());
            match commands::release::execute_changeset_status_with_format(&path, merged_format) {
                Ok(output) => {
                    cuenv_events::println_redacted(&output);
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Changeset status failed: {e}"),
                    "Check that the path is valid",
                )),
            }
        }

        Command::ChangesetFromCommits { path, since } => {
            match commands::release::execute_changeset_from_commits(&path, since.as_deref()) {
                Ok(output) => {
                    if json_format.is_json() {
                        let envelope = OkEnvelope::new(serde_json::json!({ "message": output }));
                        match serde_json::to_string(&envelope) {
                            Ok(json) => cuenv_events::println_redacted(&json),
                            Err(e) => {
                                return Err(CliError::other(format!(
                                    "JSON serialization failed: {e}"
                                )));
                            }
                        }
                    } else {
                        cuenv_events::println_redacted(&output);
                    }
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Changeset from-commits failed: {e}"),
                    "Check that the path is a valid git repository",
                )),
            }
        }

        Command::ReleasePrepare {
            path,
            since,
            dry_run,
            branch,
            no_pr,
        } => {
            let opts = commands::release::ReleasePrepareOptions {
                path,
                since,
                dry_run,
                branch,
                no_pr,
            };
            match commands::release::execute_release_prepare(&opts) {
                Ok(output) => {
                    if json_format.is_json() {
                        let envelope = OkEnvelope::new(serde_json::json!({ "result": output }));
                        match serde_json::to_string(&envelope) {
                            Ok(json) => cuenv_events::println_redacted(&json),
                            Err(e) => {
                                return Err(CliError::other(format!(
                                    "JSON serialization failed: {e}"
                                )));
                            }
                        }
                    } else {
                        cuenv_events::println_redacted(&output);
                    }
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Release prepare failed: {e}"),
                    "Check git history and workspace configuration",
                )),
            }
        }

        Command::ReleaseVersion { path, dry_run } => {
            match commands::release::execute_release_version(&path, dry_run) {
                Ok(output) => {
                    if json_format.is_json() {
                        let envelope = OkEnvelope::new(serde_json::json!({ "result": output }));
                        match serde_json::to_string(&envelope) {
                            Ok(json) => cuenv_events::println_redacted(&json),
                            Err(e) => {
                                return Err(CliError::other(format!(
                                    "JSON serialization failed: {e}"
                                )));
                            }
                        }
                    } else {
                        cuenv_events::println_redacted(&output);
                    }
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Release version failed: {e}"),
                    "Create changesets first with 'cuenv changeset add'",
                )),
            }
        }

        Command::ReleasePublish { path, dry_run } => {
            let format = if json_format.is_json() {
                commands::release::OutputFormat::Json
            } else {
                commands::release::OutputFormat::Human
            };
            match commands::release::execute_release_publish(&path, dry_run, format) {
                Ok(output) => {
                    if json_format.is_json() {
                        let envelope = OkEnvelope::new(serde_json::json!({ "result": output }));
                        match serde_json::to_string(&envelope) {
                            Ok(json) => cuenv_events::println_redacted(&json),
                            Err(e) => {
                                return Err(CliError::other(format!(
                                    "JSON serialization failed: {e}"
                                )));
                            }
                        }
                    } else {
                        cuenv_events::println_redacted(&output);
                    }
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Release publish failed: {e}"),
                    "Check that packages are ready for publishing",
                )),
            }
        }

        Command::Completions { shell } => {
            cli::generate_completions(shell);
            Ok(())
        }

        Command::SecretsSetup { provider, wasm_url } => {
            commands::secrets::execute_secrets_setup(provider, wasm_url.as_deref())
        }

        Command::ToolsList => commands::tools::execute_tools_list(),

        Command::Fmt {
            path,
            package,
            fix,
            only,
        } => match commands::fmt::execute_fmt(&path, &package, fix, only.as_deref()) {
            Ok(output) => {
                cuenv_events::println_redacted(&output);
                Ok(())
            }
            Err(e) => Err(CliError::eval_with_help(
                format!("Format failed: {e}"),
                "Check your formatters configuration in env.cue",
            )),
        },

        Command::Export {
            shell,
            path,
            package,
        } => {
            // Try sync fast path first (handles no-env-cue, running, failed states)
            match commands::export::execute_export_sync(shell.as_deref(), &path, &package) {
                Ok(Some(output)) => {
                    // Fast path succeeded - output directly (may contain env vars)
                    cuenv_events::print_redacted(&output);
                    Ok(())
                }
                Ok(None) => {
                    // Need async path - use lightweight single-thread runtime
                    // (like EnvPrint does for CUE evaluation)
                    let rt = tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                        .map_err(|e| CliError::other(format!("Runtime error: {e}")))?;

                    rt.block_on(async {
                        match commands::export::execute_export(
                            shell.as_deref(),
                            &path,
                            &package,
                            None,
                        )
                        .await
                        {
                            Ok(result) => {
                                cuenv_events::print_redacted(&result);
                                Ok(())
                            }
                            Err(e) => {
                                let cli_err: CliError = e.into();
                                Err(cli_err.with_help("Check your CUE configuration"))
                            }
                        }
                    })
                }
                Err(e) => {
                    let cli_err: CliError = e.into();
                    Err(cli_err.with_help("Check your CUE configuration"))
                }
            }
        }

        // All other commands should have been routed to async path
        _ => Err(CliError::other(
            "Internal error: async command reached sync path",
        )),
    }
}

/// Main CLI runner that handles errors properly and returns exit codes
#[instrument(name = "cuenv_run")]
async fn run() -> i32 {
    // Use biased select to prefer signal handling over normal completion
    // This ensures cleanup runs even if the child process exits simultaneously
    tokio::select! {
        biased;

        _ = tokio::signal::ctrl_c() => {
            // Terminate all child processes gracefully before exiting
            let registry = cuenv_core::tasks::global_registry();
            registry.terminate_all(std::time::Duration::from_secs(5)).await;

            // Clean up terminal state to prevent escape sequence garbage
            cleanup_terminal();
            EXIT_SIGINT
        }
        result = real_main() => {
            match result {
                Ok(()) => EXIT_OK,
                Err(err) => {
                    // Try to determine if JSON mode was requested
                    let args: Vec<String> = std::env::args().collect();
                    let json_mode = args.iter().any(|arg| arg == "--json");

                    render_error(&err, OutputFormat::from_json_flag(json_mode));
                    exit_code_for(&err)
                }
            }
        }
    }
}

/// Clean up terminal state on interrupt.
/// This prevents escape sequence garbage from being printed when the user
/// presses Ctrl-C while terminal queries are in-flight.
fn cleanup_terminal() {
    use std::io::Write;

    let mut stdout = std::io::stdout();

    // Disable raw mode if it was enabled (e.g., by TUI)
    let _ = crossterm::terminal::disable_raw_mode();

    // Pop keyboard enhancement flags (kitty protocol) if enabled
    let _ = stdout.execute(crossterm::event::PopKeyboardEnhancementFlags);

    // Show cursor if it was hidden
    let _ = stdout.execute(crossterm::cursor::Show);

    // Leave alternate screen if we were in it
    let _ = stdout.execute(crossterm::terminal::LeaveAlternateScreen);

    // Flush to ensure all escape sequences are sent
    let _ = stdout.flush();

    // Drain any pending input from stdin to consume terminal responses
    // that might have been sent by child processes or terminal queries
    drain_stdin();
}

/// Drain pending input from stdin without blocking.
/// This consumes any terminal responses that are waiting in the input buffer.
fn drain_stdin() {
    use std::time::Duration;

    // Wait briefly for any in-flight terminal responses to arrive
    std::thread::sleep(Duration::from_millis(50));

    // Poll for events with short timeout to drain any pending input
    // This uses crossterm's event system which handles the non-blocking read safely
    while crossterm::event::poll(Duration::from_millis(10)).unwrap_or(false) {
        // Read and discard the event
        let _ = crossterm::event::read();
    }
}

/// Real main implementation that can return `CliError`
#[instrument(name = "cuenv_real_main")]
async fn real_main() -> Result<(), CliError> {
    // Handle shell completion requests first (before any other processing)
    // The shell calls us with special env vars to request completions
    if cli::try_complete() {
        return Ok(());
    }

    // Check if we're being called as a supervisor process
    let args: Vec<String> = std::env::args().collect();
    if args.len() > 1 && args[1] == "__hook-supervisor" {
        return run_hook_supervisor(args).await;
    }

    // Check if we're being called as the coordinator server
    if args.len() > 1 && args[1] == "__coordinator" {
        return run_coordinator().await;
    }

    // Parse CLI arguments and initialize event system
    let init_result = match initialize_cli_and_tracing().await {
        Ok(result) => result,
        Err(e) => {
            return Err(CliError::config_with_help(
                format!("Failed to parse CLI arguments: {e}"),
                "Check your command line arguments and try again",
            ));
        }
    };

    // Handle --llms flag (print LLM context and exit)
    if init_result.cli.llms {
        #[allow(clippy::print_stdout)] // LLMS_CONTENT is static documentation, no secrets
        {
            print!("{LLMS_CONTENT}");
        }
        return Ok(());
    }

    // Ensure a subcommand was provided
    let Some(cli_command) = init_result.cli.command else {
        return Err(CliError::config_with_help(
            "No subcommand provided",
            "Run 'cuenv --help' for usage information",
        ));
    };

    // Handle completions command specially (before converting to internal command)
    if let cli::Commands::Completions { shell } = &cli_command {
        cli::generate_completions(*shell);
        return Ok(());
    }

    // Create executor with the command's package for correct module caching.
    // Each command specifies its package (--package flag, defaults to "cuenv"),
    // and the executor caches the module evaluation for that specific package.
    let executor = create_executor(cli_command.package());

    // Convert CLI command to internal command, passing global environment
    let command: Command = cli_command.into_command(init_result.cli.environment.clone());

    // Execute the command with the shared executor for module caching
    let json_format = OutputFormat::from_json_flag(init_result.cli.json);
    let result = execute_command_safe(command, json_format, &executor).await;

    // Signal renderers to finish processing and exit gracefully
    cuenv_events::emit_shutdown!();

    // Wait for renderer to finish processing any remaining events
    if let Some(handle) = init_result.renderer_handle {
        // Give renderer time to process final events, then abort if stuck
        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), handle).await;
    }

    // Shut down the global event bus BEFORE the tokio runtime exits.
    // This closes the mpsc channel that the forwarding task waits on,
    // allowing the task to exit and preventing a runtime shutdown deadlock.
    tracing::shutdown_global_events();

    result
}

/// Result of CLI and tracing initialization
struct InitResult {
    cli: cli::Cli,
    /// Handle to the renderer task (if running).
    /// This handle should be awaited before program exit to ensure
    /// all events are properly rendered.
    renderer_handle: Option<tokio::task::JoinHandle<()>>,
}

/// Create a [`CommandExecutor`] with the given package name.
///
/// The executor provides centralized module evaluation - commands that need
/// CUE access can call `executor.get_module()` to get the cached evaluation.
fn create_executor(package: &str) -> Arc<CommandExecutor> {
    let (event_sender, _event_receiver) = tokio::sync::mpsc::unbounded_channel();
    Arc::new(CommandExecutor::new(event_sender, package.to_string()))
}

/// Initialize CLI parsing and tracing configuration
#[instrument(name = "cuenv_initialize_cli_and_tracing")]
async fn initialize_cli_and_tracing() -> Result<InitResult, CliError> {
    // Parse CLI arguments once
    let cli = parse();

    // Derive tracing configuration from parsed CLI
    // In normal mode, use Pretty which suppresses output unless DEBUG level
    // Dev format is verbose and always outputs - only use when explicitly requested
    let trace_format = if cli.json {
        TracingFormat::Json
    } else {
        TracingFormat::Pretty
    };

    let log_level = match cli.level {
        tracing::LogLevel::Trace => Level::TRACE,
        tracing::LogLevel::Debug => Level::DEBUG,
        tracing::LogLevel::Info => Level::INFO,
        tracing::LogLevel::Warn => Level::WARN,
        tracing::LogLevel::Error => Level::ERROR,
    };

    // Initialize enhanced tracing with event capture
    let tracing_config = TracingConfig {
        format: trace_format,
        level: log_level,
        ..Default::default()
    };

    // Initialize tracing and get the event receiver for the main renderer
    let receiver = match tracing::init_tracing_with_events(tracing_config) {
        Ok(rx) => rx,
        Err(e) => {
            return Err(CliError::config(format!(
                "Failed to initialize tracing: {e}"
            )));
        }
    };

    // Check if TUI mode is enabled (Task command with --tui flag)
    let tui_mode = matches!(&cli.command, Some(cli::Commands::Task { tui: true, .. }));

    // Spawn appropriate renderer based on output mode
    // Skip CLI renderer in TUI mode - TUI handles its own event rendering
    let renderer_handle = if cli.json {
        // JSON mode: output structured JSON events
        let renderer = JsonRenderer::new();
        Some(tokio::spawn(async move {
            renderer.run(receiver).await;
        }))
    } else if tui_mode {
        // TUI mode: don't spawn CLI renderer, TUI subscribes to events directly
        // Drop the receiver to avoid memory buildup
        drop(receiver);
        None
    } else {
        // CLI mode: pretty-print events to terminal
        let renderer = CliRenderer::new();
        Some(tokio::spawn(async move {
            renderer.run(receiver).await;
        }))
    };

    Ok(InitResult {
        cli,
        renderer_handle,
    })
}

/// Execute command safely without ? operator
///
/// Execute a command using the `CommandExecutor`.
///
/// Special commands (Tui, Web, Completions) are handled directly here since they
/// don't fit the standard command execution pattern. All other commands are delegated
/// to the executor's event-driven `execute()` method.
#[allow(clippy::too_many_lines)]
#[instrument(name = "cuenv_execute_command_safe", skip(executor))]
async fn execute_command_safe(
    command: Command,
    json_format: cli::OutputFormat,
    executor: &CommandExecutor,
) -> Result<(), CliError> {
    // Special commands that bypass the executor (they don't fit the event pattern)
    match &command {
        Command::Tui => {
            return execute_tui_command()
                .await
                .map_err(|e| CliError::other(e.to_string()));
        }
        Command::Web { port, host } => {
            return execute_web_command(*port, host.clone())
                .await
                .map_err(|e| CliError::other(e.to_string()));
        }
        Command::Completions { shell } => {
            // Completions are handled early in real_main, this is just for exhaustiveness
            cli::generate_completions(*shell);
            return Ok(());
        }
        Command::SecretsSetup { provider, wasm_url } => {
            // Secrets setup is handled early in real_main, this is just for exhaustiveness
            return commands::secrets::execute_secrets_setup(*provider, wasm_url.as_deref());
        }
        Command::RuntimeOciActivate => {
            return run_oci_activate().await;
        }
        Command::ToolsDownload => {
            return commands::tools::execute_tools_download().await;
        }
        Command::ToolsActivate => {
            return commands::tools::execute_tools_activate();
        }
        Command::ToolsList => {
            return commands::tools::execute_tools_list();
        }
        Command::Build {
            path,
            package,
            names,
            labels,
        } => {
            let options = commands::build::BuildOptions {
                path: path.clone(),
                package: package.clone(),
                names: names.clone(),
                labels: labels.clone(),
            };
            return commands::build::execute_build(&options, executor)
                .map_err(|e| CliError::eval(format!("Build command failed: {e}")));
        }
        Command::Up {
            path,
            package,
            services,
            labels,
            environment,
        } => {
            let options = commands::up::UpOptions {
                path: path.clone(),
                package: package.clone(),
                services: services.clone(),
                labels: labels.clone(),
                environment: environment.clone(),
            };
            return commands::up::execute_up(&options, executor)
                .await
                .map_err(|e| CliError::eval(format!("Up command failed: {e}")));
        }
        Command::Down {
            path,
            package,
            services,
        } => {
            let options = commands::down::DownOptions {
                path: path.clone(),
                package: package.clone(),
                services: services.clone(),
            };
            return commands::down::execute_down(&options)
                .map(|_| ())
                .map_err(|e| CliError::eval(format!("Down command failed: {e}")));
        }
        Command::Logs {
            path,
            package,
            services,
            follow,
            lines,
        } => {
            let options = commands::logs::LogsOptions {
                path: path.clone(),
                package: package.clone(),
                services: services.clone(),
                follow: *follow,
                lines: *lines,
            };
            return commands::logs::execute_logs(&options)
                .map(|_| ())
                .map_err(|e| CliError::eval(format!("Logs command failed: {e}")));
        }
        Command::Ps {
            path,
            package,
            output_format,
        } => {
            let options = commands::ps::PsOptions {
                path: path.clone(),
                package: package.clone(),
                output_format: output_format.clone(),
            };
            return commands::ps::execute_ps(&options)
                .map(|_| ())
                .map_err(|e| CliError::eval(format!("Ps command failed: {e}")));
        }
        Command::Restart {
            path,
            package,
            services,
        } => {
            let options = commands::restart::RestartOptions {
                path: path.clone(),
                package: package.clone(),
                services: services.clone(),
            };
            return commands::restart::execute_restart(&options)
                .map(|_| ())
                .map_err(|e| CliError::eval(format!("Restart command failed: {e}")));
        }
        // Info command needs special handling for json_format and output
        Command::Info {
            path,
            package,
            meta,
        } => {
            let options = commands::info::InfoOptions {
                path: path.as_deref(),
                package,
                json_output: json_format.is_json(),
                with_meta: *meta,
            };
            return match commands::info::execute_info(options) {
                Ok(output) => {
                    cuenv_events::print_redacted(&output);
                    Ok(())
                }
                Err(e) => Err(CliError::eval_with_help(
                    format!("Info command failed: {e}"),
                    "Check that you are in a CUE module with valid env.cue files",
                )),
            };
        }
        // Changeset commands need special handling for json_format
        Command::ChangesetAdd {
            path,
            summary,
            description,
            packages,
        } => {
            return execute_changeset_add_safe(
                path.clone(),
                summary.clone(),
                description.clone(),
                packages.clone(),
                json_format,
            )
            .await;
        }
        Command::ChangesetStatus { path, json } => {
            let merged_format = OutputFormat::from_json_flag(*json || json_format.is_json());
            return execute_changeset_status_safe(path.clone(), merged_format).await;
        }
        Command::ChangesetFromCommits { path, since } => {
            return execute_changeset_from_commits_safe(path.clone(), since.clone(), json_format)
                .await;
        }
        Command::ReleasePrepare {
            path,
            since,
            dry_run,
            branch,
            no_pr,
        } => {
            return execute_release_prepare_safe(
                path.clone(),
                since.clone(),
                *dry_run,
                branch.clone(),
                *no_pr,
                json_format,
            )
            .await;
        }
        Command::ReleaseVersion { path, dry_run } => {
            return execute_release_version_safe(path.clone(), *dry_run, json_format).await;
        }
        Command::ReleasePublish { path, dry_run } => {
            return execute_release_publish_safe(path.clone(), *dry_run, json_format).await;
        }
        Command::ReleaseBinaries {
            path,
            dry_run,
            backends,
            build_only,
            package_only,
            publish_only,
            targets,
            version,
        } => {
            use commands::release::{ReleaseBinariesOptions, ReleaseBinariesPhase};

            let phase = if *build_only {
                ReleaseBinariesPhase::Build
            } else if *package_only {
                ReleaseBinariesPhase::Package
            } else if *publish_only {
                ReleaseBinariesPhase::Publish
            } else {
                ReleaseBinariesPhase::Full
            };

            let opts = ReleaseBinariesOptions::new(path.clone())
                .with_dry_run(*dry_run)
                .with_backends(backends.clone())
                .with_phase(phase)
                .with_targets(targets.clone())
                .with_version(version.clone());

            return execute_release_binaries_safe(opts, json_format).await;
        }
        _ => {}
    }

    // All other commands go through the executor's event-driven execute() method
    // Use the proper From conversion to preserve error type semantics
    executor.execute(command).await.map_err(|e| {
        let cli_err: CliError = e.into();
        cli_err.with_help("Run with --help for usage information")
    })
}

/// Execute TUI command - starts interactive event dashboard
#[instrument(name = "cuenv_execute_tui")]
async fn execute_tui_command() -> Result<(), CliError> {
    use coordinator::client::CoordinatorClient;
    use coordinator::protocol::UiType;

    // Connect to coordinator as a TUI consumer
    let Ok(mut client) = CoordinatorClient::connect_as_consumer(UiType::Tui).await else {
        return Err(CliError::other(
            "No cuenv coordinator is running.\n\n\
             The TUI connects to an event coordinator to display events from other cuenv commands.\n\
             To use the TUI:\n\
             1. Run a cuenv command (e.g., 'cuenv t') in another terminal\n\
             2. Then run 'cuenv tui' to watch the events\n\n\
             Note: The coordinator is started automatically when running task commands."
                .to_string(),
        ));
    };

    cuenv_events::emit_command_started!("tui");

    // Run the TUI event viewer
    match tui::run_event_viewer(&mut client).await {
        Ok(()) => {
            cuenv_events::emit_command_completed!("tui", true, 0_u64);
            Ok(())
        }
        Err(e) => {
            cuenv_events::emit_command_completed!("tui", false, 0_u64);
            Err(CliError::other(format!("TUI error: {e}")))
        }
    }
}

/// Execute Web command - starts web server for event streaming
#[instrument(name = "cuenv_execute_web")]
async fn execute_web_command(port: u16, host: String) -> Result<(), CliError> {
    cuenv_events::emit_command_started!("web");

    // For now, just print a placeholder message
    // Full web server implementation would require adding a web framework dependency
    cuenv_events::emit_stdout!(format!(
        "Web server would start on http://{}:{}\nThis feature is not yet implemented.",
        host, port
    ));

    cuenv_events::emit_command_completed!("web", true, 0_u64);
    Ok(())
}

/// Execute shell init command safely
#[instrument(name = "cuenv_execute_shell_init_safe")]
fn execute_shell_init_command_safe(
    shell: cli::ShellType,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    let output = commands::hooks::execute_shell_init(shell);

    if json_format.is_json() {
        let envelope = OkEnvelope::new(serde_json::json!({
            "script": output
        }));
        match serde_json::to_string(&envelope) {
            Ok(json) => cuenv_events::println_redacted(&json),
            Err(e) => return Err(CliError::other(format!("JSON serialization failed: {e}"))),
        }
    } else {
        cuenv_events::println_redacted(&output);
    }
    Ok(())
}

/// Run as the coordinator server (internal - spawned by discovery)
async fn run_coordinator() -> Result<(), CliError> {
    use coordinator::server::EventCoordinator;

    let coordinator = EventCoordinator::new();
    coordinator
        .run()
        .await
        .map_err(|e| CliError::other(format!("Coordinator failed: {e}")))
}

/// Run OCI binary activation (`cuenv runtime oci activate`).
///
/// Reads the lockfile, pulls/extracts binaries for the current platform,
/// and outputs PATH modifications to stdout (to be sourced by the hook system).
///
/// This command is typically invoked by the `#OCIActivate` hook defined in
/// `schema/oci.cue` to add OCI-managed binaries to the PATH.
async fn run_oci_activate() -> Result<(), CliError> {
    use cuenv_core::lockfile::{ArtifactKind, Lockfile};
    use cuenv_tools_oci::{OciCache, OciClient, current_platform};
    use std::collections::HashSet;

    // Find the lockfile by walking up from current directory
    let lockfile_path = find_lockfile().ok_or_else(|| {
        CliError::config_with_help(
            "No cuenv.lock found",
            "Run 'cuenv sync lock' to create the lockfile",
        )
    })?;

    // Load the lockfile
    let lockfile = Lockfile::load(&lockfile_path)
        .map_err(|e| CliError::other(format!("Failed to load lockfile: {e}")))?
        .ok_or_else(|| {
            CliError::config_with_help(
                "Lockfile is empty",
                "Run 'cuenv sync lock' to populate the lockfile",
            )
        })?;

    // Get current platform
    let platform = current_platform();
    let platform_str = platform.to_string();

    // Initialize OCI client and cache
    let client = OciClient::new();
    let cache = OciCache::default();
    cache
        .ensure_dirs()
        .map_err(|e| CliError::other(format!("Failed to create cache directories: {e}")))?;

    // Track directories to add to PATH
    let mut bin_dirs: HashSet<PathBuf> = HashSet::new();

    for artifact in &lockfile.artifacts {
        // Check if this artifact has data for our platform
        let Some(platform_data) = artifact.platforms.get(&platform_str) else {
            // Skip artifacts not available for this platform
            continue;
        };

        match &artifact.kind {
            ArtifactKind::Image { image } => {
                let digest = &platform_data.digest;
                let binary_name = extract_binary_name_from_image(image);

                // Check if binary is already cached
                if let Some(cached_path) = cache.get_binary(digest, &binary_name) {
                    if let Some(parent) = cached_path.parent() {
                        bin_dirs.insert(parent.to_path_buf());
                    }
                    continue;
                }

                // Need to pull and extract
                let resolved = client.resolve_digest(image, &platform).await.map_err(|e| {
                    CliError::other(format!("Failed to resolve '{}': {}", image, e))
                })?;

                let layer_paths = client.pull_layers(&resolved, &cache).await.map_err(|e| {
                    CliError::other(format!("Failed to pull layers for '{}': {}", image, e))
                })?;

                // Extract binary - requires explicit path in CUE config
                // For now, skip OCI images without explicit extract paths
                if layer_paths.is_empty() {
                    #[allow(clippy::print_stderr)] // Diagnostic warning, no secrets
                    {
                        eprintln!("Warning: OCI image '{}' has no layers to extract", image);
                    }
                    continue;
                }

                let dest = cache.binary_path(digest, &binary_name);
                if let Some(parent) = dest.parent() {
                    bin_dirs.insert(parent.to_path_buf());
                }
            }
        }
    }

    // Output PATH modification
    if !bin_dirs.is_empty() {
        let path_additions: Vec<String> =
            bin_dirs.iter().map(|p| p.display().to_string()).collect();
        #[allow(clippy::print_stdout)] // PATH export contains no secrets
        {
            println!("export PATH=\"{}:$PATH\"", path_additions.join(":"));
        }
    }

    Ok(())
}

/// Find the lockfile by walking up from current directory
fn find_lockfile() -> Option<PathBuf> {
    use cuenv_core::lockfile::LOCKFILE_NAME;

    let mut current = std::env::current_dir().ok()?;
    loop {
        let lockfile_path = current.join(LOCKFILE_NAME);
        if lockfile_path.exists() {
            return Some(lockfile_path);
        }

        // Also check in cue.mod directory
        let cue_mod_lockfile = current.join("cue.mod").join(LOCKFILE_NAME);
        if cue_mod_lockfile.exists() {
            return Some(cue_mod_lockfile);
        }

        if !current.pop() {
            return None;
        }
    }
}

/// Extract binary name from image reference
///
/// For example: `nginx:1.25-alpine` -> `nginx`
/// Extracts the last path component before the tag.
fn extract_binary_name_from_image(image: &str) -> String {
    // Remove tag/digest suffix
    let without_tag = image.split(':').next().unwrap_or(image);
    let without_digest = without_tag.split('@').next().unwrap_or(without_tag);

    // Get last path component
    without_digest
        .rsplit('/')
        .next()
        .unwrap_or("binary")
        .to_string()
}

/// Run as a hook supervisor process
#[allow(clippy::too_many_lines)]
async fn run_hook_supervisor(args: Vec<String>) -> Result<(), CliError> {
    // Parse supervisor arguments
    let mut directory_path = PathBuf::new();
    let mut instance_hash = String::new();
    let mut hooks_file = PathBuf::new();
    let mut config_file = PathBuf::new();

    let mut i = 2; // Skip program name and "__hook-supervisor"
    while i < args.len() {
        match args[i].as_str() {
            "--directory" => {
                directory_path = PathBuf::from(&args[i + 1]);
                i += 2;
            }
            "--instance-hash" => {
                instance_hash.clone_from(&args[i + 1]);
                i += 2;
            }
            "--config-hash" => {
                // Config hash is passed but not currently used in supervisor
                i += 2;
            }
            "--hooks-file" => {
                hooks_file = PathBuf::from(&args[i + 1]);
                i += 2;
            }
            "--config-file" => {
                config_file = PathBuf::from(&args[i + 1]);
                i += 2;
            }
            _ => i += 1,
        }
    }

    // Initialize basic logging for supervisor to stderr
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .try_init();

    // Change to the target directory so hooks run in the correct context
    if let Err(e) = std::env::set_current_dir(&directory_path) {
        cuenv_events::emit_supervisor_log!(
            "supervisor",
            format!(
                "Failed to change directory to {}: {}",
                directory_path.display(),
                e
            )
        );
        return Err(CliError::other(format!("Failed to change directory: {e}")));
    }

    cuenv_events::emit_supervisor_log!("supervisor", format!("Starting with args: {args:?}"));
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!("Directory: {}", directory_path.display())
    );
    cuenv_events::emit_supervisor_log!("supervisor", format!("Instance hash: {instance_hash}"));
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!("Hooks file: {}", hooks_file.display())
    );
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!("Config file: {}", config_file.display())
    );

    // Read and deserialize hooks and config from files
    let hooks_json = std::fs::read_to_string(&hooks_file)
        .map_err(|e| CliError::other(format!("Failed to read hooks file: {e}")))?;
    let config_json = std::fs::read_to_string(&config_file)
        .map_err(|e| CliError::other(format!("Failed to read config file: {e}")))?;

    let hooks: Vec<Hook> = serde_json::from_str(&hooks_json)
        .map_err(|e| CliError::other(format!("Failed to deserialize hooks: {e}")))?;
    let config: HookExecutionConfig = serde_json::from_str(&config_json)
        .map_err(|e| CliError::other(format!("Failed to deserialize config: {e}")))?;

    // Clean up temp files after reading
    std::fs::remove_file(&hooks_file).ok();
    std::fs::remove_file(&config_file).ok();

    // Write PID file
    let state_dir = match config.state_dir.clone() {
        Some(dir) => dir,
        None => StateManager::default_state_dir()
            .map_err(|e| CliError::other(format!("failed to get default state dir: {e}")))?,
    };
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!("Using state dir: {}", state_dir.display())
    );
    let state_manager = StateManager::new(state_dir);
    let state_file = state_manager.get_state_file_path(&instance_hash);
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!("Looking for state file: {}", state_file.display())
    );

    let pid_file = state_file.with_extension("pid");
    std::fs::write(&pid_file, format!("{}", std::process::id()))
        .map_err(|e| CliError::other(format!("Failed to write PID file: {e}")))?;

    // Load the current state
    let mut state = state_manager
        .load_state(&instance_hash)
        .await
        .map_err(|e| CliError::other(format!("Failed to load state: {e}")))?
        .ok_or_else(|| CliError::other("State not found for supervisor"))?;

    // Execute the hooks
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!(
            "Executing {} hooks for directory: {}",
            hooks.len(),
            directory_path.display()
        )
    );
    let result = execute_hooks(hooks, &directory_path, &config, &state_manager, &mut state).await;

    if let Err(e) = result {
        cuenv_events::emit_supervisor_log!("supervisor", format!("Hook execution failed: {e}"));
        state.status = ExecutionStatus::Failed;
        state.error_message = Some(e.to_string());
        state.finished_at = Some(chrono::Utc::now());
        state_manager
            .save_state(&state)
            .await
            .map_err(|e| CliError::other(format!("Failed to save error state: {e}")))?;
        return Err(CliError::other(format!("Hook execution failed: {e}")));
    }

    // Save the final state with environment variables from source hooks
    cuenv_events::emit_supervisor_log!(
        "supervisor",
        format!(
            "Saving final state with {} environment variables",
            state.environment_vars.len()
        )
    );
    state_manager
        .save_state(&state)
        .await
        .map_err(|e| CliError::other(format!("Failed to save final state: {e}")))?;

    // Clean up PID file
    std::fs::remove_file(&pid_file).ok();

    cuenv_events::emit_supervisor_log!("supervisor", "Completed successfully");
    Ok(())
}

/// Execute changeset add command safely
#[instrument(name = "cuenv_execute_changeset_add_safe")]
async fn execute_changeset_add_safe(
    path: String,
    summary: Option<String>,
    description: Option<String>,
    packages: Vec<(String, String)>,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    match commands::release::execute_changeset_add(
        &path,
        &packages,
        summary.as_deref(),
        description.as_deref(),
    ) {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "message": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Changeset add failed: {e}"),
            "Check package names and bump types (major, minor, patch)",
        )),
    }
}

/// Execute changeset status command safely
#[instrument(name = "cuenv_execute_changeset_status_safe")]
async fn execute_changeset_status_safe(
    path: String,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    // Use the format-aware function that returns proper JSON structure
    match commands::release::execute_changeset_status_with_format(&path, json_format) {
        Ok(output) => {
            cuenv_events::println_redacted(&output);
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Changeset status failed: {e}"),
            "Check that the path is valid",
        )),
    }
}

/// Execute changeset from-commits command safely
#[instrument(name = "cuenv_execute_changeset_from_commits_safe")]
async fn execute_changeset_from_commits_safe(
    path: String,
    since: Option<String>,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    match commands::release::execute_changeset_from_commits(&path, since.as_deref()) {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "message": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Changeset from-commits failed: {e}"),
            "Check that the path is a valid git repository",
        )),
    }
}

/// Execute release prepare command safely
#[instrument(name = "cuenv_execute_release_prepare_safe")]
async fn execute_release_prepare_safe(
    path: String,
    since: Option<String>,
    dry_run: cuenv_core::DryRun,
    branch: String,
    no_pr: bool,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    let opts = commands::release::ReleasePrepareOptions {
        path,
        since,
        dry_run,
        branch,
        no_pr,
    };
    match commands::release::execute_release_prepare(&opts) {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "result": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Release prepare failed: {e}"),
            "Check git history and workspace configuration",
        )),
    }
}

/// Execute release version command safely
#[instrument(name = "cuenv_execute_release_version_safe")]
async fn execute_release_version_safe(
    path: String,
    dry_run: cuenv_core::DryRun,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    match commands::release::execute_release_version(&path, dry_run) {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "result": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Release version failed: {e}"),
            "Create changesets first with 'cuenv changeset add'",
        )),
    }
}

/// Execute release publish command safely
#[instrument(name = "cuenv_execute_release_publish_safe")]
async fn execute_release_publish_safe(
    path: String,
    dry_run: cuenv_core::DryRun,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    // Use Human format for CLI, JSON can be accessed via --json flag
    let format = if json_format.is_json() {
        commands::release::OutputFormat::Json
    } else {
        commands::release::OutputFormat::Human
    };
    match commands::release::execute_release_publish(&path, dry_run, format) {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "result": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Release publish failed: {e}"),
            "Check that packages are ready for publishing",
        )),
    }
}

async fn execute_release_binaries_safe(
    opts: commands::release::ReleaseBinariesOptions,
    json_format: cli::OutputFormat,
) -> Result<(), CliError> {
    match commands::release::execute_release_binaries(opts).await {
        Ok(output) => {
            if json_format.is_json() {
                let envelope = OkEnvelope::new(serde_json::json!({
                    "result": output
                }));
                match serde_json::to_string(&envelope) {
                    Ok(json) => cuenv_events::println_redacted(&json),
                    Err(e) => {
                        return Err(CliError::other(format!("JSON serialization failed: {e}")));
                    }
                }
            } else {
                cuenv_events::println_redacted(&output);
            }
            Ok(())
        }
        Err(e) => Err(CliError::eval_with_help(
            format!("Release binaries failed: {e}"),
            "Check that binaries are built and artifacts directory exists",
        )),
    }
}

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

    #[test]
    fn test_panic_hook() {
        // Test that panic hook is properly set
        // Note: We can't easily test the panic hook directly
        // Just verify that we can set and take a hook
        let _ = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let _ = std::panic::take_hook();
        // Test passes if no panic occurs
    }

    #[test]
    fn test_cli_args_json_flag() {
        let cli_args = ["cuenv".to_string(), "--json".to_string()];
        let json_flag = cli_args.iter().any(|arg| arg == "--json");
        assert!(json_flag);
    }

    #[test]
    fn test_cli_args_level_flag() {
        let cli_args = [
            "cuenv".to_string(),
            "--level".to_string(),
            "debug".to_string(),
        ];
        let level_flag = cli_args.windows(2).find_map(|args| {
            if args[0] == "--level" || args[0] == "-l" {
                Some(args[1].as_str())
            } else {
                None
            }
        });
        assert_eq!(level_flag, Some("debug"));
    }

    #[test]
    fn test_trace_format_selection() {
        let json_flag = true;
        let trace_format = if json_flag {
            TracingFormat::Json
        } else {
            TracingFormat::Pretty
        };
        assert!(matches!(trace_format, TracingFormat::Json));

        let json_flag = false;
        let trace_format = if json_flag {
            TracingFormat::Json
        } else {
            TracingFormat::Pretty
        };
        assert!(matches!(trace_format, TracingFormat::Pretty));
    }

    #[test]
    fn test_log_level_parsing() {
        let test_cases = vec![
            (Some("trace"), Level::TRACE),
            (Some("debug"), Level::DEBUG),
            (Some("info"), Level::INFO),
            (Some("warn"), Level::WARN),
            (Some("error"), Level::ERROR),
            (None, Level::WARN),            // Default
            (Some("invalid"), Level::WARN), // Invalid falls back to default
        ];

        for (input, expected) in test_cases {
            let log_level = match input {
                Some("trace") => Level::TRACE,
                Some("debug") => Level::DEBUG,
                Some("info") => Level::INFO,
                Some("error") => Level::ERROR,
                _ => Level::WARN,
            };
            assert_eq!(log_level, expected);
        }
    }

    #[test]
    fn test_tracing_config_default() {
        let tracing_config = TracingConfig {
            format: TracingFormat::Dev,
            level: Level::WARN,
            ..Default::default()
        };
        assert!(matches!(tracing_config.format, TracingFormat::Dev));
        assert_eq!(tracing_config.level, Level::WARN);
    }

    #[tokio::test]
    async fn test_command_conversion() {
        use cli::{Commands, OutputFormat};

        // Test Version command conversion
        let cli_command = Commands::Version {
            output_format: OutputFormat::Text,
        };
        let command: Command = cli_command.into_command(None);
        match command {
            Command::Version { format } => assert_eq!(format, "text"),
            _ => panic!("Expected Command::Version"),
        }
    }
}