crap-core 0.5.0

Language-agnostic foundation for the CRAP analyzer family — domain types, port traits, and shared invariants for crap4rs / future crap4ts.
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Config file adapter — loads the adapter's TOML config (file name
//! supplied by the binary via `AdapterMeta::config_file_name`) and
//! converts to domain types.
//!
//! Handles TOML parsing and config file discovery. All CLI-representable
//! options are supported. Per-path threshold overrides use glob patterns.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::Deserialize;

use crate::domain::threshold::{ThresholdOverride, ThresholdPreset, is_valid_threshold};
use crate::domain::types::ComplexityMetric;
use crate::domain::view::{CoverageRange, CoverageRangeError, GroupKey, SortKey};

// ── Public config type (adapter output) ────────────────────────────

/// Parsed configuration from a TOML file.
///
/// All fields are optional — missing fields mean "use CLI default."
/// The CLI layer merges this with command-line flags.
#[derive(Debug, Clone, Default)]
pub struct FileConfig {
    pub threshold: Option<f64>,
    pub preset: Option<ThresholdPreset>,
    pub metric: Option<ComplexityMetric>,
    pub src: Option<PathBuf>,
    pub exclude: Option<Vec<String>>,
    pub overrides: Vec<ThresholdOverride>,
    /// Saved view presets keyed by preset name.
    ///
    /// Each `[views.<name>]` block in TOML deserializes into a
    /// [`ViewPreset`]; the CLI layer resolves `--view <name>` against
    /// this map and folds preset values into `Cli` before
    /// `build_view_spec`.
    pub views: HashMap<String, ViewPreset>,
    /// Output-shaping settings under `[output]`.
    ///
    /// Reporter-specific knobs (today: `annotation_limit`) live here
    /// so they share a single TOML namespace rather than polluting the
    /// top-level table. Missing `[output]` blocks deserialize to
    /// `OutputConfig::default()`.
    pub output: OutputConfig,
}

/// Reporter-level output settings (TOML `[output]` table).
///
/// All fields are optional — missing fields mean "use CLI default."
#[derive(Debug, Clone, Default, PartialEq)]
pub struct OutputConfig {
    /// Cap on the number of `::warning` annotations emitted by the
    /// `github-annotations` reporter per invocation. `None` defers to
    /// the CLI default (10); a CLI `--annotation-limit` flag always
    /// wins over this value when both are set.
    pub annotation_limit: Option<u32>,
}

/// Saved view preset.
///
/// All fields are optional — `None` means "preset does not assert this
/// field, defer to CLI / defaults." Booleans are `Option<bool>` so the
/// preset can distinguish "absent" from "explicitly false," which lets
/// the CLI layer treat a CLI bool of `false` as "user didn't say"
/// (OR-merge semantics — see `apply_preset_to_cli`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ViewPreset {
    pub top: Option<u32>,
    pub min_coverage: Option<f64>,
    pub max_coverage: Option<f64>,
    pub sort: Option<SortKey>,
    pub only_failing: Option<bool>,
    pub no_fail: Option<bool>,
    pub group_by: Option<GroupKey>,
    pub minimal_view: Option<bool>,
}

// ── TOML serde types (private) ─────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    threshold: Option<f64>,
    preset: Option<String>,
    metric: Option<String>,
    src: Option<String>,
    exclude: Option<Vec<String>>,
    #[serde(default)]
    overrides: Vec<RawOverride>,
    #[serde(default)]
    views: HashMap<String, RawViewPreset>,
    #[serde(default)]
    output: RawOutputConfig,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawOutputConfig {
    annotation_limit: Option<u32>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawOverride {
    pattern: String,
    threshold: f64,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawViewPreset {
    top: Option<u32>,
    min_coverage: Option<f64>,
    max_coverage: Option<f64>,
    sort: Option<String>,
    only_failing: Option<bool>,
    no_fail: Option<bool>,
    group_by: Option<String>,
    minimal_view: Option<bool>,
}

// ── Public API ─────────────────────────────────────────────────────

/// Discover the adapter's config file in the current working directory.
///
/// `name` is the adapter-specific file name (e.g., `"crap4rs.toml"` for
/// the Rust adapter; `"crap4ts.toml"` for the TS adapter). Supplied by
/// the binary via `AdapterMeta.config_file_name`.
///
/// Returns `Ok(Some(path))` if the file exists, `Ok(None)` if absent.
/// Returns `Err` on permission errors or other filesystem failures.
pub fn discover_config(name: &str) -> Result<Option<PathBuf>> {
    let path = PathBuf::from(name);
    match std::fs::metadata(&path) {
        Ok(m) if m.is_file() => Ok(Some(path)),
        Ok(_) => Ok(None), // exists but not a file (directory, symlink to dir, etc.)
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => anyhow::bail!(
            "cannot access config file {}: {e}\n  hint: check file permissions",
            path.display()
        ),
    }
}

/// Load and parse a config file from the given path.
pub fn load_config(path: &Path) -> Result<FileConfig> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config file: {}", path.display()))?;
    parse_config(&content)
        .with_context(|| format!("failed to parse config file: {}", path.display()))
}

/// Parse TOML content into a `FileConfig`.
fn parse_config(content: &str) -> Result<FileConfig> {
    let raw: RawConfig = toml::from_str(content)?;
    validate_raw_config(&raw)?;

    let metric = raw.metric.as_deref().map(parse_metric).transpose()?;
    let preset = raw.preset.as_deref().map(parse_preset).transpose()?;

    let overrides = raw
        .overrides
        .into_iter()
        .map(|o| ThresholdOverride {
            pattern: o.pattern,
            threshold: o.threshold,
        })
        .collect();

    let views = raw
        .views
        .into_iter()
        .map(|(name, raw_preset)| {
            let preset = parse_view_preset(&name, raw_preset)?;
            Ok::<_, anyhow::Error>((name, preset))
        })
        .collect::<Result<HashMap<_, _>>>()?;

    Ok(FileConfig {
        threshold: raw.threshold,
        preset,
        metric,
        src: raw.src.map(PathBuf::from),
        exclude: raw.exclude,
        overrides,
        views,
        output: OutputConfig {
            annotation_limit: raw.output.annotation_limit,
        },
    })
}

fn validate_raw_config(raw: &RawConfig) -> Result<()> {
    if raw.preset.is_some() && raw.threshold.is_some() {
        anyhow::bail!("preset and threshold are mutually exclusive in config");
    }
    if let Some(t) = raw.threshold
        && !is_valid_threshold(t)
    {
        anyhow::bail!("threshold must be a finite positive number, got: {t}");
    }
    for o in &raw.overrides {
        if !is_valid_threshold(o.threshold) {
            anyhow::bail!(
                "override threshold must be a finite positive number, got: {} (pattern: {})",
                o.threshold,
                o.pattern
            );
        }
    }
    // Mirror the CLI's `clap::value_parser!(u32).range(1..=100)` on
    // `--annotation-limit` so config and CLI agree on the legal range.
    // Without this check a TOML `[output] annotation_limit = 0` would
    // silently disable annotation emission (only the truncation notice
    // fires); `= 999` would silently flood the per-step UI cap. Both
    // are rejected by clap at the CLI boundary — config must match.
    if let Some(limit) = raw.output.annotation_limit
        && !(1..=100).contains(&limit)
    {
        anyhow::bail!(
            "output.annotation_limit must be in 1..=100, got: {limit}\n  hint: matches the CLI `--annotation-limit` range; 0 disables emission, > 100 floods the GH Actions per-step cap"
        );
    }
    Ok(())
}

fn parse_view_preset(name: &str, raw: RawViewPreset) -> Result<ViewPreset> {
    let sort = raw
        .sort
        .as_deref()
        .map(|s| parse_sort_key(name, s))
        .transpose()?;
    let group_by = raw
        .group_by
        .as_deref()
        .map(|s| parse_group_key(name, s))
        .transpose()?;
    validate_preset_coverage_range(name, raw.min_coverage, raw.max_coverage)?;
    Ok(ViewPreset {
        top: raw.top,
        min_coverage: raw.min_coverage,
        max_coverage: raw.max_coverage,
        sort,
        only_failing: raw.only_failing,
        no_fail: raw.no_fail,
        group_by,
        minimal_view: raw.minimal_view,
    })
}

fn parse_sort_key(preset_name: &str, s: &str) -> Result<SortKey> {
    match s {
        "crap" => Ok(SortKey::Crap),
        "coverage" => Ok(SortKey::Coverage),
        "complexity" => Ok(SortKey::Complexity),
        "path" => Ok(SortKey::Path),
        other => anyhow::bail!(
            "preset `{preset_name}`: unknown sort: {other}\n  valid values: crap, coverage, complexity, path"
        ),
    }
}

fn parse_group_key(preset_name: &str, s: &str) -> Result<GroupKey> {
    match s {
        "file" => Ok(GroupKey::File),
        other => {
            anyhow::bail!("preset `{preset_name}`: unknown group_by: {other}\n  valid values: file")
        }
    }
}

/// Validate the preset's coverage bounds in isolation (fail-fast at config
/// load). Either-side-only is allowed and the absent side is
/// defaulted to `0` / `100` for the relational check, mirroring CLI
/// `validate_view_args` so a preset that would resolve to an invalid range
/// is rejected at TOML parse time rather than at `--view` resolution.
fn validate_preset_coverage_range(
    preset_name: &str,
    min: Option<f64>,
    max: Option<f64>,
) -> Result<()> {
    if min.is_none() && max.is_none() {
        return Ok(());
    }
    let lo = min.unwrap_or(0.0);
    let hi = max.unwrap_or(100.0);
    // `CoverageRangeError` has `#[non_exhaustive]` paused per ADR D10
    // (restored at v1.0). Now that this adapter lives in crap-core
    // alongside the enum, the match is in-crate and exhaustive — no
    // wildcard arm needed. v1.0 new variants will require an
    // explicit arm here.
    match CoverageRange::new(lo, hi) {
        Ok(_) => Ok(()),
        Err(CoverageRangeError::OutOfRange { value }) => anyhow::bail!(
            "preset `{preset_name}`: coverage value out of range: {value}\n  valid range: [0, 100]"
        ),
        Err(CoverageRangeError::MinExceedsMax { min, max }) => anyhow::bail!(
            "preset `{preset_name}`: min_coverage ({min}) must not exceed max_coverage ({max})"
        ),
    }
}

fn parse_preset(s: &str) -> Result<ThresholdPreset> {
    match s {
        "strict" => Ok(ThresholdPreset::Strict),
        "default" => Ok(ThresholdPreset::Default),
        "lenient" => Ok(ThresholdPreset::Lenient),
        other => anyhow::bail!("unknown preset: {other}\n  valid values: strict, default, lenient"),
    }
}

fn parse_metric(s: &str) -> Result<ComplexityMetric> {
    match s {
        "cognitive" => Ok(ComplexityMetric::Cognitive),
        "cyclomatic" => Ok(ComplexityMetric::Cyclomatic),
        other => anyhow::bail!("unknown metric: {other}\n  valid values: cognitive, cyclomatic"),
    }
}

// ── Tests ──────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_full_config() {
        let toml = r#"
threshold = 10.0
metric = "cyclomatic"
src = "crates"
exclude = ["tests/**", "benches/**"]

[[overrides]]
pattern = "domain/**"
threshold = 5.0

[[overrides]]
pattern = "adapters/**"
threshold = 15.0
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, Some(10.0));
        assert_eq!(config.metric, Some(ComplexityMetric::Cyclomatic));
        assert_eq!(config.src, Some(PathBuf::from("crates")));
        assert_eq!(
            config.exclude,
            Some(vec!["tests/**".to_string(), "benches/**".to_string()])
        );
        assert_eq!(config.overrides.len(), 2);
        assert_eq!(config.overrides[0].pattern, "domain/**");
        assert_eq!(config.overrides[0].threshold, 5.0);
        assert_eq!(config.overrides[1].pattern, "adapters/**");
        assert_eq!(config.overrides[1].threshold, 15.0);
    }

    #[test]
    fn parse_minimal_config() {
        let toml = "";
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, None);
        assert_eq!(config.metric, None);
        assert_eq!(config.src, None);
        assert_eq!(config.exclude, None);
        assert!(config.overrides.is_empty());
    }

    #[test]
    fn parse_threshold_only() {
        let toml = "threshold = 12.5\n";
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, Some(12.5));
        assert_eq!(config.metric, None);
    }

    #[test]
    fn parse_overrides_only() {
        let toml = r#"
[[overrides]]
pattern = "core/**"
threshold = 3.0
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, None);
        assert_eq!(config.overrides.len(), 1);
    }

    #[test]
    fn parse_metric_cognitive() {
        let toml = r#"metric = "cognitive""#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.metric, Some(ComplexityMetric::Cognitive));
    }

    #[test]
    fn parse_metric_cyclomatic() {
        let toml = r#"metric = "cyclomatic""#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.metric, Some(ComplexityMetric::Cyclomatic));
    }

    #[test]
    fn invalid_metric_rejected() {
        let toml = r#"metric = "halstead""#;
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("unknown metric"));
    }

    #[test]
    fn negative_threshold_rejected() {
        let toml = "threshold = -5.0\n";
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("finite positive"));
    }

    #[test]
    fn zero_threshold_rejected() {
        let toml = "threshold = 0.0\n";
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("finite positive"));
    }

    #[test]
    fn inf_threshold_rejected() {
        let toml = "threshold = inf\n";
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("finite positive"));
    }

    #[test]
    fn negative_override_threshold_rejected() {
        let toml = r#"
[[overrides]]
pattern = "src/**"
threshold = -1.0
"#;
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("finite positive"));
    }

    #[test]
    fn unknown_field_rejected() {
        let toml = "unknown_key = true\n";
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("unknown"));
    }

    #[test]
    fn malformed_toml_rejected() {
        let toml = "this is not toml [[[";
        assert!(parse_config(toml).is_err());
    }

    #[test]
    fn zero_override_threshold_rejected() {
        let toml = r#"
[[overrides]]
pattern = "src/**"
threshold = 0.0
"#;
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("finite positive"));
    }

    #[test]
    fn parse_preset_strict() {
        let config = parse_config(r#"preset = "strict""#).unwrap();
        assert_eq!(config.preset, Some(ThresholdPreset::Strict));
        assert_eq!(config.threshold, None);
    }

    #[test]
    fn parse_preset_default() {
        let config = parse_config(r#"preset = "default""#).unwrap();
        assert_eq!(config.preset, Some(ThresholdPreset::Default));
    }

    #[test]
    fn parse_preset_lenient() {
        let config = parse_config(r#"preset = "lenient""#).unwrap();
        assert_eq!(config.preset, Some(ThresholdPreset::Lenient));
    }

    #[test]
    fn preset_and_threshold_mutually_exclusive() {
        let toml = "preset = \"strict\"\nthreshold = 10.0\n";
        let err = parse_config(toml).unwrap_err();
        assert!(err.to_string().contains("mutually exclusive"));
    }

    #[test]
    fn unknown_preset_rejected() {
        let err = parse_config(r#"preset = "extreme""#).unwrap_err();
        assert!(err.to_string().contains("unknown preset"));
    }

    #[test]
    fn load_config_missing_file() {
        let err = load_config(Path::new("nonexistent.toml")).unwrap_err();
        assert!(err.to_string().contains("failed to read config file"));
    }

    #[test]
    fn load_config_valid_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("crap4rs.toml");
        std::fs::write(&path, "threshold = 10.0\n").unwrap();

        let config = load_config(&path).unwrap();
        assert_eq!(config.threshold, Some(10.0));
    }

    #[test]
    fn load_config_invalid_toml() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("crap4rs.toml");
        std::fs::write(&path, "not valid toml [[[").unwrap();

        let err = load_config(&path).unwrap_err();
        assert!(err.to_string().contains("failed to parse config file"));
    }

    // ── ViewPreset tests ───────────────────────────────────

    #[test]
    fn parse_no_views_table_yields_empty_map() {
        // Back-compat: existing TOML with no `[views]` blocks must continue
        // to parse with `views == HashMap::new()`.
        let config = parse_config("threshold = 10.0\n").unwrap();
        assert_eq!(config.threshold, Some(10.0));
        assert!(config.views.is_empty());
    }

    #[test]
    fn parse_empty_view_block_yields_default_preset() {
        let toml = "[views.ci]\n";
        let config = parse_config(toml).unwrap();
        assert_eq!(config.views.len(), 1);
        let ci = config.views.get("ci").expect("preset `ci` parsed");
        assert_eq!(*ci, ViewPreset::default());
    }

    #[test]
    fn parse_full_view_block_parses_every_field() {
        let toml = r#"
[views.ci]
top = 20
min_coverage = 0
max_coverage = 90
sort = "coverage"
only_failing = true
no_fail = false
group_by = "file"
minimal_view = true
"#;
        let config = parse_config(toml).unwrap();
        let ci = config.views.get("ci").expect("preset `ci` parsed");
        assert_eq!(ci.top, Some(20));
        assert_eq!(ci.min_coverage, Some(0.0));
        assert_eq!(ci.max_coverage, Some(90.0));
        assert_eq!(ci.sort, Some(SortKey::Coverage));
        assert_eq!(ci.only_failing, Some(true));
        assert_eq!(ci.no_fail, Some(false));
        assert_eq!(ci.group_by, Some(GroupKey::File));
        assert_eq!(ci.minimal_view, Some(true));
    }

    #[test]
    fn parse_unknown_view_field_rejected() {
        let toml = r#"
[views.ci]
top = 5
diff_ref = "main"
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unknown") || msg.contains("diff_ref"),
            "expected deny_unknown_fields error, got: {msg}"
        );
    }

    #[test]
    fn parse_bad_sort_string_rejected() {
        let toml = r#"
[views.ci]
sort = "nonsense"
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown sort"), "got: {msg}");
        assert!(msg.contains("ci"), "error must name preset, got: {msg}");
    }

    #[test]
    fn parse_bad_group_by_string_rejected() {
        let toml = r#"
[views.ci]
group_by = "module"
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown group_by"), "got: {msg}");
        assert!(msg.contains("ci"), "error must name preset, got: {msg}");
    }

    #[test]
    fn parse_multiple_view_presets_independent() {
        let toml = r#"
[views.ci]
top = 20
sort = "coverage"

[views.investigate]
top = 10
sort = "complexity"
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.views.len(), 2);
        let ci = config.views.get("ci").unwrap();
        assert_eq!(ci.top, Some(20));
        assert_eq!(ci.sort, Some(SortKey::Coverage));
        let inv = config.views.get("investigate").unwrap();
        assert_eq!(inv.top, Some(10));
        assert_eq!(inv.sort, Some(SortKey::Complexity));
    }

    #[test]
    fn parse_view_preset_top_zero_accepted() {
        // `top = 0` is canonicalised to `None` by `build_view_spec` (per
        // existing CLI semantic — see `cli/view_args.rs::build_view_spec`).
        // Config-load must accept the value rather than reject it.
        let toml = r#"
[views.ci]
top = 0
"#;
        let config = parse_config(toml).unwrap();
        let ci = config.views.get("ci").unwrap();
        assert_eq!(ci.top, Some(0));
    }

    #[test]
    fn parse_view_preset_min_coverage_out_of_range_rejected() {
        let toml = r#"
[views.ci]
min_coverage = -1
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("out of range"), "got: {msg}");
        assert!(msg.contains("ci"), "error must name preset, got: {msg}");
    }

    #[test]
    fn parse_view_preset_max_coverage_out_of_range_rejected() {
        let toml = r#"
[views.ci]
max_coverage = 105
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("out of range"), "got: {msg}");
    }

    #[test]
    fn parse_view_preset_min_exceeds_max_rejected() {
        let toml = r#"
[views.ci]
min_coverage = 90
max_coverage = 30
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("must not exceed") || msg.contains("exceeds"),
            "got: {msg}"
        );
        assert!(msg.contains("ci"), "error must name preset, got: {msg}");
    }

    #[test]
    fn parse_view_preset_min_only_resolves_to_full_upper_bound() {
        // `min_coverage = 50` alone (no `max_coverage`) is valid because
        // the absent side defaults to 100 — mirrors CLI semantics in
        // `cli::view_args::resolve_coverage_bounds`.
        let toml = r#"
[views.ci]
min_coverage = 50
"#;
        let config = parse_config(toml).unwrap();
        let ci = config.views.get("ci").unwrap();
        assert_eq!(ci.min_coverage, Some(50.0));
        assert_eq!(ci.max_coverage, None);
    }

    #[test]
    fn parse_view_preset_alongside_threshold() {
        // Existing top-level fields and view presets coexist.
        let toml = r#"
threshold = 12.0

[views.ci]
top = 20
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, Some(12.0));
        assert_eq!(config.views.len(), 1);
        assert_eq!(config.views["ci"].top, Some(20));
    }

    #[test]
    fn parse_view_preset_all_sort_variants() {
        let toml = r#"
[views.crap_sort]
sort = "crap"

[views.coverage_sort]
sort = "coverage"

[views.complexity_sort]
sort = "complexity"

[views.path_sort]
sort = "path"
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.views["crap_sort"].sort, Some(SortKey::Crap));
        assert_eq!(config.views["coverage_sort"].sort, Some(SortKey::Coverage));
        assert_eq!(
            config.views["complexity_sort"].sort,
            Some(SortKey::Complexity)
        );
        assert_eq!(config.views["path_sort"].sort, Some(SortKey::Path));
    }

    // ── OutputConfig tests ───────────────────────────────────────

    #[test]
    fn parse_no_output_table_yields_default_output_config() {
        // Back-compat: every existing crap4rs.toml lacks `[output]` and
        // must continue to parse with the new field defaulted.
        let config = parse_config("threshold = 10.0\n").unwrap();
        assert_eq!(config.output, OutputConfig::default());
        assert_eq!(config.output.annotation_limit, None);
    }

    #[test]
    fn parse_output_annotation_limit() {
        let toml = "[output]\nannotation_limit = 25\n";
        let config = parse_config(toml).unwrap();
        assert_eq!(config.output.annotation_limit, Some(25));
    }

    #[test]
    fn parse_output_alongside_threshold() {
        let toml = r#"
threshold = 12.0

[output]
annotation_limit = 7
"#;
        let config = parse_config(toml).unwrap();
        assert_eq!(config.threshold, Some(12.0));
        assert_eq!(config.output.annotation_limit, Some(7));
    }

    #[test]
    fn parse_output_annotation_limit_zero_rejected() {
        // 0 would silently disable annotation emission (the reporter
        // takes 0 of the eligible set + only emits the truncation
        // notice). Clap rejects 0 at the CLI boundary via
        // `value_parser!(u32).range(1..=100)`; config must match.
        let toml = "[output]\nannotation_limit = 0\n";
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("annotation_limit") && msg.contains("1..=100"),
            "expected range error, got: {msg}"
        );
    }

    #[test]
    fn parse_output_annotation_limit_above_max_rejected() {
        // 101+ would silently flood the GH Actions per-step UI cap
        // (10 warning per step; anything past 10 is dropped by the
        // runner). Clap rejects at the CLI; config must match.
        let toml = "[output]\nannotation_limit = 101\n";
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("annotation_limit") && msg.contains("1..=100"),
            "expected range error, got: {msg}"
        );
    }

    #[test]
    fn parse_output_annotation_limit_boundary_values_accepted() {
        for v in [1u32, 10, 50, 100] {
            let toml = format!("[output]\nannotation_limit = {v}\n");
            let config = parse_config(&toml).expect("boundary value should parse");
            assert_eq!(config.output.annotation_limit, Some(v));
        }
    }

    #[test]
    fn parse_unknown_output_field_rejected() {
        // deny_unknown_fields guards forward-compat: a TOML pinned at
        // an old crap4rs version must still surface unrecognised output
        // settings as load-time errors rather than silently dropping
        // them.
        let toml = r#"
[output]
annotation_limit = 5
nonsense_field = "x"
"#;
        let err = parse_config(toml).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unknown") || msg.contains("nonsense_field"),
            "expected deny_unknown_fields error, got: {msg}"
        );
    }

    // ── discover_config parameterization (#161) ───────────────────

    #[test]
    fn discover_config_honors_caller_supplied_name() {
        // Verifies the `name` parameter actually drives lookup — a
        // regression would silently fall back to a hardcoded constant
        // (e.g., the v0.4 `crap4rs.toml` literal) and make the second
        // adapter (`crap4ts.toml`) invisible to discovery.
        //
        // `discover_config` interprets `name` as a path (it calls
        // `PathBuf::from(name)` and feeds it to `std::fs::metadata`),
        // so passing tempdir-qualified paths avoids any process-wide
        // CWD mutation. This keeps the test safe under nextest's
        // parallel execution model.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("crap4ts.toml"), "threshold = 7.0\n").unwrap();

        let rust_path = dir.path().join("crap4rs.toml");
        let ts_path = dir.path().join("crap4ts.toml");
        let alt_path = dir.path().join("custom-tool.toml");

        let rust_lookup = discover_config(rust_path.to_str().unwrap()).unwrap();
        let ts_lookup = discover_config(ts_path.to_str().unwrap()).unwrap();
        let alt_lookup = discover_config(alt_path.to_str().unwrap()).unwrap();

        assert_eq!(rust_lookup, None, "absent crap4rs.toml must return None");
        assert_eq!(
            ts_lookup,
            Some(ts_path.clone()),
            "present crap4ts.toml must be discovered by name"
        );
        assert_eq!(alt_lookup, None, "absent custom name must return None");
    }
}