slopguard-cli 0.1.19

CLI tool to catch AI-generated code patterns via static analysis
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
mod baseline_cmd;
mod cli;
mod output;
mod stats_cmd;

use std::cmp::Ordering;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{SystemTime, UNIX_EPOCH};

use clap::Parser;
use strsim::normalized_levenshtein;
use thiserror::Error;

use slopguard_ai::{build_provider, run_ai_pass, AiCache, AiCandidate, DEFAULT_MODEL};
use slopguard_core::baseline::BaselineError;
use slopguard_core::config::{load_config, load_config_file, Config, ConfigError, OutputFormat};
use slopguard_core::escalation::apply_escalation;
use slopguard_core::finding::{Finding, ScanResult};
use slopguard_core::git::{changed_files, GitError};
use slopguard_core::preset::{presets_help, Preset};
use slopguard_core::rule::{
    is_rule_active, load_all_rules, load_builtin_rules, load_effective_rules, Category, Language,
    Rule, RuleError, Severity,
};
use slopguard_core::scanner::{
    count_severities, scan, scan_cached, scan_files, scan_files_cached, ScanError,
};
use slopguard_core::testing::{self, RuleTestStatus, TestError, TestFailureKind};

use crate::baseline_cmd::{apply_baseline, run_baseline, BaselineOpts};
use crate::cli::{CategoryFilter, Cli, Command, Format, LanguageFilter, SeverityThreshold};
use crate::output::html::{project_name, HtmlMeta};
use crate::output::json::ListEntry;
use crate::output::{html, json, sarif, text};
use crate::stats_cmd::{compute_report, run_stats, StatsOpts};

fn has_findings_above_threshold(result: &ScanResult, threshold: &SeverityThreshold) -> bool {
    result.findings.iter().any(|f| match threshold {
        SeverityThreshold::Warning => true,
        SeverityThreshold::Error => f.severity == Severity::Error,
    })
}

fn write_output(
    result: &ScanResult,
    format: &Format,
    w: &mut impl Write,
    use_colors: bool,
    html_meta: &HtmlMeta,
) -> io::Result<()> {
    match format {
        Format::Text => text::format_text(result, w, use_colors),
        Format::Json => json::format_json(result, w),
        Format::Sarif => sarif::format_sarif(result, w),
        Format::Html => html::format_html(result, &compute_report(result), html_meta, w),
    }
}

#[derive(Debug, Error)]
pub enum AppError {
    #[error("{0}")]
    Config(#[from] ConfigError),
    #[error("{0}")]
    Rule(#[from] RuleError),
    #[error("{0}")]
    Scan(#[from] ScanError),
    #[error("{0}")]
    Test(#[from] TestError),
    #[error("{0}")]
    Io(#[from] io::Error),
    #[error("{0}")]
    Baseline(#[from] BaselineError),
    #[error("{0}")]
    Git(#[from] GitError),
}

fn suggest_similar<'a>(id: &str, rules: &'a [Rule]) -> Option<&'a str> {
    rules
        .iter()
        .map(|r| (r.id.as_str(), normalized_levenshtein(id, r.id.as_str())))
        .filter(|(_, score)| *score >= 0.6)
        .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal))
        .map(|(id, _)| id)
}

struct ScanOpts {
    paths: Vec<PathBuf>,
    format: Option<Format>,
    output: Option<PathBuf>,
    severity_threshold: SeverityThreshold,
    config_path: Option<PathBuf>,
    no_colors: bool,
    cli_disable: Vec<String>,
    cli_enable: Vec<String>,
    rule_filter: Option<String>,
    no_cache: bool,
    cache_dir: Option<PathBuf>,
    no_ai: bool,
    no_baseline: bool,
    baseline_path: Option<PathBuf>,
    no_escalation: bool,
    diff: bool,
    base: Option<String>,
}

/// Options shared by `scan` and `baseline`, which collect findings the same
/// way and only differ in what they do with them.
pub struct CollectOpts {
    pub paths: Vec<PathBuf>,
    pub config_path: Option<PathBuf>,
    pub cli_disable: Vec<String>,
    pub cli_enable: Vec<String>,
    pub rule_filter: Option<String>,
    pub no_cache: bool,
    pub cache_dir: Option<PathBuf>,
    pub no_ai: bool,
    pub diff: bool,
    pub diff_base: Option<String>,
}

/// Where the AST pass looks: directory roots to walk (normal scan), or the
/// exact list of files git reported as changed (`--diff`).
enum ScanTargets {
    Walk(Vec<PathBuf>),
    Files(Vec<PathBuf>),
}

impl ScanTargets {
    fn run(
        &self,
        rules: &[Rule],
        config: &Config,
        no_cache: bool,
        cache_dir: &Path,
    ) -> Result<ScanResult, ScanError> {
        match (self, no_cache) {
            (ScanTargets::Walk(p), true) => scan(p, rules, config),
            (ScanTargets::Walk(p), false) => scan_cached(p, rules, config, cache_dir),
            (ScanTargets::Files(f), true) => scan_files(f, rules, config),
            (ScanTargets::Files(f), false) => scan_files_cached(f, rules, config, cache_dir),
        }
    }
}

/// Keep the changed files that live under one of the requested paths, so
/// `slopguard scan src/ --diff` stays scoped to `src/`.
///
/// Paths that cannot be canonicalized are compared as given.
fn under_requested_paths(files: Vec<PathBuf>, paths: &[PathBuf]) -> Vec<PathBuf> {
    let roots: Vec<PathBuf> = paths
        .iter()
        .map(|p| p.canonicalize().unwrap_or_else(|_| p.clone()))
        .collect();
    files
        .into_iter()
        .filter(|file| {
            let resolved = file.canonicalize().unwrap_or_else(|_| file.clone());
            roots.iter().any(|root| resolved.starts_with(root))
        })
        .collect()
}

/// Resolve the config, load the active rules, run the AST pass (cached or
/// not) then the AI pass, and return the raw unfiltered result along with the
/// resolved config.
pub fn collect_findings(opts: CollectOpts) -> Result<(ScanResult, Config), AppError> {
    let CollectOpts {
        paths,
        config_path,
        cli_disable,
        cli_enable,
        rule_filter,
        no_cache,
        cache_dir,
        no_ai,
        diff,
        diff_base,
    } = opts;

    let mut config = resolve_config(config_path.as_deref())?;
    config.rules.disable.extend(cli_disable);
    config.rules.enable.extend(cli_enable);

    let mut rules = load_effective_rules(&config)?;

    if let Some(ref filter_id) = rule_filter {
        let found = rules.iter().any(|r| r.id.as_str() == filter_id);
        if !found {
            let suggestion = suggest_similar(filter_id, &rules);
            if let Some(suggested) = suggestion {
                eprintln!("error: unknown rule '{filter_id}'. Did you mean '{suggested}'?");
            } else {
                eprintln!("error: unknown rule '{filter_id}'");
            }
            return Err(AppError::Io(io::Error::new(
                io::ErrorKind::NotFound,
                format!("unknown rule '{filter_id}'"),
            )));
        }
        rules.retain(|r| r.id.as_str() == filter_id);
    }

    // --no-ai: exclude AI rules entirely so their AST pre-filter matches
    // never appear as unconfirmed findings.
    if no_ai {
        rules.retain(|r| r.ai_check.is_none());
    }

    let (ai_rules, ast_rules): (Vec<Rule>, Vec<Rule>) =
        rules.into_iter().partition(|r| r.ai_check.is_some());

    let targets = if diff {
        let cwd = env::current_dir().map_err(AppError::Io)?;
        let changed = under_requested_paths(changed_files(&cwd, diff_base.as_deref())?, &paths);
        ScanTargets::Files(changed)
    } else {
        ScanTargets::Walk(paths)
    };

    let resolved_cache_dir = resolve_cache_dir(cache_dir, &config);
    let mut result = targets.run(&ast_rules, &config, no_cache, &resolved_cache_dir)?;

    if !ai_rules.is_empty() {
        let ai_findings =
            run_ai_phase(&targets, &ai_rules, &config, no_cache, &resolved_cache_dir)?;
        if !ai_findings.is_empty() {
            merge_ai_findings(&mut result, ai_findings);
        }
    }

    // Set last, so the AI merge cannot drop the diff metadata.
    if let ScanTargets::Files(ref files) = targets {
        result.stats.diff_base = Some(diff_base.unwrap_or_else(|| "HEAD".to_string()));
        result.stats.files_changed = Some(files.len());
    }

    Ok((result, config))
}

fn run_scan(opts: ScanOpts) -> Result<bool, AppError> {
    let ScanOpts {
        paths,
        format,
        output,
        severity_threshold,
        config_path,
        no_colors,
        cli_disable,
        cli_enable,
        rule_filter,
        no_cache,
        cache_dir,
        no_ai,
        no_baseline,
        baseline_path,
        no_escalation,
        diff,
        base,
    } = opts;
    let use_colors = !no_colors && env::var_os("NO_COLOR").is_none();
    // `paths` is moved into CollectOpts below, so derive the title first.
    let project = project_name(&paths);

    let (mut result, config) = collect_findings(CollectOpts {
        paths,
        config_path,
        cli_disable,
        cli_enable,
        rule_filter,
        no_cache,
        cache_dir,
        no_ai,
        diff,
        diff_base: base,
    })?;

    let baseline_active = apply_baseline(&mut result, no_baseline, baseline_path)?;

    // After the baseline (suppressed findings must not inflate the per-file
    // count) and before the severity threshold, so an escalated finding can
    // fail a `--severity-threshold error` run.
    if !no_escalation {
        apply_escalation(&mut result, &config.escalation);
    }

    let format = format.unwrap_or(match config.output.format {
        OutputFormat::Text => Format::Text,
        OutputFormat::Json => Format::Json,
        OutputFormat::Sarif => Format::Sarif,
        OutputFormat::Html => Format::Html,
    });

    let has_findings = has_findings_above_threshold(&result, &severity_threshold);

    let html_meta = HtmlMeta {
        project_name: project,
        generated_at_secs: SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        baseline_active,
    };

    match output {
        Some(path) => {
            let file = fs::File::create(&path)?;
            let mut w = BufWriter::new(file);
            // A file is never a terminal: never emit ANSI escapes into it.
            write_output(&result, &format, &mut w, false, &html_meta)?;
            w.flush()?;
        }
        None => {
            let stdout = io::stdout();
            let mut out = stdout.lock();
            write_output(&result, &format, &mut out, use_colors, &html_meta)?;
        }
    }

    Ok(has_findings)
}

/// Map a file path to the rule language it is scanned as.
pub(crate) fn language_for_path(path: &Path) -> Option<Language> {
    match path.extension().and_then(|e| e.to_str()) {
        Some("rs") => Some(Language::Rust),
        Some("ts" | "tsx") => Some(Language::TypeScript),
        _ => None,
    }
}

/// Find the `ai_check` rule that produced a candidate finding, matching on id
/// and (when possible) the file's language, so a shared id across Rust and
/// TypeScript resolves to the right variant.
fn find_ai_rule<'a>(ai_rules: &'a [Rule], finding: &Finding) -> Option<&'a Rule> {
    let lang = language_for_path(&finding.file);
    ai_rules
        .iter()
        .find(|r| r.id == finding.rule_id && Some(&r.language) == lang.as_ref())
        .or_else(|| ai_rules.iter().find(|r| r.id == finding.rule_id))
}

/// Turn AST candidate findings into AI candidates: attach each rule's prompt,
/// resolved model, and the file content used for context and cache keys. Files
/// are read once each; unreadable files or unmatched findings are skipped.
fn build_candidates(
    findings: Vec<Finding>,
    ai_rules: &[Rule],
    config: &Config,
) -> Vec<AiCandidate> {
    let mut contents: HashMap<PathBuf, Option<String>> = HashMap::new();
    let mut candidates = Vec::new();
    for finding in findings {
        let Some(rule) = find_ai_rule(ai_rules, &finding) else {
            continue;
        };
        let Some(ai_check) = rule.ai_check.as_ref() else {
            continue;
        };
        let content = contents
            .entry(finding.file.clone())
            .or_insert_with(|| fs::read_to_string(&finding.file).ok());
        let Some(file_content) = content.clone() else {
            continue;
        };
        let model = ai_check
            .model
            .clone()
            .or_else(|| config.ai.model.clone())
            .unwrap_or_else(|| DEFAULT_MODEL.to_string());
        let rule_context = rule.note.clone().unwrap_or_else(|| rule.message.clone());
        candidates.push(AiCandidate {
            finding,
            file_content,
            prompt_template: ai_check.prompt.clone(),
            model,
            rule_context,
        });
    }
    candidates
}

/// Merge AI-confirmed findings into the AST result, keeping ordering, dedup,
/// and severity counts consistent (`files_scanned` is preserved).
fn merge_ai_findings(result: &mut ScanResult, ai_findings: Vec<Finding>) {
    result.findings.extend(ai_findings);
    result
        .findings
        .sort_by(|a, b| (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column)));
    result.findings.dedup_by(|a, b| {
        a.rule_id == b.rule_id && a.file == b.file && a.line == b.line && a.column == b.column
    });
    let (errors, warnings) = count_severities(&result.findings);
    result.stats.errors = errors;
    result.stats.warnings = warnings;
    result.stats.total = errors + warnings;
}

/// Run the AI confirmation phase for `ai_rules`.
///
/// When the provider cannot be built (disabled, missing credentials), a single
/// warning is emitted and no LLM call is made. Otherwise the AST pre-filter
/// produces candidates that the LLM confirms.
fn run_ai_phase(
    targets: &ScanTargets,
    ai_rules: &[Rule],
    config: &Config,
    no_cache: bool,
    cache_dir: &Path,
) -> Result<Vec<Finding>, AppError> {
    let provider = match build_provider(&config.ai) {
        Ok(provider) => provider,
        Err(err) => {
            // Clear, credential-specific reason (disabled, missing API key,
            // missing claude binary, missing OAuth token). Non-fatal: the AST
            // findings still stand.
            eprintln!("warning: {} AI rules skipped ({err})", ai_rules.len());
            return Ok(Vec::new());
        }
    };

    // Pre-filter: run the AST patterns of the AI rules to collect candidates.
    let candidate_result = targets.run(ai_rules, config, true, cache_dir)?;
    if candidate_result.findings.is_empty() {
        return Ok(Vec::new());
    }
    let candidates = build_candidates(candidate_result.findings, ai_rules, config);
    let cache = (!no_cache).then(|| AiCache::new(cache_dir));
    Ok(run_ai_pass(
        &*provider,
        candidates,
        config.ai.concurrency,
        cache.as_ref(),
    ))
}

fn run_explain(
    rule_id: String,
    format: Option<Format>,
    config_path: Option<PathBuf>,
) -> Result<(), AppError> {
    let config = resolve_config(config_path.as_deref())?;
    let rules = load_all_rules(&config)?;

    let rule = rules.iter().find(|r| r.id.as_str() == rule_id);
    match rule {
        Some(r) => {
            let format = format.unwrap_or(Format::Text);
            let stdout = io::stdout();
            let mut out = stdout.lock();
            match format {
                Format::Text => text::format_explain(r, &mut out),
                Format::Json => json::format_explain_json(r, &mut out),
                Format::Sarif => {
                    eprintln!("error: SARIF format is not supported for explain");
                    return Err(AppError::Io(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "SARIF format is not supported for explain",
                    )));
                }
                Format::Html => {
                    return Err(AppError::Io(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "HTML format is not supported for explain",
                    )));
                }
            }?;
            Ok(())
        }
        None => {
            let suggestion = suggest_similar(&rule_id, &rules);
            if let Some(suggested) = suggestion {
                eprintln!("error: unknown rule '{rule_id}'. Did you mean '{suggested}'?");
            } else {
                eprintln!("error: unknown rule '{rule_id}'");
            }
            Err(AppError::Io(io::Error::new(
                io::ErrorKind::NotFound,
                format!("unknown rule '{rule_id}'"),
            )))
        }
    }
}

fn resolve_cache_dir(cli_flag: Option<PathBuf>, config: &Config) -> PathBuf {
    cli_flag
        .or_else(|| {
            env::var("SLOPGUARD_CACHE_DIR")
                .ok()
                .filter(|s| !s.is_empty())
                .map(PathBuf::from)
        })
        .or_else(|| config.scan.cache_dir.clone())
        .unwrap_or_else(|| {
            let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
            cwd.join(".slopguard-cache")
        })
}

fn resolve_config(config_path: Option<&Path>) -> Result<Config, AppError> {
    match config_path {
        Some(path) => Ok(load_config_file(path)?),
        None => {
            let cwd = env::current_dir().map_err(|e| {
                AppError::Config(ConfigError::Io {
                    path: ".".to_string(),
                    source: e,
                })
            })?;
            Ok(load_config(&cwd)?)
        }
    }
}

fn run_test(config_path: Option<PathBuf>) -> Result<bool, AppError> {
    let config = resolve_config(config_path.as_deref())?;
    let rules = load_effective_rules(&config)?;
    let summary = testing::test_rules(&rules)?;

    for result in &summary.results {
        match &result.status {
            RuleTestStatus::Pass => {
                println!("  PASS  {}", result.rule_id);
            }
            RuleTestStatus::Fail { failures } => {
                println!("  FAIL  {}", result.rule_id);
                for failure in failures {
                    let label = match failure.kind {
                        TestFailureKind::ShouldMatchDidNot => "should_match did not match",
                        TestFailureKind::ShouldNotMatchDid => "should_not_match matched",
                    };
                    println!(
                        "        {label}: {}",
                        failure.snippet.lines().next().unwrap_or("")
                    );
                }
            }
            RuleTestStatus::NoTests => {
                println!("  WARN  {} - no tests", result.rule_id);
            }
        }
    }

    println!(
        "\n{} rules tested, {} passed, {} failed",
        summary.total_tested, summary.passed, summary.failed
    );
    if summary.no_tests > 0 {
        println!("{} rules with no tests", summary.no_tests);
    }

    Ok(summary.failed > 0)
}

fn run_list(
    show_all: bool,
    category: Option<CategoryFilter>,
    language: Option<LanguageFilter>,
    format: Option<Format>,
    config_path: Option<PathBuf>,
) -> Result<(), AppError> {
    let config = resolve_config(config_path.as_deref())?;

    let rules = if show_all {
        load_builtin_rules()?
    } else {
        load_effective_rules(&config)?
    };

    let entries: Vec<ListEntry> = rules
        .iter()
        .map(|r| ListEntry {
            id: r.id.to_string(),
            language: r.language.to_string(),
            severity: r.severity.to_string(),
            category: r
                .category
                .as_ref()
                .unwrap_or(&Category::Correctness)
                .to_string(),
            kind: json::rule_kind(r).to_string(),
            status: if !show_all || is_rule_active(r, &config) {
                "enabled".to_string()
            } else {
                "disabled".to_string()
            },
        })
        .collect();

    let filtered: Vec<&ListEntry> = entries
        .iter()
        .filter(|e| match &category {
            Some(CategoryFilter::Slop) => e.category == "slop",
            Some(CategoryFilter::Security) => e.category == "security",
            Some(CategoryFilter::Correctness) => e.category == "correctness",
            None => true,
        })
        .filter(|e| match &language {
            Some(LanguageFilter::Rust) => e.language == "rust",
            Some(LanguageFilter::Typescript) => e.language == "typescript",
            None => true,
        })
        .collect();

    match format {
        Some(Format::Json) => {
            return json::format_list_json(&filtered, &mut io::stdout().lock())
                .map_err(AppError::Io);
        }
        Some(Format::Sarif) => {
            eprintln!("error: SARIF format is not supported for list");
            return Err(AppError::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "SARIF format is not supported for list",
            )));
        }
        Some(Format::Html) => {
            eprintln!("error: HTML format is not supported for list");
            return Err(AppError::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "HTML format is not supported for list",
            )));
        }
        None | Some(Format::Text) => {}
    }

    let id_w = filtered
        .iter()
        .map(|e| e.id.len())
        .max()
        .unwrap_or(2)
        .max(2);
    let lang_w = filtered
        .iter()
        .map(|e| e.language.len())
        .max()
        .unwrap_or(8)
        .max(8);
    let sev_w = filtered
        .iter()
        .map(|e| e.severity.len())
        .max()
        .unwrap_or(8)
        .max(8);
    let cat_w = filtered
        .iter()
        .map(|e| e.category.len())
        .max()
        .unwrap_or(8)
        .max(8);
    let kind_w = filtered
        .iter()
        .map(|e| e.kind.len())
        .max()
        .unwrap_or(4)
        .max(4);

    println!(
        "{:<id_w$}  {:<lang_w$}  {:<sev_w$}  {:<cat_w$}  {:<kind_w$}  status",
        "id", "language", "severity", "category", "type"
    );
    println!(
        "{:<id_w$}  {:<lang_w$}  {:<sev_w$}  {:<cat_w$}  {:<kind_w$}  ------",
        "--", "--------", "--------", "--------", "----"
    );
    for e in &filtered {
        println!(
            "{:<id_w$}  {:<lang_w$}  {:<sev_w$}  {:<cat_w$}  {:<kind_w$}  {}",
            e.id, e.language, e.severity, e.category, e.kind, e.status
        );
    }

    println!("\n{} rules", filtered.len());
    Ok(())
}

fn run_init(force: bool, preset: Option<Option<Preset>>) -> Result<(), AppError> {
    // `--preset` with no value lists the presets and writes nothing.
    if matches!(preset, Some(None)) {
        print!("{}", presets_help());
        return Ok(());
    }
    let preset = preset.flatten().unwrap_or_default();

    let config_path = Path::new("slopguard.toml");
    if config_path.exists() && !force {
        eprintln!("error: slopguard.toml already exists (use --force to overwrite)");
        return Err(AppError::Io(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "slopguard.toml already exists",
        )));
    }
    fs::write(config_path, preset.render()?)?;
    println!("Created slopguard.toml (preset: {preset})");
    Ok(())
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    match cli.command {
        Command::Scan {
            paths,
            format,
            output,
            severity_threshold,
            config,
            no_colors,
            cli_disable,
            cli_enable,
            rule_filter,
            no_cache,
            cache_dir,
            no_ai,
            no_baseline,
            baseline_path,
            no_escalation,
            diff,
            base,
        } => match run_scan(ScanOpts {
            paths,
            format,
            output,
            severity_threshold,
            config_path: config,
            no_colors,
            cli_disable,
            cli_enable,
            rule_filter,
            no_cache,
            cache_dir,
            no_ai,
            no_baseline,
            baseline_path,
            no_escalation,
            diff,
            base,
        }) {
            Ok(true) => ExitCode::from(1),
            Ok(false) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
        Command::Stats {
            paths,
            format,
            config,
            no_colors,
            cli_disable,
            cli_enable,
            rule_filter,
            no_cache,
            cache_dir,
            no_ai,
            no_baseline,
            baseline_path,
            no_escalation,
        } => match run_stats(StatsOpts {
            paths,
            format,
            config_path: config,
            no_colors,
            cli_disable,
            cli_enable,
            rule_filter,
            no_cache,
            cache_dir,
            no_ai,
            no_baseline,
            baseline_path,
            no_escalation,
        }) {
            Ok(()) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
        Command::Baseline {
            paths,
            output,
            config,
            cli_disable,
            cli_enable,
            no_cache,
            cache_dir,
            no_ai,
        } => match run_baseline(BaselineOpts {
            paths,
            output,
            config_path: config,
            cli_disable,
            cli_enable,
            no_cache,
            cache_dir,
            no_ai,
        }) {
            Ok(()) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
        Command::Explain {
            rule_id,
            format,
            config,
        } => match run_explain(rule_id, format, config) {
            Ok(()) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
        Command::Init { force, preset } => match run_init(force, preset) {
            Ok(()) => ExitCode::SUCCESS,
            Err(_) => ExitCode::from(1),
        },
        Command::Test { config } => match run_test(config) {
            Ok(true) => ExitCode::from(1),
            Ok(false) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
        Command::List {
            all,
            format,
            category,
            language,
            config,
        } => match run_list(all, category, language, format, config) {
            Ok(()) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        },
    }
}