complior-cli 1.0.1

AI Act Compliance Scanner & Fixer — CLI
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
// V1-M30.11: CI re-trigger marker (post-merge engine + Rust verification).
// Merge commit's Rust Clippy was cancelled by docs-only follow-up; touch-trigger
// re-runs all Rust jobs. See engine/core/src/index.ts for context.
// V1-M30.9: CI re-trigger marker (post-merge engine + Rust verification).
// See engine/core/src/index.ts for context. paths-filter triggers Rust job.
// V1-M30.8a+b: CI re-trigger marker (post-merge engine + Rust verification).
// See engine/core/src/index.ts for context. paths-filter triggers Rust job.
// V1-M30.7: CI re-trigger marker (post-merge engine + Rust verification).
// See engine/core/src/index.ts for context — both files prepended together
// so paths-filter runs both Rust + Engine jobs in one CI invocation.
// V1-M30.6: CI re-trigger marker (post-merge engine + Rust verification).
// See engine/core/src/index.ts for context — both files prepended together
// so paths-filter runs both Rust + Engine jobs in one CI invocation.
// TUI-only modules
#[cfg(feature = "tui")]
mod animation;
#[cfg(feature = "tui")]
mod app;
#[cfg(feature = "tui")]
mod chat_stream;
#[cfg(feature = "tui")]
mod components;
#[cfg(feature = "tui")]
mod input;
#[cfg(feature = "tui")]
mod layout;
#[cfg(feature = "tui")]
mod obligations;
#[cfg(feature = "tui")]
mod session;
#[cfg(feature = "tui")]
mod theme;
#[cfg(feature = "tui")]
mod theme_picker;
#[cfg(feature = "tui")]
mod views;
#[cfg(feature = "tui")]
mod watcher;
#[cfg(feature = "tui")]
mod widgets;

// Extras-only modules
#[cfg(feature = "extras")]
mod saas_client;

// Core modules (always available)
mod cli;
mod config;
mod contract_test;
mod daemon;
mod engine_client;
mod engine_process;
mod error;
mod headless;
mod types;

// LLM settings (TUI overlay + types)
#[cfg(feature = "tui")]
mod llm_settings;

use std::io;
#[cfg(feature = "tui")]
use std::io::Write as _;

use clap::{CommandFactory, Parser};

use config::load_config;
use engine_process::EngineManager;

#[cfg(feature = "tui")]
use app::executor::execute_command;
#[cfg(feature = "tui")]
use app::{App, AppCommand};
#[cfg(feature = "tui")]
use crossterm::event::{DisableMouseCapture, EnableMouseCapture, Event, EventStream};
#[cfg(feature = "tui")]
use crossterm::execute;
#[cfg(feature = "tui")]
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
#[cfg(feature = "tui")]
use futures_util::StreamExt;
#[cfg(feature = "tui")]
use ratatui::Terminal;
#[cfg(feature = "tui")]
use ratatui::backend::CrosstermBackend;
#[cfg(feature = "tui")]
use std::time::Duration;
#[cfg(feature = "tui")]
use tokio::sync::mpsc;
#[cfg(feature = "tui")]
use views::dashboard::render_dashboard;

#[tokio::main]
#[allow(clippy::too_many_lines)]
async fn main() -> color_eyre::Result<()> {
    color_eyre::install()?;
    tracing_subscriber::fmt()
        .with_env_filter("complior_cli=info")
        .with_writer(io::stderr)
        .init();

    let mut config = load_config();

    // Parse CLI args with clap
    let parsed_cli = cli::Cli::parse();
    #[cfg(feature = "tui")]
    let resume = parsed_cli.resume;
    config.engine_url_override = parsed_cli.engine_url.clone();

    // Apply --no-color: set env var so OnceLock picks it up
    if parsed_cli.no_color {
        // SAFETY: This runs single-threaded before any other threads start,
        // and before the OnceLock for color/unicode detection is initialized.
        unsafe {
            std::env::set_var("NO_COLOR", "1");
        }
    }

    // Apply theme from CLI if provided
    if let Some(ref theme_name) = parsed_cli.theme {
        config.theme = theme_name.clone();
    }

    // Auto-discover daemon port from PID file (if no --engine-url override)
    if config.engine_url_override.is_none() {
        let project_path = std::env::current_dir().unwrap_or_default();
        if let Some(info) = daemon::find_running_daemon(&project_path) {
            config.engine_url_override = Some(format!("http://127.0.0.1:{}", info.port));
        }
    }

    // Handle headless commands (non-TUI)
    if cli::is_headless(&parsed_cli) {
        // Auto-launch engine for commands that need it (skip for version/update/daemon/login/logout)
        let mut engine_guard: Option<EngineManager> = None;
        if config.engine_url_override.is_none() && cli::needs_engine(&parsed_cli) {
            let project_path = cli::explicit_project_path(&parsed_cli)
                .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
            let mut mgr = if let Ok(dir) = std::env::var("COMPLIOR_ENGINE_DIR") {
                EngineManager::from_engine_dir(std::path::Path::new(&dir))
            } else {
                let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                    .parent()
                    .unwrap_or_else(|| std::path::Path::new("."));
                EngineManager::new(workspace_root)
            }
            .with_project_path(&project_path);
            // Read-only commands (doctor) skip PID file to avoid creating .complior/
            let start_result = if cli::wants_pid_file(&parsed_cli) {
                let pid_path = daemon::pid_file_path(&project_path);
                mgr.start_with_pid(&pid_path, false)
            } else {
                mgr.start()
            };
            match start_result {
                Ok(port) => {
                    config.engine_url_override = Some(format!("http://127.0.0.1:{port}"));
                    let client =
                        engine_client::EngineClient::from_url(&format!("http://127.0.0.1:{port}"));
                    if !cli::wants_quiet_startup(&parsed_cli) {
                        eprintln!("Starting engine on port {port}...");
                    }
                    if mgr.wait_for_ready(&client).await {
                        engine_guard = Some(mgr);
                    } else {
                        eprintln!("Error: Engine failed to become ready");
                        drop(mgr);
                        std::process::exit(1);
                    }
                }
                Err(e) => {
                    eprintln!("Error: Cannot auto-start engine: {e}");
                    eprintln!("Try: complior daemon");
                    std::process::exit(1);
                }
            }
        }

        // Ensure engine cleanup on Ctrl+C (SIGINT doesn't call destructors)
        #[cfg(unix)]
        if let Some(pid) = engine_guard.as_ref().and_then(EngineManager::child_pid) {
            let pid = pid as i32;
            tokio::spawn(async move {
                let _ = tokio::signal::ctrl_c().await;
                eprintln!("\nInterrupted. Stopping engine...");
                unsafe {
                    libc::kill(-pid, libc::SIGTERM);
                }
                std::thread::sleep(std::time::Duration::from_millis(300));
                unsafe {
                    libc::kill(-pid, libc::SIGKILL);
                }
                std::process::exit(130);
            });
        }

        let code: i32 = match &parsed_cli.command {
            Some(cli::Command::Scan {
                ci,
                json,
                sarif,
                no_tui,
                threshold,
                fail_on,
                diff,
                fail_on_regression,
                comment,
                deep,
                llm,
                cloud,
                quiet,
                agent,
                path,
            }) => {
                if let Some(base_branch) = diff {
                    headless::scan::run_scan_diff(
                        base_branch,
                        *json,
                        *fail_on_regression,
                        *comment,
                        path.as_deref(),
                        &config,
                    )
                    .await
                } else {
                    headless::run_headless_scan(
                        *ci,
                        *json,
                        *sarif,
                        *no_tui,
                        *threshold,
                        *fail_on,
                        *deep,
                        *llm,
                        *cloud,
                        *quiet,
                        agent.as_deref(),
                        path.as_deref(),
                        &config,
                    )
                    .await
                }
            }
            Some(cli::Command::Fix {
                dry_run,
                json,
                ai,
                source,
                check_id,
                doc,
                agent,
                path,
            }) => {
                // --doc flag: delegate to document generation
                if let Some(ref doc_type) = *doc {
                    headless::fix::run_doc_generate_fix(
                        doc_type,
                        agent.as_deref(),
                        *json,
                        path.as_deref(),
                        &config,
                    )
                    .await
                } else {
                    match source {
                        cli::FixSource::Eval => {
                            headless::eval::run_eval_fix(*dry_run, *json, path.as_deref(), &config)
                                .await
                        }
                        cli::FixSource::All => {
                            let scan_code = headless::run_headless_fix(
                                *dry_run,
                                *json,
                                path.as_deref(),
                                &config,
                                *ai,
                            )
                            .await;
                            let eval_code = headless::eval::run_eval_fix(
                                *dry_run,
                                *json,
                                path.as_deref(),
                                &config,
                            )
                            .await;
                            if scan_code != 0 { scan_code } else { eval_code }
                        }
                        cli::FixSource::Scan => {
                            if let Some(cid) = check_id {
                                headless::fix::run_fix_single(
                                    cid,
                                    *json,
                                    path.as_deref(),
                                    &config,
                                    *ai,
                                )
                                .await
                            } else {
                                headless::run_headless_fix(
                                    *dry_run,
                                    *json,
                                    path.as_deref(),
                                    &config,
                                    *ai,
                                )
                                .await
                            }
                        }
                    }
                }
            }
            Some(cli::Command::Version) => {
                headless::run_version();
                0
            }
            Some(cli::Command::Doctor { .. }) => headless::run_doctor(&config).await,
            Some(cli::Command::Status { json, path }) => {
                headless::run_headless_status(*json, path.as_deref(), &config).await
            }
            Some(cli::Command::Report {
                format,
                output,
                json,
                share,
                path,
            }) => {
                let effective_format = if *json { "json" } else { format.as_str() };
                headless::run_report(
                    effective_format,
                    output.as_deref(),
                    path.as_deref(),
                    *share,
                    &config,
                )
                .await
            }
            Some(cli::Command::Init { force, path }) => {
                headless::run_init(path.as_deref(), parsed_cli.yes, *force, &config).await
            }
            Some(cli::Command::Update) => {
                headless::run_update().await;
                0
            }
            Some(cli::Command::Completions { shell }) => {
                clap_complete::generate(
                    *shell,
                    &mut cli::Cli::command(),
                    "complior",
                    &mut std::io::stdout(),
                );
                0
            }
            Some(cli::Command::Daemon { action, watch }) => {
                let project_path = std::env::current_dir().unwrap_or_default();
                headless::daemon::run_daemon(action.as_ref(), *watch, &project_path, &config).await;
                0
            }
            Some(cli::Command::Agent { action }) => {
                headless::passport::run_passport_command(action, &config).await
            }
            Some(cli::Command::Passport { action }) => {
                // V1-M30.4 B.1: `passport` is now a deprecated alias for `agent`.
                // Print a one-line yellow warning to stderr (so JSON/SARIF stdout
                // remains valid for CI consumers) but still dispatch to the same
                // handler so existing scripts keep working.
                eprintln!(
                    "\x1b[33m⚠ Deprecated: 'complior passport' is now 'complior agent'. \
                     The 'passport' alias will be removed in v2.0.0.\x1b[0m"
                );
                headless::passport::run_passport_command(action, &config).await
            }
            Some(cli::Command::Eval {
                target,
                det,
                llm,
                security,
                full,
                agent,
                categories,
                json,
                ci,
                threshold,
                model,
                api_key,
                request_template,
                response_path,
                headers,
                last,
                failures,
                verbose,
                concurrency,
                no_remediation,
                remediation,
                fix,
                dry_run,
                path,
            }) => {
                if *last {
                    headless::eval::run_eval_last(*json, *failures, *ci, *threshold, &config).await
                } else if let Some(target_raw) = target {
                    // T-12: Strip protocol hints (openai://, anthropic://, ollama://)
                    // so they become valid HTTP(S) URLs for the engine's parseProtocolHint().
                    let normalized_target = if let Some(stripped) = target_raw
                        .strip_prefix("openai://")
                        .or_else(|| target_raw.strip_prefix("anthropic://"))
                        .or_else(|| target_raw.strip_prefix("ollama://"))
                    {
                        if stripped.starts_with("http://") || stripped.starts_with("https://") {
                            stripped.to_string()
                        } else {
                            format!("http://{stripped}")
                        }
                    } else {
                        target_raw.clone()
                    };

                    if !normalized_target.starts_with("http://")
                        && !normalized_target.starts_with("https://")
                    {
                        eprintln!(
                            "Error: eval target must be an HTTP(S) URL, got: {normalized_target}"
                        );
                        eprintln!();
                        eprintln!("Usage: complior eval <url> [--det] [--llm] [--security]");
                        eprintln!("Example: complior eval http://localhost:4000/api/chat");
                        eprintln!(
                            "Note: openai://, anthropic://, ollama:// protocol hints are supported."
                        );
                        eprintln!();
                        eprintln!("Eval tests a running AI endpoint dynamically.");
                        eprintln!(
                            "To scan local source code, use: complior scan {normalized_target}"
                        );
                        1
                    } else if *fix {
                        // Run eval then apply fixes
                        let code = headless::eval::run_eval_command(
                            &normalized_target,
                            *det,
                            *llm,
                            *security,
                            *full,
                            agent.as_deref(),
                            categories,
                            *json,
                            *ci,
                            *threshold,
                            model.as_deref(),
                            api_key.as_deref(),
                            request_template.as_deref(),
                            response_path.as_deref(),
                            headers.as_deref(),
                            *verbose,
                            *concurrency,
                            *no_remediation,
                            *remediation,
                            path.as_deref(),
                            &config,
                        )
                        .await;
                        if code == 0 {
                            headless::eval::run_eval_fix(*dry_run, *json, path.as_deref(), &config)
                                .await
                        } else {
                            code
                        }
                    } else {
                        headless::eval::run_eval_command(
                            &normalized_target,
                            *det,
                            *llm,
                            *security,
                            *full,
                            agent.as_deref(),
                            categories,
                            *json,
                            *ci,
                            *threshold,
                            model.as_deref(),
                            api_key.as_deref(),
                            request_template.as_deref(),
                            response_path.as_deref(),
                            headers.as_deref(),
                            *verbose,
                            *concurrency,
                            *no_remediation,
                            *remediation,
                            path.as_deref(),
                            &config,
                        )
                        .await
                    }
                } else {
                    eprintln!("Error: <target> is required unless --last is used");
                    eprintln!("Usage: complior eval <url> [--det] [--llm] [--security]");
                    1
                }
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Chat {
                message,
                json,
                model,
            }) => headless::chat::run_chat(message, *json, model.as_deref(), &config).await,
            #[cfg(feature = "extras")]
            Some(cli::Command::Cert { action }) => {
                headless::cert::run_cert_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::SupplyChain { json, models, path }) => {
                headless::supply_chain::run_supply_chain(*json, *models, path.as_deref(), &config)
                    .await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Cost {
                hourly_rate,
                agent,
                json,
            }) => headless::cost::run_cost(*hourly_rate, agent.as_deref(), *json, &config).await,
            #[cfg(feature = "extras")]
            Some(cli::Command::Debt { json, trend }) => {
                headless::debt::run_debt(*json, *trend, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Simulate {
                fix,
                add_doc,
                complete_passport,
                json,
            }) => {
                headless::simulate::run_simulate(fix, add_doc, complete_passport, *json, &config)
                    .await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Login) => match headless::run_login(&config).await {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("Login failed: {e}");
                    1
                }
            },
            #[cfg(feature = "extras")]
            Some(cli::Command::Logout) => match headless::run_logout(&config).await {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("Logout failed: {e}");
                    1
                }
            },
            #[cfg(feature = "extras")]
            Some(cli::Command::Sync {
                passport,
                scan,
                docs,
                audit,
                evidence,
                registry,
                ..
            }) => {
                headless::run_sync(
                    *passport, *scan, *docs, *audit, *evidence, *registry, &config,
                )
                .await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Doc { action }) => {
                headless::doc::run_doc_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Jurisdiction { action }) => {
                headless::jurisdiction::run_jurisdiction_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Proxy { action }) => {
                headless::proxy::run_proxy_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Import { action }) => {
                headless::import::run_import_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Redteam { action }) => {
                headless::redteam::run_redteam_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Tools { action }) => {
                headless::tools::run_tools_command(action, &config).await
            }
            #[cfg(feature = "extras")]
            Some(cli::Command::Audit {
                target,
                agent,
                json,
                path,
            }) => {
                headless::audit::run_audit_command(
                    target,
                    agent.as_deref(),
                    *json,
                    path.as_deref(),
                    &config,
                )
                .await
            }
            None => unreachable!(),
        };

        drop(engine_guard);
        std::process::exit(code);
    }

    // Without TUI feature, no-subcommand = show help
    #[cfg(not(feature = "tui"))]
    {
        eprintln!("Complior v{}", env!("CARGO_PKG_VERSION"));
        eprintln!("Run 'complior --help' for available commands");
        eprintln!("Core pipeline: complior init -> scan -> eval -> fix");
        std::process::exit(0);
    }

    // === TUI startup (only compiled with `tui` feature) ===
    #[cfg(feature = "tui")]
    {
        // Initialize theme from config
        theme::init_theme(&config.theme);

        // Engine manager: auto-launch or external
        // Workspace root is parent of cli/ (CARGO_MANIFEST_DIR at compile time)
        let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap_or_else(|| std::path::Path::new("."));

        #[allow(clippy::option_if_let_else)]
        let mut engine_mgr = if let Some(ref url) = config.engine_url_override {
            // External mode — extract port for display
            let port = url
                .rsplit(':')
                .next()
                .and_then(|p| p.trim_end_matches('/').parse::<u16>().ok())
                .unwrap_or(3099);
            EngineManager::external(port)
        } else {
            // Check for existing daemon before auto-launching
            let project_path = std::env::current_dir().unwrap_or_default();
            if let Some(info) = daemon::find_running_daemon(&project_path) {
                // Reuse existing daemon (External mode — won't be killed on TUI exit)
                tracing::info!("Found daemon on port {} (PID {})", info.port, info.pid);
                EngineManager::external(info.port)
            } else {
                // Auto-launch with PID file so other instances can discover it
                let mut mgr = EngineManager::new(workspace_root).with_project_path(&project_path);
                let pid_path = daemon::pid_file_path(&project_path);
                match mgr.start_with_pid(&pid_path, config.watch_on_start) {
                    Ok(port) => {
                        tracing::info!("Engine auto-launched on port {port}");
                    }
                    Err(e) => {
                        tracing::warn!("Failed to auto-launch engine: {e}");
                        // Fall through — will use default port from config
                    }
                }
                mgr
            }
        };

        // Create app with engine URL (either auto-launched or override)
        let effective_url = config.engine_url_override.clone().unwrap_or_else(|| {
            if engine_mgr.port > 0 {
                engine_mgr.engine_url()
            } else {
                config.engine_url()
            }
        });

        let mut app = App::new(config.clone());
        // Override engine client with the effective URL
        app.engine_client = engine_client::EngineClient::from_url(&effective_url);
        // Start splash animation (only in production, not in tests)
        app.animation.start_splash();

        // Check for --resume flag
        if resume && let Ok(data) = session::load_session("latest").await {
            app.load_session_data(data);
            tracing::info!("Resumed session 'latest'");
        }

        // Parse --yes flag for non-interactive onboarding
        let skip_onboarding = parsed_cli.yes || std::env::var("CI").is_ok();

        // Show onboarding on first run, or provider setup if no providers
        if !config.onboarding_completed && !skip_onboarding {
            // Check for partial resume
            let wiz = if let Some(last_step) = config.onboarding_last_step {
                crate::views::onboarding::OnboardingWizard::resume(last_step)
            } else {
                crate::views::onboarding::OnboardingWizard::new()
            };
            app.onboarding = Some(wiz);
            app.overlay = types::Overlay::Onboarding;
        } else if !config.onboarding_completed && skip_onboarding {
            // --yes or CI: apply defaults and mark complete
            config::mark_onboarding_complete().await;
            app.config.onboarding_completed = true;
        }

        // Build initial file tree
        app.load_file_tree().await;

        // Setup terminal
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
        // Enable xterm modifyOtherKeys mode 2 — makes Shift+Enter distinguishable
        // Works in tmux 3.2+ (unlike Kitty CSI u protocol)
        let _ = stdout.write_all(b"\x1b[>4;2m");
        let _ = stdout.flush();
        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend)?;
        terminal.clear()?;

        // Wait for engine if we auto-launched it
        if engine_mgr.status == engine_process::EngineProcessStatus::Starting {
            app.engine_status = types::EngineConnectionStatus::Connecting;
            app.messages.push(types::ChatMessage::new(
                types::MessageRole::System,
                "Starting engine...".to_string(),
            ));

            // Render once to show "Starting engine..."
            terminal.draw(|frame| render_dashboard(frame, &app))?;

            if engine_mgr.wait_for_ready(&app.engine_client).await {
                app.engine_status = types::EngineConnectionStatus::Connected;
                app.messages.push(types::ChatMessage::new(
                    types::MessageRole::System,
                    format!("Engine ready on port {}.", engine_mgr.port),
                ));
            } else {
                app.engine_status = types::EngineConnectionStatus::Disconnected;
                app.messages.push(types::ChatMessage::new(
                    types::MessageRole::System,
                    "Engine failed to start. Use /reconnect or restart.".to_string(),
                ));
            }
        }

        // Run the event loop
        let result = run_event_loop(&mut terminal, &mut app, &mut engine_mgr).await;

        // Shutdown engine
        engine_mgr.shutdown();

        // Auto-save session on exit
        if let Err(e) = session::save_session(&app.to_session_data(), "latest").await {
            tracing::warn!("Failed to save session: {e}");
        }

        // Restore terminal
        disable_raw_mode()?;
        // Disable modifyOtherKeys
        let _ = execute!(
            terminal.backend_mut(),
            crossterm::style::Print("\x1b[>4;0m")
        );
        execute!(
            terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        )?;
        terminal.show_cursor()?;

        result?;
    }

    #[allow(unreachable_code)]
    Ok(())
}

#[cfg(feature = "tui")]
async fn run_event_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    engine_mgr: &mut EngineManager,
) -> color_eyre::Result<()> {
    let mut event_stream = EventStream::new();
    let tick_rate = Duration::from_millis(app.config.tick_rate_ms);
    let mut tick_interval = tokio::time::interval(tick_rate);

    // Animation tick: 50ms (20fps) — only fires when animations are active
    let mut anim_interval = tokio::time::interval(Duration::from_millis(50));

    // Watch mode channel + handle
    let (watch_tx, mut watch_rx) = mpsc::unbounded_channel::<std::path::PathBuf>();
    let mut watch_handle: Option<tokio::task::JoinHandle<()>> = None;

    // Background command results channel (non-blocking async operations)
    let mut bg_rx = app.take_bg_rx();

    // Try to connect to engine (if we haven't already from auto-launch)
    if app.engine_status != types::EngineConnectionStatus::Connected {
        match app.engine_client.status().await {
            Ok(status) if status.ready => {
                app.engine_status = types::EngineConnectionStatus::Connected;
                app.messages.push(types::ChatMessage::new(
                    types::MessageRole::System,
                    "Connected to engine.".to_string(),
                ));
            }
            _ => {
                app.engine_status = types::EngineConnectionStatus::Disconnected;
                app.messages.push(types::ChatMessage::new(
                    types::MessageRole::System,
                    "Engine not running. Try: complior daemon".to_string(),
                ));
            }
        }
    }

    // Auto-start watch if configured
    if app.config.watch_on_start {
        watch_handle = Some(watcher::spawn_watcher(
            app.project_path.clone(),
            watch_tx.clone(),
        ));
        app.watch_active = true;
        app.messages.push(types::ChatMessage::new(
            types::MessageRole::System,
            "Watch mode started (auto).".to_string(),
        ));
    }

    // Load framework scores + dashboard metrics on startup if connected
    if app.engine_status == types::EngineConnectionStatus::Connected {
        execute_command(
            app,
            AppCommand::LoadFrameworkScores,
            &watch_tx,
            &mut watch_handle,
        )
        .await;
        execute_command(
            app,
            AppCommand::LoadDashboardMetrics,
            &watch_tx,
            &mut watch_handle,
        )
        .await;
    }

    // Tick counter for periodic health checks (~5s at 250ms tick)
    let mut tick_count: u32 = 0;
    let health_check_interval: u32 = 20; // 20 ticks × 250ms = 5s

    while app.running {
        // Compute click areas for mouse support
        if let Ok(size) = crossterm::terminal::size() {
            app.rebuild_click_areas(size.0, size.1);
        }

        // Render
        terminal.draw(|frame| render_dashboard(frame, app))?;

        // Event multiplexing
        tokio::select! {
            // Terminal events (keyboard/mouse)
            maybe_event = event_stream.next() => {
                match maybe_event {
                    Some(Ok(Event::Key(key))) => {
                        let action = input::handle_key_event(key, app);
                        if let Some(cmd) = app.apply_action(action) {
                            execute_command(app, cmd, &watch_tx, &mut watch_handle).await;
                        }
                    }
                    Some(Ok(Event::Mouse(mouse))) => {
                        let action = input::handle_mouse_event(mouse, app);
                        if let Some(cmd) = app.apply_action(action) {
                            execute_command(app, cmd, &watch_tx, &mut watch_handle).await;
                        }
                    }
                    Some(Ok(Event::Resize(_w, _h))) => {
                        // Resize handled naturally by ratatui on next render
                    }
                    _ => {
                        // Other events — terminal re-renders on next loop
                    }
                }
            }

            // Background command results (non-blocking async operations)
            Some(bg_cmd) = bg_rx.recv() => {
                execute_command(app, bg_cmd, &watch_tx, &mut watch_handle).await;
            }

            // File watch events
            Some(path) = watch_rx.recv(), if app.watch_active => {
                app.push_activity(types::ActivityKind::Watch, path.display().to_string());
                execute_command(app, AppCommand::AutoScan, &watch_tx, &mut watch_handle).await;
            }

            // Tick for general state + health checks (250ms)
            _ = tick_interval.tick() => {
                if let Some(cmd) = app.tick() {
                    execute_command(app, cmd, &watch_tx, &mut watch_handle).await;
                }

                tick_count += 1;

                // Periodic engine health check
                if tick_count.is_multiple_of(health_check_interval)
                    && !engine_mgr.is_alive()
                    && engine_mgr.status == engine_process::EngineProcessStatus::Stopped
                {
                    tracing::warn!("Engine process died, attempting restart");
                    match engine_mgr.try_restart() {
                        Ok(port) => {
                            app.engine_client = engine_client::EngineClient::from_url(
                                &format!("http://127.0.0.1:{port}"),
                            );
                            app.engine_status = types::EngineConnectionStatus::Connecting;
                            app.messages.push(types::ChatMessage::new(
                                types::MessageRole::System,
                                format!("Engine restarting on port {port}..."),
                            ));
                        }
                        Err(e) => {
                            app.engine_status = types::EngineConnectionStatus::Error;
                            app.messages.push(types::ChatMessage::new(
                                types::MessageRole::System,
                                format!("Engine restart failed: {e}"),
                            ));
                        }
                    }
                }
            }

            // Animation tick (50ms, 20fps) — only when animations active
            _ = anim_interval.tick(), if app.animation.active() => {
                app.animation.step();
            }
        }
    }

    // Clean up watcher on exit
    if let Some(handle) = watch_handle.take() {
        handle.abort();
    }

    Ok(())
}