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
mod apply;
mod diff_preview;
mod render;
#[cfg(test)]
#[path = "tests.rs"]
mod tests;

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};

use crate::app::App;
use crate::theme;
use crate::types::Finding;

// Re-export public API (same paths as before the split).
pub use apply::apply_fix_to_file;

/// Status of a single fix item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixItemStatus {
    Pending,
    Applied,
    Failed,
}

/// A fixable finding with selection state.
#[derive(Debug, Clone)]
pub struct FixableItem {
    pub finding_index: usize,
    pub check_id: String,
    pub obligation_id: Option<String>,
    pub article_reference: Option<String>,
    pub message: String,
    pub selected: bool,
    pub predicted_impact: i32,
    pub status: FixItemStatus,
    pub finding_type: crate::types::FindingType,
    pub file_path: Option<String>,
}

/// Results of applying fixes.
#[derive(Debug, Clone)]
pub struct FixResults {
    pub applied: u32,
    pub failed: u32,
    pub old_score: f64,
    pub new_score: f64,
}

/// State for the Fix View.
#[derive(Debug, Clone)]
pub struct FixViewState {
    pub fixable_findings: Vec<FixableItem>,
    pub selected_index: usize,
    pub diff_visible: bool,
    pub applying: bool,
    pub results: Option<FixResults>,
    /// When set, Fix view shows only this finding (single-fix mode from Scan).
    pub focus_check_id: Option<String>,
}

impl Default for FixViewState {
    fn default() -> Self {
        Self {
            fixable_findings: Vec::new(),
            selected_index: 0,
            diff_visible: true,
            applying: false,
            results: None,
            focus_check_id: None,
        }
    }
}

impl FixViewState {
    /// Build fix view state from scan findings.
    pub fn from_scan(findings: &[Finding]) -> Self {
        let fixable: Vec<FixableItem> = findings
            .iter()
            .enumerate()
            .filter(|(_, f)| f.fix.is_some())
            .map(|(i, f)| FixableItem {
                finding_index: i,
                check_id: f.check_id.clone(),
                obligation_id: f.obligation_id.clone(),
                article_reference: f.article_reference.clone(),
                message: f.message.clone(),
                selected: false,
                predicted_impact: f.predicted_impact(),
                status: FixItemStatus::Pending,
                finding_type: f.finding_type(),
                file_path: f.file.clone(),
            })
            .collect();

        Self {
            fixable_findings: fixable,
            selected_index: 0,
            diff_visible: true,
            applying: false,
            results: None,
            focus_check_id: None,
        }
    }

    pub const fn is_single_fix(&self) -> bool {
        self.focus_check_id.is_some()
    }

    pub fn selected_count(&self) -> usize {
        self.fixable_findings.iter().filter(|f| f.selected).count()
    }

    pub fn total_predicted_impact(&self) -> i32 {
        self.fixable_findings
            .iter()
            .filter(|f| f.selected)
            .map(|f| f.predicted_impact)
            .sum()
    }

    pub fn toggle_current(&mut self) {
        if let Some(item) = self.fixable_findings.get_mut(self.selected_index) {
            item.selected = !item.selected;
        }
    }

    pub fn toggle_at(&mut self, idx: usize) {
        if let Some(item) = self.fixable_findings.get_mut(idx) {
            item.selected = !item.selected;
        }
    }

    pub fn select_all(&mut self) {
        for item in &mut self.fixable_findings {
            item.selected = true;
        }
    }

    pub fn deselect_all(&mut self) {
        for item in &mut self.fixable_findings {
            item.selected = false;
        }
    }

    pub const fn navigate_up(&mut self) {
        self.selected_index = self.selected_index.saturating_sub(1);
    }

    pub fn navigate_down(&mut self) {
        if !self.fixable_findings.is_empty() {
            self.selected_index = (self.selected_index + 1).min(self.fixable_findings.len() - 1);
        }
    }
}

/// Render the Fix View.
pub fn render_fix_view(frame: &mut Frame, area: Rect, app: &App) {
    if let Some(results) = &app.fix_view.results {
        render_fix_results(frame, area, results);
        return;
    }

    if app.last_scan.is_none() {
        render_no_fix_data(frame, area, "No scan data. Run a scan first (Ctrl+S).");
        return;
    }

    if app.fix_view.fixable_findings.is_empty() {
        render_no_fix_data(
            frame,
            area,
            "No fixable findings. All checks are passing or have no suggested fix.",
        );
        return;
    }

    if app.fix_view.diff_visible {
        let left_pct = app.fix_split_pct.clamp(25, 75);
        let right_pct = 100 - left_pct;
        let layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(left_pct),
                Constraint::Percentage(right_pct),
            ])
            .split(area);
        render::render_checklist(frame, layout[0], app);
        diff_preview::render_diff_preview(frame, layout[1], app);
    } else {
        render::render_checklist(frame, area, app);
    }
}

fn render_no_fix_data(frame: &mut Frame, area: Rect, message: &str) {
    let t = theme::theme();
    let block = Block::default()
        .title(" Fix ")
        .title_style(theme::title_style())
        .borders(Borders::ALL)
        .border_style(Style::default().fg(t.border));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let lines = vec![
        Line::raw(""),
        Line::from(Span::styled(
            format!("  {message}"),
            Style::default().fg(t.muted),
        )),
    ];
    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

fn render_fix_results(frame: &mut Frame, area: Rect, results: &FixResults) {
    let t = theme::theme();
    let block = Block::default()
        .title(" Fix Results ")
        .title_style(theme::title_style())
        .borders(Borders::ALL)
        .border_style(Style::default().fg(t.zone_green));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let delta = results.new_score - results.old_score;
    let delta_color = if delta > 0.0 {
        t.zone_green
    } else {
        t.zone_red
    };
    let new_color = if results.new_score < 50.0 {
        t.zone_red
    } else if results.new_score < 80.0 {
        t.zone_yellow
    } else {
        t.zone_green
    };
    let old_color = if results.old_score < 50.0 {
        t.zone_red
    } else if results.old_score < 80.0 {
        t.zone_yellow
    } else {
        t.zone_green
    };

    let w = inner.width.saturating_sub(4) as usize;

    let mut lines = vec![Line::raw("")];

    // Success header
    if results.failed == 0 {
        lines.push(Line::from(Span::styled(
            "  All fixes applied successfully!",
            Style::default()
                .fg(t.zone_green)
                .add_modifier(Modifier::BOLD),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            format!(
                "  {} fixes applied, {} failed",
                results.applied, results.failed
            ),
            Style::default()
                .fg(t.zone_yellow)
                .add_modifier(Modifier::BOLD),
        )));
    }
    lines.push(Line::raw(""));

    // Visual score comparison: Before -> After
    lines.push(Line::from(Span::styled(
        "  Score Improvement",
        Style::default().fg(t.fg).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(Span::styled(
        format!("  {}", "\u{2500}".repeat(w)),
        Style::default().fg(t.border),
    )));

    // Before gauge
    let old_ratio = (results.old_score / 100.0).clamp(0.0, 1.0);
    let old_filled = (old_ratio * (w.min(40) as f64)) as usize;
    let old_empty = w.min(40).saturating_sub(old_filled);
    lines.push(Line::from(vec![
        Span::styled("  Before: ", Style::default().fg(t.muted)),
        Span::styled(
            "\u{2588}".repeat(old_filled),
            Style::default().fg(old_color),
        ),
        Span::styled("\u{2591}".repeat(old_empty), Style::default().fg(t.muted)),
        Span::styled(
            format!(" {:.0}/100", results.old_score),
            Style::default().fg(old_color).add_modifier(Modifier::BOLD),
        ),
    ]));

    // After gauge
    let new_ratio = (results.new_score / 100.0).clamp(0.0, 1.0);
    let new_filled = (new_ratio * (w.min(40) as f64)) as usize;
    let new_empty = w.min(40).saturating_sub(new_filled);
    lines.push(Line::from(vec![
        Span::styled("  After:  ", Style::default().fg(t.muted)),
        Span::styled(
            "\u{2588}".repeat(new_filled),
            Style::default().fg(new_color),
        ),
        Span::styled("\u{2591}".repeat(new_empty), Style::default().fg(t.muted)),
        Span::styled(
            format!(" {:.0}/100", results.new_score),
            Style::default().fg(new_color).add_modifier(Modifier::BOLD),
        ),
    ]));

    // Delta highlight
    lines.push(Line::raw(""));
    lines.push(Line::from(vec![
        Span::styled("  Change: ", Style::default().fg(t.muted)),
        Span::styled(
            format!("{delta:+.0} points"),
            Style::default()
                .fg(delta_color)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  ({} fixes applied)", results.applied),
            Style::default().fg(t.muted),
        ),
    ]));

    lines.push(Line::raw(""));

    // Zone assessment
    let zone_label = if results.new_score >= 80.0 {
        ("GREEN \u{2014} Compliant", t.zone_green)
    } else if results.new_score >= 50.0 {
        ("YELLOW \u{2014} Partial Compliance", t.zone_yellow)
    } else {
        ("RED \u{2014} Non-Compliant", t.zone_red)
    };
    lines.push(Line::from(vec![
        Span::styled("  Status: ", Style::default().fg(t.muted)),
        Span::styled(
            zone_label.0,
            Style::default()
                .fg(zone_label.1)
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    lines.push(Line::raw(""));

    // Next steps
    lines.push(Line::from(Span::styled(
        "  Recommended Next Steps",
        Style::default().fg(t.fg).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(Span::styled(
        format!("  {}", "\u{2500}".repeat(w)),
        Style::default().fg(t.border),
    )));

    if results.new_score < 50.0 {
        lines.push(Line::from(vec![
            Span::styled("  1. ", Style::default().fg(t.accent)),
            Span::styled(
                "Run scan (S) to find remaining critical issues",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  2. ", Style::default().fg(t.accent)),
            Span::styled(
                "Focus on CRITICAL and HIGH severity findings",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  3. ", Style::default().fg(t.accent)),
            Span::styled(
                "Create required documentation (FRIA, transparency)",
                Style::default().fg(t.fg),
            ),
        ]));
    } else if results.new_score < 80.0 {
        lines.push(Line::from(vec![
            Span::styled("  1. ", Style::default().fg(t.accent)),
            Span::styled(
                "Run scan (S) to verify improvements",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  2. ", Style::default().fg(t.accent)),
            Span::styled(
                "Address remaining HIGH severity findings",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  3. ", Style::default().fg(t.accent)),
            Span::styled(
                "Export compliance report (R, then e)",
                Style::default().fg(t.fg),
            ),
        ]));
    } else {
        lines.push(Line::from(vec![
            Span::styled("  1. ", Style::default().fg(t.accent)),
            Span::styled(
                "Export compliance report (R, then e)",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  2. ", Style::default().fg(t.accent)),
            Span::styled(
                "Enable watch mode (w) for continuous monitoring",
                Style::default().fg(t.fg),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("  3. ", Style::default().fg(t.accent)),
            Span::styled(
                "Set up Agent Passport (P) for AI system identity",
                Style::default().fg(t.fg),
            ),
        ]));
    }

    lines.push(Line::raw(""));
    lines.push(Line::from(Span::styled(
        format!("  {}", "\u{2500}".repeat(w)),
        Style::default().fg(t.border),
    )));
    lines.push(Line::from(vec![
        Span::styled("  [Enter] ", Style::default().fg(t.accent)),
        Span::styled("Continue  ", Style::default().fg(t.fg)),
        Span::styled("[S] ", Style::default().fg(t.accent)),
        Span::styled("Scan View  ", Style::default().fg(t.fg)),
        Span::styled("[Esc] ", Style::default().fg(t.accent)),
        Span::styled("Back", Style::default().fg(t.fg)),
    ]));

    frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}