killer 1.1.0

A Rust security platform: static analysis, the .klr test language, a parallel test framework, project intelligence, code review, and a CI gate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Killer — a fast, extensible code quality and security analysis engine.
//!
//! Phase 1: CLI, project scanner, language detection, an extensible rule
//! engine, an initial set of security/quality rules, and a terminal report.
//!
//! Phase 2: the Killer Rule Language (`.klr`) — a DSL for writing vulnerability
//! attacks and static code rules, executed by `killer test`.
//!
//! This binary is a thin wrapper over the `killer` library crate.

mod cli;

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use clap::Parser;
use colored::Colorize;

use cli::{Cli, Command, GithubAction};
use killer::analyzer::Analyzer;
use killer::attacks::http::StdHttpClient;
use killer::config::{self, Config};
use killer::git::{self, DiffTarget};
use killer::intelligence::{IntelStore, Snapshot};
use killer::klr::interpreter::RunConfig;
use killer::report::{self, Report};
use killer::results::{RuleFinding, TestRun};
use killer::{ci, explain, klr, review, rules, scanner, suites};

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

    let result = match cli.command {
        Command::Scan {
            path,
            quiet,
            fail_on_issues,
            no_record,
        } => run_scan(&path, quiet, fail_on_issues, no_record),
        Command::History { path } => run_history(&path),
        Command::Review {
            path,
            staged,
            base,
            fail_on_issues,
        } => run_review(&path, staged, base, fail_on_issues),
        Command::Ci { path, base } => run_ci(&path, base),
        Command::Github { action } => run_github(action),
        Command::Test {
            path,
            suite,
            url,
            project,
            parallel,
            format,
            no_save,
            fail_on_issues,
        } => run_test(TestArgs {
            path,
            suite,
            url,
            project,
            parallel,
            format,
            no_save,
            fail_on_issues,
        }),
        Command::Report { path, html, out } => run_report(&path, html, &out),
        Command::Explain { issue_id } => run_explain(&issue_id),
        Command::Init { path, force } => run_init(&path, force).map(|_| ExitCode::SUCCESS),
        Command::Doctor { path, fix } => run_doctor(&path, fix),
        Command::Version => {
            print_version();
            Ok(ExitCode::SUCCESS)
        }
    };

    match result {
        Ok(code) => code,
        Err(err) => {
            eprintln!("{} {:#}", "error:".red().bold(), err);
            ExitCode::FAILURE
        }
    }
}

/// Run the analysis for a directory and return the report (shared by `scan`,
/// `ci`, and snapshot recording).
fn perform_scan(root: &Path, config: &Config) -> Report {
    let scan = scanner::scan(root, config);
    let findings = Analyzer::with_default_rules(config).analyze(&scan);
    let project_name = config
        .project
        .name
        .clone()
        .unwrap_or_else(|| directory_name(root));
    Report::new(project_name, scan.stats, findings)
}

/// Record a scan snapshot in the project intelligence history (best effort).
fn record_snapshot(root: &Path, report: &Report) {
    let (timestamp, slug) = timestamp_now();
    let snapshot = Snapshot::from_report(&slug, &timestamp, report);
    let store = IntelStore::new(root);
    if let Err(e) = store.record(&snapshot, Some(&report.project_name)) {
        eprintln!("{} could not record snapshot: {e}", "warning:".yellow());
    }
}

/// Run `killer scan`.
fn run_scan(path: &Path, quiet: bool, fail_on_issues: bool, no_record: bool) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;

    if !root.is_dir() {
        anyhow::bail!("'{}' is not a directory", path.display());
    }

    let config = Config::load(&root)?;
    let report = perform_scan(&root, &config);

    if quiet {
        let c = report.severity_counts();
        println!(
            "{}: {} issues ({} critical, {} high, {} warning, {} info) — score {}/100",
            report.project_name,
            c.total(),
            c.critical,
            c.high,
            c.warning,
            c.info,
            report.score()
        );
    } else {
        print!("{}", report::banner());
        print!("{}", report.render_terminal());
    }

    if !no_record {
        record_snapshot(&root, &report);
    }

    if fail_on_issues && report.has_blocking_issues() {
        return Ok(ExitCode::FAILURE);
    }
    Ok(ExitCode::SUCCESS)
}

/// Run `killer history`.
fn run_history(path: &Path) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;
    let store = IntelStore::new(&root);
    let history = store.load_history()?;
    let trend = killer::intelligence::compute_trend(&history);
    print!("{}", report::render_score_history(&history, trend.as_ref()));
    Ok(ExitCode::SUCCESS)
}

/// Run `killer review`.
fn run_review(
    path: &Path,
    staged: bool,
    base: Option<String>,
    fail_on_issues: bool,
) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;
    let config = Config::load(&root)?;

    let target = diff_target(staged, base);
    let changed = git::changed_files(&root, &target)?;

    let findings = review::review(&root, &changed, &config);
    print!("{}", report::render_review(&findings, changed.len()));

    let blocking = findings.iter().any(|f| {
        matches!(
            f.severity,
            killer::analyzer::Severity::Critical | killer::analyzer::Severity::High
        )
    });
    if fail_on_issues && blocking {
        return Ok(ExitCode::FAILURE);
    }
    Ok(ExitCode::SUCCESS)
}

/// Run `killer ci`: scan + `.klr` tests + review, with a non-zero exit on any
/// failure. Designed for pipelines.
fn run_ci(path: &Path, base: Option<String>) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;
    let config = Config::load(&root)?;
    let mut failed = false;

    println!("{}", "▶ Killer CI gate".bold());

    // 1. Static scan.
    let report = perform_scan(&root, &config);
    record_snapshot(&root, &report);
    let sc = report.severity_counts();
    let scan_ok = !report.has_blocking_issues();
    failed |= !scan_ok;
    println!(
        "  {} scan — score {}/100, {} critical, {} high",
        status_mark(scan_ok),
        report.score(),
        sc.critical,
        sc.high
    );

    // 2. Static `.klr` rules (attacks need a live target, so CI runs rules only).
    if let Some(dir) = klr_dir_if_present(&root, &config) {
        match run_klr_rules(&root, &config, &dir) {
            Ok(n) => {
                let ok = n == 0;
                failed |= !ok;
                println!("  {} klr rules — {} finding(s)", status_mark(ok), n);
            }
            Err(e) => println!("  {} klr rules — skipped ({e})", "".dimmed()),
        }
    }

    // 3. Review of the diff (best effort — no diff is fine).
    let target = diff_target(false, base);
    match git::changed_files(&root, &target) {
        Ok(changed) if !changed.is_empty() => {
            let findings = review::review(&root, &changed, &config);
            let blocking = findings
                .iter()
                .filter(|f| {
                    matches!(
                        f.severity,
                        killer::analyzer::Severity::Critical | killer::analyzer::Severity::High
                    )
                })
                .count();
            let ok = blocking == 0;
            failed |= !ok;
            println!(
                "  {} review — {} finding(s), {} blocking",
                status_mark(ok),
                findings.len(),
                blocking
            );
        }
        Ok(_) => println!("  {} review — no changes to review", "".dimmed()),
        Err(e) => println!("  {} review — skipped ({e})", "".dimmed()),
    }

    println!();
    if failed {
        println!("{}", "✗ Killer gate FAILED".red().bold());
        Ok(ExitCode::FAILURE)
    } else {
        println!("{}", "✓ Killer gate PASSED".green().bold());
        Ok(ExitCode::SUCCESS)
    }
}

/// Run `killer github <action>`.
fn run_github(action: GithubAction) -> Result<ExitCode> {
    match action {
        GithubAction::Enable { path, force } => {
            let root = path
                .canonicalize()
                .with_context(|| format!("cannot access path '{}'", path.display()))?;
            let written = ci::write_github_workflow(&root, force)?;
            println!(
                "{} Wrote {}",
                "".green().bold(),
                file_display(&root, &written).bold()
            );
            println!("  Commit it and Killer will run on every push and pull request.");
            Ok(ExitCode::SUCCESS)
        }
    }
}

/// Build a [`DiffTarget`] from the CLI flags.
fn diff_target(staged: bool, base: Option<String>) -> DiffTarget {
    match (staged, base) {
        (_, Some(b)) => DiffTarget::Base(b),
        (true, None) => DiffTarget::Staged,
        (false, None) => DiffTarget::WorkingTree,
    }
}

/// Resolve the `.klr` directory to run rules from during CI, if it exists.
fn klr_dir_if_present(root: &Path, config: &Config) -> Option<PathBuf> {
    let dir = config
        .klr
        .directory
        .as_ref()
        .map(|d| root.join(d))
        .unwrap_or_else(|| root.to_path_buf());
    dir.exists().then_some(dir)
}

/// Parse the `.klr` files under `dir`, run their static rules over the project,
/// and return the number of findings.
fn run_klr_rules(root: &Path, config: &Config, dir: &Path) -> Result<usize> {
    let files = collect_klr_files(dir)?;
    let mut rules = Vec::new();
    for file in &files {
        let src = std::fs::read_to_string(file)?;
        let program = klr::parse(&src).map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?;
        rules.extend(program.rules);
    }
    if rules.is_empty() {
        return Ok(0);
    }
    let scan = scanner::scan(root, config);
    Ok(klr::rule_engine::run_rules(&rules, &scan.files).len())
}

fn status_mark(ok: bool) -> colored::ColoredString {
    if ok {
        "".green()
    } else {
        "".red()
    }
}

/// Run `killer test`.
/// Arguments for `killer test` (grouped to keep the signature readable).
struct TestArgs {
    path: Option<PathBuf>,
    suite: Option<String>,
    url: Option<String>,
    project: PathBuf,
    parallel: Option<usize>,
    format: String,
    no_save: bool,
    fail_on_issues: bool,
}

fn run_test(args: TestArgs) -> Result<ExitCode> {
    let json_output = args.format.eq_ignore_ascii_case("json");
    if !json_output {
        print!("{}", report::banner());
    }
    let project_root = args
        .project
        .canonicalize()
        .with_context(|| format!("cannot access project path '{}'", args.project.display()))?;
    let config = Config::load(&project_root)?;

    let mut project_name = config.project.name.clone();
    let mut attacks = Vec::new();
    let mut klr_rules = Vec::new();
    let mut sources = Vec::new();

    // Source of tests: a built-in suite, or `.klr` files.
    if let Some(suite_name) = &args.suite {
        let suite = suites::get(suite_name).ok_or_else(|| {
            let names: Vec<_> = suites::all().iter().map(|s| s.name).collect();
            anyhow::anyhow!(
                "unknown suite '{suite_name}'. Available: {}",
                names.join(", ")
            )
        })?;
        let program = parse_klr(suite.source, &format!("<builtin:{}>", suite.name))?;
        project_name = project_name.or(program.project.clone());
        attacks.extend(program.all_attacks());
        klr_rules.extend(program.rules);
        sources.push(format!("builtin:{}", suite.name));
    } else {
        let klr_path = match args.path {
            Some(p) => p,
            None => match &config.klr.directory {
                Some(dir) => project_root.join(dir),
                None => project_root.clone(),
            },
        };
        let files = collect_klr_files(&klr_path)?;
        if files.is_empty() {
            anyhow::bail!("no .klr files found at '{}'", klr_path.display());
        }
        for file in &files {
            let src = std::fs::read_to_string(file)
                .with_context(|| format!("failed to read {}", file.display()))?;
            let program = parse_klr(&src, &file_display(&project_root, file))?;
            if project_name.is_none() {
                project_name = program.project.clone();
            }
            attacks.extend(program.all_attacks());
            klr_rules.extend(program.rules);
            sources.push(file_display(&project_root, file));
        }
    }

    // Resolve base URL and worker count.
    let base_url = args
        .url
        .or_else(|| config.klr.base_url.clone())
        .unwrap_or_else(|| RunConfig::default().base_url);
    let workers = resolve_workers(args.parallel);

    let run_config = RunConfig {
        base_url,
        ..RunConfig::default()
    };
    let client = StdHttpClient::new();

    let started = Instant::now();
    let outcomes = klr::runner::run_all(&attacks, &client, &run_config, workers);
    let elapsed_ms = started.elapsed().as_millis();

    // Run static rules over the project source.
    let rule_findings: Vec<RuleFinding> = if klr_rules.is_empty() {
        Vec::new()
    } else {
        let scan = scanner::scan(&project_root, &config);
        klr::rule_engine::run_rules(&klr_rules, &scan.files)
    };

    let (timestamp, slug) = timestamp_now();
    let run = TestRun {
        project: project_name,
        timestamp,
        sources,
        attacks: outcomes,
        rule_findings,
        workers,
        elapsed_ms,
    };

    if json_output {
        println!("{}", serde_json::to_string_pretty(&run)?);
    } else {
        print!("{}", report::render_attack_report(&run));
    }

    if !args.no_save {
        match run.save(&project_root, &slug) {
            Ok(path) if !json_output => println!(
                "{} results saved to {}",
                "".green(),
                file_display(&project_root, &path).dimmed()
            ),
            Ok(_) => {}
            Err(e) => eprintln!("{} could not save results: {e}", "warning:".yellow()),
        }
    }

    if args.fail_on_issues && run.has_vulnerabilities() {
        return Ok(ExitCode::FAILURE);
    }
    Ok(ExitCode::SUCCESS)
}

/// Parse `.klr` source, turning a parse error into a nicely-formatted report.
fn parse_klr(src: &str, source_name: &str) -> Result<killer::klr::ast::Program> {
    klr::parse(src).map_err(|e| anyhow::anyhow!("{}", format_klr_error(source_name, &e)))
}

/// Format a `.klr` parse error in the KLR#### diagnostic style.
fn format_klr_error(source_name: &str, err: &killer::klr::parser::ParseError) -> String {
    let mut s = String::new();
    s.push_str(&format!("\n{}\n\n", err.code.red().bold()));
    s.push_str(&format!("{}\n\n", err.message));
    s.push_str(&format!("  {}  {}\n", "File:".bold(), source_name));
    s.push_str(&format!("  {}  {}\n", "Line:".bold(), err.line));
    if let (Some(expected), Some(found)) = (&err.expected, &err.found) {
        s.push_str(&format!(
            "\n  {}  {}\n",
            "Expected:".bold(),
            expected.green()
        ));
        s.push_str(&format!("  {}  {}\n", "Found:".bold(), found.red()));
    }
    s
}

/// Resolve the worker count: `Some(0)`/auto → cpu-based; `Some(n)` → n; None → 1.
fn resolve_workers(parallel: Option<usize>) -> usize {
    match parallel {
        None => 1,
        Some(0) => std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4)
            .clamp(1, 16),
        Some(n) => n.max(1),
    }
}

/// Run `killer report [--html]`.
fn run_report(path: &Path, html: bool, out: &Path) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;
    let run = load_latest_result(&root)?;

    if html {
        let doc = report::render_html(&run);
        std::fs::write(out, doc).with_context(|| format!("failed to write {}", out.display()))?;
        println!(
            "{} Wrote {}",
            "".green().bold(),
            out.display().to_string().bold()
        );
    } else {
        print!("{}", report::render_attack_report(&run));
    }
    Ok(ExitCode::SUCCESS)
}

/// Load the most recent saved [`TestRun`] from `.killer/results/`.
fn load_latest_result(root: &Path) -> Result<TestRun> {
    let dir = root.join(".killer").join("results");
    let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
        .with_context(|| {
            format!(
                "no results found in {} (run `killer test` first)",
                dir.display()
            )
        })?
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("json"))
        .collect();
    files.sort();
    let latest = files
        .last()
        .ok_or_else(|| anyhow::anyhow!("no saved results in {}", dir.display()))?;
    let text = std::fs::read_to_string(latest)?;
    Ok(serde_json::from_str(&text)?)
}

/// Run `killer explain <ISSUE_ID>`.
fn run_explain(issue_id: &str) -> Result<ExitCode> {
    match explain::lookup(issue_id) {
        Some(e) => {
            println!("\n{}  {}\n", e.id.bold(), e.title.bold().underline());
            println!("{}", "What it is".bold());
            println!("  {}\n", e.summary);
            println!("{}", "Impact".bold());
            println!("  {}\n", e.impact);
            println!("{}", "How to fix it".bold());
            println!("  {}\n", e.remediation);
            if !e.references.is_empty() {
                println!("{}", "References".bold());
                for r in e.references {
                    println!("{r}");
                }
                println!();
            }
            Ok(ExitCode::SUCCESS)
        }
        None => {
            eprintln!(
                "{} unknown issue id '{}'.\n\nKnown ids:",
                "error:".red().bold(),
                issue_id
            );
            for id in explain::all_ids() {
                eprintln!("{id}");
            }
            Ok(ExitCode::FAILURE)
        }
    }
}

/// Collect `.klr` files from a path (a single file or a directory tree).
fn collect_klr_files(path: &Path) -> Result<Vec<PathBuf>> {
    if path.is_file() {
        return Ok(vec![path.to_path_buf()]);
    }
    if !path.is_dir() {
        anyhow::bail!("'{}' does not exist", path.display());
    }
    let mut files: Vec<PathBuf> = walkdir::WalkDir::new(path)
        .into_iter()
        .filter_map(Result::ok)
        .filter(|e| e.file_type().is_file())
        .map(|e| e.into_path())
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("klr"))
        .collect();
    files.sort();
    Ok(files)
}

/// A path shown relative to `root` where possible, with forward slashes.
fn file_display(root: &Path, path: &Path) -> String {
    match path.strip_prefix(root) {
        Ok(rel) => rel
            .components()
            .map(|c| c.as_os_str().to_string_lossy())
            .collect::<Vec<_>>()
            .join("/"),
        // Not under the project root: show the native path as-is.
        Err(_) => path.display().to_string(),
    }
}

/// A `(human_timestamp, filename_slug)` pair from the system clock.
fn timestamp_now() -> (String, String) {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    // Human timestamp uses seconds; the slug uses zero-padded nanoseconds so
    // that back-to-back runs get distinct, correctly-sorting ids.
    (
        format!("epoch-{}", now.as_secs()),
        format!("{:020}", now.as_nanos()),
    )
}

/// Run `killer init`.
fn run_init(path: &Path, force: bool) -> Result<()> {
    if !path.is_dir() {
        anyhow::bail!("'{}' is not a directory", path.display());
    }
    let target = path.join(config::CONFIG_FILE_NAME);

    if target.exists() && !force {
        anyhow::bail!(
            "{} already exists (use --force to overwrite)",
            target.display()
        );
    }

    std::fs::write(&target, Config::default_file_contents())
        .with_context(|| format!("failed to write {}", target.display()))?;

    println!(
        "{} Created {}",
        "".green().bold(),
        target.display().to_string().bold()
    );
    Ok(())
}

/// Run `killer doctor`.
fn run_doctor(path: &Path, fix: bool) -> Result<ExitCode> {
    let root = path
        .canonicalize()
        .with_context(|| format!("cannot access path '{}'", path.display()))?;

    println!("\n{}\n", "KILLER DOCTOR".bold());
    let mut problems = 0usize;

    // 1. git — required for `review` and `ci`.
    let git_ok = std::process::Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    check(
        if git_ok { Status::Ok } else { Status::Warn },
        "git available",
        if git_ok {
            "found on PATH"
        } else {
            "not found — `review` and `ci` need git"
        },
    );

    // 2. Configuration file.
    let cfg_path = root.join(config::CONFIG_FILE_NAME);
    if cfg_path.exists() {
        match Config::load(&root) {
            Ok(_) => check(Status::Ok, ".killer.toml", "present and valid"),
            Err(e) => {
                problems += 1;
                check(Status::Fail, ".killer.toml", &format!("invalid: {e}"));
            }
        }
    } else if fix {
        std::fs::write(&cfg_path, Config::default_file_contents())
            .with_context(|| format!("failed to write {}", cfg_path.display()))?;
        check(Status::Ok, ".killer.toml", "created (--fix)");
    } else {
        check(
            Status::Warn,
            ".killer.toml",
            "not found — defaults are used (run `killer init` or `doctor --fix`)",
        );
    }

    let config = Config::load(&root).unwrap_or_default();

    // 3. Configured .klr directory, if any.
    if let Some(dir) = &config.klr.directory {
        let d = root.join(dir);
        if d.exists() {
            check(Status::Ok, "klr directory", dir);
        } else if fix {
            std::fs::create_dir_all(&d)
                .with_context(|| format!("failed to create {}", d.display()))?;
            check(Status::Ok, "klr directory", &format!("{dir} (created)"));
        } else {
            check(
                Status::Warn,
                "klr directory",
                &format!("configured '{dir}' does not exist"),
            );
        }
    }

    // 4. The .killer/ state directory is writable.
    let killer_dir = root.join(".killer").join("history");
    match std::fs::create_dir_all(&killer_dir) {
        Ok(_) => check(
            Status::Ok,
            ".killer/ writable",
            "results & history can be saved",
        ),
        Err(e) => {
            problems += 1;
            check(
                Status::Fail,
                ".killer/ writable",
                &format!("cannot write: {e}"),
            );
        }
    }

    // 5. Rule set and suites sanity (always available; a self-check).
    check(
        Status::Ok,
        "rules & suites",
        &format!(
            "{} scan rules, {} built-in suites",
            rules::all_rule_ids().len(),
            suites::all().len()
        ),
    );

    println!();
    if problems == 0 {
        println!("{}", "✓ Killer is healthy.".green().bold());
        Ok(ExitCode::SUCCESS)
    } else {
        println!(
            "{}",
            format!("{problems} problem(s) found — see above.")
                .red()
                .bold()
        );
        Ok(ExitCode::FAILURE)
    }
}

/// Status of a single doctor check.
enum Status {
    Ok,
    Warn,
    Fail,
}

/// Print one doctor check line.
fn check(status: Status, label: &str, detail: &str) {
    let mark = match status {
        Status::Ok => "".green(),
        Status::Warn => "".yellow(),
        Status::Fail => "".red().bold(),
    };
    println!("  {mark} {}  {}", label.bold(), detail.dimmed());
}

/// Run `killer version`.
fn print_version() {
    println!("{} {}", "killer".bold(), env!("CARGO_PKG_VERSION"));
    println!("{}", env!("CARGO_PKG_DESCRIPTION").dimmed());
    println!();
    println!("{}", "Active scan rules:".bold());
    for id in rules::all_rule_ids() {
        println!("{id}");
    }
    println!();
    println!("{}", "Known .klr issue ids:".bold());
    for id in explain::all_ids() {
        println!("{id}");
    }
    println!();
    println!("{}", "Built-in test suites:".bold());
    for suite in suites::all() {
        println!("{}  {}", suite.name, suite.description.dimmed());
    }
}

/// The final path component of `root`, used as a fallback project name.
fn directory_name(root: &Path) -> String {
    root.file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| root.to_string_lossy().into_owned())
}