complior-cli 1.0.0

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
mod actions;
mod commands;
pub mod executor;
mod overlays;
mod scan;
mod tests;
mod view_keys;

use std::path::PathBuf;
use std::time::Instant;

use ratatui::layout::Rect;

use crate::animation::AnimationState;
use crate::components::spinner::Spinner;
use crate::components::suggestions::IdleSuggestionState;
use crate::components::undo_history::UndoHistoryState;
use crate::config::TuiConfig;
use crate::engine_client::EngineClient;
use crate::layout::Breakpoint;
use crate::saas_client::SyncStats;
use crate::types::{
    ActivityEntry, ActivityKind, ChatBlock, ChatMessage, ClickTarget, CostEstimateResult,
    DebtResult, EngineConnectionStatus, FileEntry, InputMode, LlmSessionConfig, MessageRole, Mode,
    MultiFrameworkScoreResult, Overlay, Panel, ReadinessResult, ScanResult, Selection,
    StreamingState, ViewState,
};
use crate::views::file_browser;
use crate::views::fix::FixViewState;
use crate::views::obligations::ObligationsViewState;
use crate::views::passport::PassportViewState;
use crate::views::report::ReportViewState;
use crate::views::scan::ScanViewState;
use crate::views::timeline::TimelineViewState;

#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct SyncState {
    pub authenticated: bool,
    pub user_email: Option<String>,
    pub org_name: Option<String>,
    pub last_sync: Option<String>,
    pub stats: Option<SyncStats>,
}

pub struct App {
    // Core state
    pub running: bool,
    pub active_panel: Panel,
    pub input_mode: InputMode,
    pub config: TuiConfig,
    pub view_state: ViewState,
    pub mode: Mode,

    // Engine
    pub engine_status: EngineConnectionStatus,
    pub engine_client: EngineClient,

    // Status Log (system messages)
    pub messages: Vec<ChatMessage>,
    pub input: String,
    pub input_cursor: usize,
    pub chat_scroll: usize,
    pub chat_auto_scroll: bool,

    // Input history (separate from chat messages)
    pub input_history: Vec<String>,
    pub history_index: Option<usize>,
    pub history_saved_input: String, // saved input when navigating history

    // Score
    pub last_scan: Option<ScanResult>,
    pub score_history: Vec<f64>,

    // File browser
    pub file_tree: Vec<FileEntry>,
    pub file_browser_index: usize,

    // Code viewer
    pub code_content: Option<String>,
    pub open_file_path: Option<String>,
    pub code_scroll: usize,
    pub selection: Option<Selection>,

    // Terminal
    pub terminal_output: Vec<String>,
    pub terminal_visible: bool,
    pub terminal_scroll: usize,
    pub terminal_auto_scroll: bool,

    // Panels visibility
    pub sidebar_visible: bool,
    pub files_panel_visible: bool,

    // Overlay popups
    pub overlay: Overlay,
    pub overlay_filter: String,
    pub palette_index: usize,

    // View-specific state
    pub scan_view: ScanViewState,
    pub fix_view: FixViewState,
    pub timeline_view: TimelineViewState,
    pub report_view: ReportViewState,
    pub passport_view: PassportViewState,
    pub obligations_view: ObligationsViewState,

    // Activity log (Dashboard widget)
    pub activity_log: Vec<ActivityEntry>,

    // Watch mode
    pub watch_active: bool,
    pub watch_last_score: Option<f64>,

    // T904: Pre-fix score for auto-validate delta
    pub pre_fix_score: Option<f64>,

    // Help overlay scroll
    pub help_scroll: usize,

    // Theme picker
    pub theme_picker: Option<crate::theme_picker::ThemePickerState>,

    // Onboarding wizard
    pub onboarding: Option<crate::views::onboarding::OnboardingWizard>,

    // Code viewer search
    pub code_search_query: Option<String>,
    pub code_search_matches: Vec<usize>,
    pub code_search_current: usize,

    // T07: Toast notifications
    pub toasts: crate::components::toast::ToastStack,

    // T07: Confirmation dialog
    pub confirm_dialog: Option<crate::components::confirm_dialog::ConfirmDialog>,

    // T07: Widget zoom
    pub zoom: crate::components::zoom::ZoomState,

    // T07: Fix split ratio (percentage for left panel, 25-75)
    pub fix_split_pct: u16,

    // T07: Complior Zen
    pub zen_messages_used: u32,
    pub zen_messages_limit: u32,
    pub zen_active: bool,

    // T07: Dismiss modal
    pub dismiss_modal: Option<crate::components::quick_actions::DismissModal>,

    // T08: Mouse click areas (populated each render frame)
    pub click_areas: Vec<(Rect, ClickTarget)>,
    pub scroll_events: Vec<Instant>,

    // T08: Undo history
    pub undo_history: UndoHistoryState,

    // T08: Colon-command mode
    pub colon_mode: bool,

    // T08: Idle suggestions
    pub idle_suggestions: IdleSuggestionState,

    // T08: Animations
    pub animation: AnimationState,

    // T09: What-If scenario state
    pub whatif: crate::components::whatif::WhatIfState,

    // UI
    pub spinner: Spinner,
    pub project_path: PathBuf,
    pub operation_start: Option<Instant>,

    // Multi-framework scores (E-105, E-106, E-107)
    pub framework_scores: Option<MultiFrameworkScoreResult>,
    /// Focused framework index (None = all cards, Some(idx) = single gauge)
    pub focused_framework: Option<usize>,

    // Dashboard metrics (S05: Cost, Debt, Readiness)
    pub cost_estimate: Option<CostEstimateResult>,
    pub debt_score: Option<DebtResult>,
    pub readiness_score: Option<ReadinessResult>,

    // SaaS sync state
    pub sync_state: SyncState,

    // LLM chat streaming state
    pub streaming: StreamingState,
    pub llm_config: LlmSessionConfig,
    pub llm_settings: Option<crate::llm_settings::LlmSettingsState>,
    pub chat_cancel: Option<std::sync::Arc<tokio::sync::Notify>>,

    // Background command channel (for async results → event loop)
    pub bg_tx: tokio::sync::mpsc::UnboundedSender<AppCommand>,
    bg_rx: Option<tokio::sync::mpsc::UnboundedReceiver<AppCommand>>,
}

const MAX_HISTORY: usize = 50;
const MAX_TERMINAL_LINES: usize = 1000;
const MAX_ACTIVITY_LOG: usize = 10;

impl App {
    pub fn new(config: TuiConfig) -> Self {
        let engine_client = EngineClient::new(&config);
        let (bg_tx, bg_rx) = tokio::sync::mpsc::unbounded_channel();
        let sidebar_visible = config.sidebar_visible;
        let animations_enabled = config.animations_enabled;
        let llm_config = LlmSessionConfig {
            api_key: config
                .llm_provider
                .as_deref()
                .and_then(crate::config::load_llm_api_key),
            provider: config.llm_provider.clone(),
            model: config.llm_model.clone(),
        };
        let project_path = config.project_path.as_deref().map_or_else(
            || std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            PathBuf::from,
        );

        let mut app = Self {
            running: true,
            active_panel: Panel::Chat,
            input_mode: InputMode::Normal,
            config,
            view_state: ViewState::Dashboard,
            mode: Mode::Scan,
            engine_status: EngineConnectionStatus::Disconnected,
            engine_client,
            messages: vec![ChatMessage::new(
                MessageRole::System,
                "Welcome to Complior. Use /scan to start, /help for commands.".to_string(),
            )],
            input: String::new(),
            input_cursor: 0,
            chat_scroll: 0,
            chat_auto_scroll: true,
            input_history: Vec::new(),
            history_index: None,
            history_saved_input: String::new(),
            last_scan: None,
            score_history: Vec::new(),
            file_tree: Vec::new(),
            file_browser_index: 0,
            code_content: None,
            open_file_path: None,
            code_scroll: 0,
            selection: None,
            terminal_output: Vec::new(),
            terminal_visible: false,
            terminal_scroll: 0,
            terminal_auto_scroll: true,
            sidebar_visible,
            files_panel_visible: true,
            overlay: Overlay::None,
            overlay_filter: String::new(),
            palette_index: 0,
            scan_view: ScanViewState::default(),
            fix_view: FixViewState::default(),
            timeline_view: TimelineViewState::default(),
            report_view: ReportViewState::default(),
            passport_view: PassportViewState::default(),
            obligations_view: ObligationsViewState::default(),
            activity_log: Vec::new(),
            watch_active: false,
            watch_last_score: None,
            pre_fix_score: None,
            help_scroll: 0,
            theme_picker: None,
            onboarding: None,
            code_search_query: None,
            code_search_matches: Vec::new(),
            code_search_current: 0,
            toasts: crate::components::toast::ToastStack::new(),
            confirm_dialog: None,
            zoom: crate::components::zoom::ZoomState::new(),
            fix_split_pct: 40,
            zen_messages_used: 0,
            zen_messages_limit: 1000,
            zen_active: false,
            dismiss_modal: None,
            click_areas: Vec::new(),
            scroll_events: Vec::new(),
            undo_history: UndoHistoryState::new(),
            colon_mode: false,
            idle_suggestions: IdleSuggestionState::new(),
            animation: AnimationState::new(animations_enabled),
            framework_scores: None,
            focused_framework: None,
            cost_estimate: None,
            debt_score: None,
            readiness_score: None,
            whatif: crate::components::whatif::WhatIfState::new(),
            spinner: Spinner::new(),
            project_path,
            operation_start: None,
            sync_state: SyncState::default(),
            streaming: StreamingState::default(),
            llm_config,
            llm_settings: None,
            chat_cancel: None,
            bg_tx,
            bg_rx: Some(bg_rx),
        };

        // Initialize sync state from saved tokens
        if let Some(tokens) = crate::config::load_tokens() {
            app.sync_state.authenticated = crate::config::is_authenticated();
            app.sync_state.user_email = tokens.user_email;
            app.sync_state.org_name = tokens.org_name;
        }

        app
    }

    /// Take the background command receiver (call once from event loop).
    pub const fn take_bg_rx(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<AppCommand> {
        self.bg_rx.take().expect("bg_rx already taken")
    }

    pub fn tick(&mut self) -> Option<AppCommand> {
        self.spinner.advance();
        self.toasts.gc();

        // Idle suggestion: check if idle > 10s and no blockers
        if self.idle_suggestions.current.is_none()
            && self.idle_suggestions.is_idle(10)
            && !self.scan_view.scanning
            && self.overlay == Overlay::None
            && self.input_mode != InputMode::Insert
            && !self.idle_suggestions.recently_dismissed()
            && !self.idle_suggestions.fetch_pending
        {
            // Mark fetch as pending so we don't re-trigger every tick
            self.idle_suggestions.fetch_pending = true;
            return Some(AppCommand::FetchSuggestions);
        }
        None
    }

    /// Elapsed seconds since operation started.
    pub fn elapsed_secs(&self) -> Option<u64> {
        self.operation_start.map(|s| s.elapsed().as_secs())
    }

    /// Rebuild mouse click targets based on current terminal size and view state.
    pub fn rebuild_click_areas(&mut self, width: u16, height: u16) {
        use crate::types::ClickTarget;
        self.click_areas.clear();

        // Footer view tabs — letter-key tabs across the bottom line
        let footer_y = height.saturating_sub(1);
        let tab_width: u16 = 10;
        for (i, view) in ViewState::ALL.iter().enumerate() {
            let x = (i as u16) * tab_width;
            if x + tab_width <= width {
                self.click_areas.push((
                    Rect::new(x, footer_y, tab_width, 1),
                    ClickTarget::ViewTab(*view),
                ));
            }
        }

        // Sidebar area (if visible) — click on sidebar to toggle
        let bp = crate::layout::Breakpoint::from_width(width);
        if bp.show_sidebar() && self.sidebar_visible {
            let sb_w = bp.sidebar_width();
            let sb_x = width.saturating_sub(sb_w);
            self.click_areas.push((
                Rect::new(sb_x, 0, sb_w, height.saturating_sub(2)),
                ClickTarget::SidebarToggle,
            ));
        }

        // Scan view: finding rows
        if self.view_state == ViewState::Scan {
            let count = self.last_scan.as_ref().map_or(0, |s| s.findings.len());
            let start_y: u16 = 5; // approximate start of findings list
            for i in 0..count.min(20) {
                self.click_areas.push((
                    Rect::new(0, start_y + i as u16, width / 2, 1),
                    ClickTarget::FindingRow(i),
                ));
            }
        }

        // Fix view: checkboxes
        if self.view_state == ViewState::Fix {
            let start_y: u16 = 3;
            for i in 0..self.fix_view.fixable_findings.len().min(20) {
                self.click_areas.push((
                    Rect::new(0, start_y + i as u16, width / 2, 1),
                    ClickTarget::FixCheckbox(i),
                ));
            }
        }
    }

    pub const fn next_panel(&mut self) {
        self.active_panel = match self.active_panel {
            Panel::Chat => Panel::Score,
            Panel::Score => {
                if self.code_content.is_some() {
                    Panel::CodeViewer
                } else {
                    Panel::FileBrowser
                }
            }
            Panel::FileBrowser | Panel::CodeViewer => {
                if self.terminal_visible {
                    Panel::Terminal
                } else {
                    Panel::Chat
                }
            }
            Panel::Terminal => Panel::Chat,
            Panel::DiffPreview => Panel::Chat,
        };
    }

    fn push_to_history(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        // Don't duplicate consecutive entries
        if self.input_history.last().is_some_and(|last| last == text) {
            return;
        }
        self.input_history.push(text.to_string());
        if self.input_history.len() > MAX_HISTORY {
            self.input_history.remove(0);
        }
        self.history_index = None;
    }

    pub fn history_up(&mut self) {
        if self.input_history.is_empty() {
            return;
        }
        match self.history_index {
            None => {
                self.history_saved_input = self.input.clone();
                self.history_index = Some(self.input_history.len() - 1);
            }
            Some(0) => return,
            Some(i) => self.history_index = Some(i - 1),
        }
        if let Some(i) = self.history_index {
            self.input = self.input_history[i].clone();
            self.input_cursor = self.input.len();
        }
    }

    pub fn history_down(&mut self) {
        let Some(i) = self.history_index else {
            return;
        };
        if i + 1 >= self.input_history.len() {
            // Back to saved input
            self.history_index = None;
            self.input = std::mem::take(&mut self.history_saved_input);
            self.input_cursor = self.input.len();
        } else {
            self.history_index = Some(i + 1);
            self.input = self.input_history[i + 1].clone();
            self.input_cursor = self.input.len();
        }
    }

    pub fn add_terminal_line(&mut self, line: String) {
        self.terminal_output.push(line);
        if self.terminal_output.len() > MAX_TERMINAL_LINES {
            self.terminal_output.remove(0);
        }
        if self.terminal_auto_scroll {
            self.terminal_scroll = self.terminal_output.len().saturating_sub(1);
        }
    }

    pub fn push_activity(&mut self, kind: ActivityKind, detail: impl Into<String>) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let hours = (now % 86400) / 3600;
        let mins = (now % 3600) / 60;
        let timestamp = format!("{hours:02}:{mins:02}");

        self.activity_log.push(ActivityEntry {
            timestamp,
            kind,
            detail: detail.into(),
        });
        if self.activity_log.len() > MAX_ACTIVITY_LOG {
            self.activity_log.remove(0);
        }
    }

    pub async fn load_file_tree(&mut self) {
        let path = self.project_path.clone();
        if let Ok(tree) =
            tokio::task::spawn_blocking(move || file_browser::build_file_tree(&path)).await
        {
            self.file_tree = tree;
        }
    }

    pub fn open_file(&mut self, path: &str, content: String) {
        self.push_activity(ActivityKind::Scan, path.to_string());
        self.code_content = Some(content);
        self.open_file_path = Some(path.to_string());
        self.code_scroll = 0;
        self.selection = None;
        self.active_panel = Panel::CodeViewer;
    }

    pub fn to_session_data(&self) -> crate::session::SessionData {
        crate::session::SessionData {
            messages: self.messages.clone(),
            score_history: self.score_history.clone(),
            open_file_path: self.open_file_path.clone(),
            terminal_output: self
                .terminal_output
                .iter()
                .rev()
                .take(100)
                .rev()
                .cloned()
                .collect(),
            last_scan: self.last_scan.clone(),
        }
    }

    pub fn load_session_data(&mut self, data: crate::session::SessionData) {
        self.messages = data.messages;
        self.score_history = data.score_history;
        self.open_file_path = data.open_file_path;
        self.terminal_output = data.terminal_output;
        self.last_scan = data.last_scan;
    }

    /// Returns true when the app is performing a blocking operation and idle
    /// suggestions should be suppressed (T08: responsive widget selection).
    pub fn is_busy(&self) -> bool {
        self.operation_start.is_some() || self.streaming.active || self.confirm_dialog.is_some()
    }
}

/// Commands that `apply_action()` can emit for async execution by the event loop.
#[derive(Debug)]
pub enum AppCommand {
    Scan,
    AutoScan,
    OpenFile(String),
    RunCommand(String),
    Reconnect,
    SwitchTheme(String),
    SaveSession(String),
    LoadSession(String),
    ToggleWatch,
    Undo(Option<u32>),
    FetchUndoHistory,
    FetchSuggestions,
    WhatIf(String),
    FixDryRun(Vec<String>),
    /// Async: persist theme name to config file.
    SaveTheme(String),
    /// Async: mark onboarding as completed in config.
    MarkOnboardingComplete,
    /// Async: mark first-run marker file.
    MarkFirstRunDone,
    /// Async: list saved sessions.
    ListSessions,
    /// Apply selected fixes to files on disk, then auto-rescan.
    ApplyFixes,
    /// Async: export compliance report to markdown file.
    ExportReport,
    /// Complete onboarding: save config + credentials, trigger post-completion action.
    CompleteOnboarding,
    /// Save partial onboarding progress for resume.
    SaveOnboardingPartial(usize),
    /// Load Agent Passports from engine (spawns background task).
    LoadPassports,
    /// Background result: passports loaded from engine.
    PassportsLoaded(Result<serde_json::Value, String>),
    /// Load passport completeness data from engine.
    LoadPassportCompleteness,
    /// Validate passport (schema + signature + completeness).
    ValidatePassport,
    /// Generate FRIA report from passport.
    GeneratePassportFria,
    /// Export passport JSON to file.
    ExportPassport,
    /// Load obligations from engine.
    LoadObligations,
    /// Load agent registry data from engine (spawns background task).
    LoadRegistry,
    /// Background result: registry data loaded from engine.
    RegistryLoaded(Result<serde_json::Value, String>),
    /// Load audit trail entries from engine (spawns background task).
    LoadAuditTrail,
    /// Background result: audit trail loaded from engine.
    AuditTrailLoaded(Result<Vec<serde_json::Value>, String>),
    /// Load multi-framework scores from engine (E-105, E-106, E-107).
    LoadFrameworkScores,
    /// Background result: framework scores loaded from engine.
    FrameworkScoresLoaded(Result<MultiFrameworkScoreResult, String>),
    /// Load dashboard metrics (cost, debt, readiness) in parallel.
    LoadDashboardMetrics,
    /// Background result: dashboard metrics loaded from engine.
    DashboardMetricsLoaded {
        cost: Result<CostEstimateResult, String>,
        debt: Result<DebtResult, String>,
        readiness: Result<ReadinessResult, String>,
    },
    /// Send user message to LLM via engine chat endpoint.
    ChatSend(String),
    /// Streaming text chunk arrived from LLM.
    ChatStreamDelta(String),
    /// Structured block (`thinking/tool_call/tool_result`) from stream.
    ChatStreamBlock(ChatBlock),
    /// LLM stream completed.
    ChatStreamDone,
    /// Error from LLM stream.
    ChatStreamError(String),
    /// User cancelled streaming.
    ChatCancel,
    /// Test LLM API key validity.
    TestLlmConnection,
    /// Result of LLM connection test.
    LlmConnectionTestResult(Result<String, String>),
    /// Persist LLM settings from overlay.
    SaveLlmSettings,
}