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
//! Markdown reporter — formats an `AnalysisView` as GitHub-flavored
//! Markdown with a pipe-syntax table and a readable summary block.
//!
//! No ANSI. Suitable for piping into PR comments, issue bodies, or
//! documentation.
//!
//! Rendering goes through an askama compile-time template
//! (`crates/crap-core/templates/markdown_report.txt`, crap-rs#260).
//! Width-aligned numeric fields are pre-formatted in Rust because
//! askama's `{{ }}` interpolation does not honor Rust format
//! specifiers; the template is composition-only.

use crate::cli::AdapterMeta;
use crate::domain::delta::{DeltaView, FunctionChange};
use crate::domain::types::{ComplexityMetric, FunctionVerdict};
use crate::domain::view::AnalysisView;
use askama::Template;

/// Format an `AnalysisView` as GitHub-flavored Markdown.
///
/// Default body shape: title + summary block (multi-metric stats +
/// risk distribution) + a top-N spotlight (failures if any exceed
/// threshold, otherwise the worst by CRAP). Designed to fit comfortably
/// in a PR comment — bounded output regardless of codebase size.
///
/// `breakdown` injects an indented bullet list of complexity
/// contributors under each exceeding function in the spotlight (or
/// the full table when `full_table` is set). `explain` adds a trailing
/// legend describing increment semantics (only meaningful when
/// `breakdown` is set).
///
/// `full_table` switches the body to the legacy row-per-function table
/// rendered after the summary — useful when piping into a longer
/// document instead of a PR comment. Off by default.
///
/// `top_n` bounds the spotlight table size. The summary block is
/// always full-fidelity (computed from `view.full.summary`).
///
/// When `delta` is `Some`, a `## CRAP Scorecard` section is appended
/// after the analysis body — designed for PR-comment rendering.
///
/// `meta` carries the calling binary's identity (the literal
/// `env!("CARGO_PKG_NAME")` value resolves to `crap-core` here, not
/// the adapter binary's name — so the binary supplies its own). The
/// signature widened from `(&str, &str)` to `&AdapterMeta` in
/// crap-rs#260 to thread `display_name` + `default_metric` through
/// to the HTML reporter's per-adapter footer; the markdown reporter
/// only consumes `tool_name` + `tool_version` but takes the bundle
/// for signature symmetry with `format_html`. `effective_metric` is
/// the runtime-resolved metric (post-CLI/config merge); see
/// `EffectiveInputs.metric`.
#[allow(clippy::too_many_arguments)]
pub fn format_markdown(
    view: &AnalysisView<'_>,
    delta: Option<&DeltaView<'_>>,
    threshold: f64,
    breakdown: bool,
    explain: bool,
    full_table: bool,
    top_n: usize,
    meta: &AdapterMeta,
    _effective_metric: ComplexityMetric,
) -> String {
    let body = if view.full.functions.is_empty() {
        MarkdownBody::Empty
    } else {
        let summary = Box::new(summary_data(view, threshold));
        let section = if let Some(grouped) = view.grouped.as_ref() {
            BodySection::Grouped {
                rows: grouped_rows(grouped),
            }
        } else if full_table {
            full_table_section(view, breakdown, explain)
        } else {
            spotlight_section(view, threshold, top_n, breakdown, explain)
        };
        MarkdownBody::Filled { summary, section }
    };

    let delta_block = delta.map(format_markdown_delta);

    let tmpl = MarkdownReport {
        tool_name: meta.tool_name,
        tool_version: meta.tool_version,
        body,
        delta: delta_block,
    };
    let mut out = tmpl
        .render()
        .expect("markdown template render is total — all fields owned");
    // POSIX text files end with `\n`. Pre-PR-#260 the hand-rolled
    // reporter always emitted a trailing newline; askama's `{%-` ws
    // operator strips it in the template, and `insta` snapshot
    // assertions trim trailing whitespace on compare so the drift is
    // invisible to in-process tests. The composite scorecard action's
    // `cat <file>` + `echo "<EOF>"` heredoc emission relies on the
    // trailing `\n` to place the EOF delimiter on its own line — a
    // missing newline collides with the heredoc terminator and breaks
    // GH Actions' `$GITHUB_OUTPUT` parsing. Restore the trailing
    // newline here so the contract holds across all consumers.
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

#[derive(Template)]
#[template(path = "markdown_report.txt", escape = "none")]
struct MarkdownReport<'a> {
    tool_name: &'a str,
    tool_version: &'a str,
    body: MarkdownBody,
    delta: Option<String>,
}

enum MarkdownBody {
    Empty,
    /// `summary` is boxed because `SummaryData` carries ~14 owned
    /// `String` fields — boxing matches the clippy
    /// `large_enum_variant` recommendation and keeps the
    /// `MarkdownBody::Empty` discriminant cheap.
    Filled {
        summary: Box<SummaryData>,
        section: BodySection,
    },
}

struct SummaryData {
    pass_fail: &'static str,
    total_functions: usize,
    threshold_display: String,
    exceeding_threshold: usize,
    crap_max: String,
    crap_avg: String,
    crap_med: String,
    cx_max: String,
    cx_avg: String,
    cx_med: String,
    cov_min: String,
    cov_avg: String,
    cov_med: String,
    dist_low: usize,
    dist_acceptable: usize,
    dist_moderate: usize,
    dist_high: usize,
}

enum BodySection {
    Grouped {
        rows: Vec<GroupedRow>,
    },
    FullTable {
        rows: Vec<FunctionRow>,
        legend: Option<&'static str>,
    },
    Spotlight {
        header: String,
        rows: Vec<FunctionRow>,
        legend: Option<&'static str>,
        footnote: Option<&'static str>,
    },
    /// All summary-displayed, no body table. Used when a clean run has
    /// zero shown rows (e.g. `--only-failing` strips everything).
    None,
}

struct GroupedRow {
    file_path: String,
    function_count: usize,
    exceeding_count: usize,
    average_crap: String,
    worst_crap: String,
    worst_fn: String,
}

struct FunctionRow {
    file: String,
    function: String,
    cc: u32,
    cov: String,
    crap: String,
    risk: String,
    breakdown_bullets: Vec<String>,
}

fn summary_data(view: &AnalysisView<'_>, threshold: f64) -> SummaryData {
    let summary = &view.full.summary;
    let pass_fail = if view.full.passed { "PASS" } else { "FAIL" };
    let crap_max = summary
        .max_crap
        .as_ref()
        .map(|c| format!("{:.2}", c.value))
        .unwrap_or_else(|| "".to_string());
    let d = &summary.distribution;
    SummaryData {
        pass_fail,
        total_functions: summary.total_functions,
        threshold_display: format_threshold(view, threshold),
        exceeding_threshold: summary.exceeding_threshold,
        crap_max,
        crap_avg: format!("{:>7.2}", summary.average_crap),
        crap_med: format!("{:>6.2}", summary.median_crap),
        cx_max: format!("{:>5}", summary.max_complexity),
        cx_avg: format!("{:>7.1}", summary.average_complexity),
        cx_med: format!("{:>6.1}", summary.median_complexity),
        cov_min: format!("{:>4.1}%", summary.min_coverage),
        cov_avg: format!("{:>6.1}%", summary.average_coverage),
        cov_med: format!("{:>5.1}%", summary.median_coverage),
        dist_low: d.low,
        dist_acceptable: d.acceptable,
        dist_moderate: d.moderate,
        dist_high: d.high,
    }
}

fn grouped_rows(grouped: &crate::domain::view::GroupedView) -> Vec<GroupedRow> {
    grouped
        .files
        .iter()
        .map(|f| {
            let worst_crap = f
                .max_crap
                .as_ref()
                .map(|c| format!("{:.2}", c.value))
                .unwrap_or_else(|| "N/A".to_string());
            let worst_fn = f
                .worst_function
                .as_ref()
                .map(|id| escape_cell(&id.qualified_name))
                .unwrap_or_else(|| "".to_string());
            GroupedRow {
                file_path: escape_cell(&f.file_path),
                function_count: f.function_count,
                exceeding_count: f.exceeding_count,
                average_crap: format!("{:.2}", f.average_crap),
                worst_crap,
                worst_fn,
            }
        })
        .collect()
}

fn full_table_section(view: &AnalysisView<'_>, breakdown: bool, explain: bool) -> BodySection {
    let rows: Vec<FunctionRow> = view
        .shown
        .iter()
        .map(|v| function_row(v, breakdown))
        .collect();
    BodySection::FullTable {
        rows,
        legend: legend_if_needed(view, breakdown, explain),
    }
}

fn spotlight_section(
    view: &AnalysisView<'_>,
    threshold: f64,
    top_n: usize,
    breakdown: bool,
    explain: bool,
) -> BodySection {
    let summary = &view.full.summary;

    if summary.exceeding_threshold == 0 {
        let worst = top_n_by_crap(view.shown.iter().copied(), top_n);
        if worst.is_empty() {
            return BodySection::None;
        }
        let header = format!("## Top {} worst by CRAP", worst.len());
        let rows: Vec<FunctionRow> = worst.iter().map(|v| function_row(v, breakdown)).collect();
        return BodySection::Spotlight {
            header,
            rows,
            legend: legend_if_needed(view, breakdown, explain),
            footnote: Some("\n_All functions are within threshold._"),
        };
    }

    let shown_failures: Vec<&FunctionVerdict> =
        top_n_by_crap(view.shown.iter().copied().filter(|v| v.exceeds), top_n);
    let header = if summary.exceeding_threshold > shown_failures.len() {
        format!(
            "## Failures (top {} of {} above threshold {})",
            shown_failures.len(),
            summary.exceeding_threshold,
            format_threshold(view, threshold),
        )
    } else {
        format!(
            "## Failures ({} above threshold {})",
            summary.exceeding_threshold,
            format_threshold(view, threshold),
        )
    };
    let rows: Vec<FunctionRow> = shown_failures
        .iter()
        .map(|v| function_row(v, breakdown))
        .collect();
    BodySection::Spotlight {
        header,
        rows,
        legend: legend_if_needed(view, breakdown, explain),
        footnote: None,
    }
}

fn function_row(verdict: &FunctionVerdict, breakdown: bool) -> FunctionRow {
    let s = &verdict.scored;
    let bullets = breakdown_bullets(verdict, breakdown);
    FunctionRow {
        file: escape_cell(&s.identity.file_path),
        function: escape_cell(&s.identity.qualified_name),
        cc: s.complexity,
        cov: format!("{:.1}", s.coverage_percent),
        crap: format!("{:.2}", s.crap.value),
        risk: s.crap.risk_level.to_string(),
        breakdown_bullets: bullets,
    }
}

fn breakdown_bullets(verdict: &FunctionVerdict, breakdown: bool) -> Vec<String> {
    if !breakdown || !verdict.exceeds || verdict.scored.contributors.is_empty() {
        return Vec::new();
    }
    verdict
        .scored
        .contributors
        .iter()
        .map(|c| format!("  - L{} {} +{}", c.line, c.kind, c.increment))
        .collect()
}

fn top_n_by_crap<'a, I>(iter: I, n: usize) -> Vec<&'a FunctionVerdict>
where
    I: IntoIterator<Item = &'a FunctionVerdict>,
{
    let mut v: Vec<&FunctionVerdict> = iter.into_iter().collect();
    v.sort_by(|a, b| {
        b.scored
            .crap
            .value
            .partial_cmp(&a.scored.crap.value)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    v.truncate(n);
    v
}

const LEGEND: &str = "_Legend: +1 = base structural increment. +N (nested) = +1 base plus +(N-1) from active nesting depth (if/else, match arms, while/for/loop, let-else diverging branches, closures)._";

fn legend_if_needed(
    view: &AnalysisView<'_>,
    breakdown: bool,
    explain: bool,
) -> Option<&'static str> {
    if breakdown && explain && needs_legend(view) {
        Some(LEGEND)
    } else {
        None
    }
}

fn needs_legend(view: &AnalysisView<'_>) -> bool {
    view.shown
        .iter()
        .filter(|v| v.exceeds)
        .flat_map(|v| v.scored.contributors.iter())
        .any(|c| c.increment > 1)
}

fn format_threshold(view: &AnalysisView<'_>, threshold: f64) -> String {
    if has_varied_thresholds(&view.full.functions) {
        format!("varied (default: {})", threshold)
    } else {
        format!("{}", threshold)
    }
}

fn has_varied_thresholds(functions: &[FunctionVerdict]) -> bool {
    let mut iter = functions.iter().map(|v| v.threshold);
    let Some(first) = iter.next() else {
        return false;
    };
    iter.any(|t| (t - first).abs() > f64::EPSILON)
}

/// Render the delta scorecard block. Format is stable enough to drop
/// into PR comments verbatim. Counts come from `view.full.summary`
/// (the unshapeable gate); regression / new-violation tables iterate
/// `view.shown` so `--delta-top` / `--delta-only` shape the rendered
/// rows but not the counts.
fn format_markdown_delta(view: &DeltaView<'_>) -> String {
    let summary = &view.full.summary;
    let status = if summary.passed { "PASS" } else { "FAIL" };

    let mut out = String::new();
    out.push_str("## CRAP Scorecard\n\n");
    out.push_str(&format!("- **Delta status:** {status}\n"));
    out.push_str(&format!(
        "- **Changes:** +{added} added, {removed} removed, {modified} modified\n",
        added = summary.added,
        removed = summary.removed,
        modified = summary.modified,
    ));
    out.push_str(&format!(
        "- **Regressions:** {regressions} · **Improvements:** {improvements} · **New violations:** {new_violations}\n",
        regressions = summary.regressions,
        improvements = summary.improvements,
        new_violations = summary.new_violations,
    ));

    // Filter threshold matches the `{:.2}` cell-rendering precision:
    // a delta below 0.005 rounds to "+0.00" in the table and looks
    // like a falsely-flagged regression. Anything that rounds up to
    // ≥ +0.01 is admitted. (CrapScore values are themselves
    // 2-decimal rounded, so this gate rarely fires in practice — but
    // float arithmetic can produce sub-0.005 noise on identity
    // comparisons.)
    let regressions: Vec<&FunctionChange> = view
        .shown
        .iter()
        .copied()
        .filter(|c| {
            matches!(c, FunctionChange::Modified { .. }) && c.score_delta().unwrap_or(0.0) >= 0.005
        })
        .collect();
    if !regressions.is_empty() {
        out.push_str("\n### Regressions\n\n");
        out.push_str("| File | Function | Baseline CRAP | Current CRAP | Δ |\n");
        out.push_str("|------|----------|--------------:|-------------:|--:|\n");
        for change in regressions {
            let baseline = change.baseline_score().unwrap_or(0.0);
            let current = change.current_score().unwrap_or(0.0);
            let delta = change.score_delta().unwrap_or(0.0);
            out.push_str(&format!(
                "| {} | {} | {:.2} | {:.2} | +{:.2} |\n",
                escape_cell(change.file_path()),
                escape_cell(change.qualified_name()),
                baseline,
                current,
                delta,
            ));
        }
    }

    let new_violations: Vec<&FunctionChange> = view
        .shown
        .iter()
        .copied()
        .filter(|c| match c {
            FunctionChange::Added { current } => current.exceeds,
            FunctionChange::Modified { baseline, current } => !baseline.exceeds && current.exceeds,
            FunctionChange::Removed { .. } => false,
            // `FunctionChange` has `#[non_exhaustive]` paused per ADR
            // D10 (restored at v1.0). In-crate match is exhaustive —
            // no wildcard arm needed. v1.0 new variants will require
            // an explicit arm here.
        })
        .collect();
    if !new_violations.is_empty() {
        out.push_str("\n### New violations\n\n");
        out.push_str("| File | Function | Current CRAP |\n");
        out.push_str("|------|----------|-------------:|\n");
        for change in new_violations {
            let current = change.current_score().unwrap_or(0.0);
            out.push_str(&format!(
                "| {} | {} | {:.2} |\n",
                escape_cell(change.file_path()),
                escape_cell(change.qualified_name()),
                current,
            ));
        }
    }

    out
}

/// Escape characters with special meaning inside a GFM table cell.
/// Pipes break the cell boundary; backslashes can interfere with
/// downstream rendering. Newlines are replaced with spaces — qualified
/// names and file paths shouldn't contain them, but defend anyway.
fn escape_cell(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '|' => out.push_str("\\|"),
            '\\' => out.push_str("\\\\"),
            '\n' | '\r' => out.push(' '),
            _ => out.push(ch),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::reporters::test_fixtures::*;

    /// Build a synthetic `AdapterMeta` for reporter tests. Mirrors the
    /// in-crate `fake_meta` pattern from `cli/mod.rs` but stays local
    /// to the reporter module so tests don't reach across module
    /// boundaries.
    fn test_meta() -> AdapterMeta {
        AdapterMeta {
            tool_name: TEST_TOOL_NAME,
            display_name: "Test",
            tool_version: TEST_TOOL_VERSION,
            long_version: TEST_TOOL_VERSION,
            about: "test",
            long_about: "test",
            after_help: "",
            coverage_hint: "test",
            extensions: &["rs"],
            tool_info_uri: TEST_TOOL_INFO_URI,
            rule_help_uri: TEST_RULE_HELP_URI,
            config_file_name: "test-adapter.toml",
            default_excludes: &[],
            forced_excludes: &[],
            default_metric: ComplexityMetric::Cognitive,
        }
    }

    fn md(view: &AnalysisView<'_>) -> String {
        format_markdown(
            view,
            None,
            8.0,
            false,
            false,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        )
    }

    #[test]
    fn header_row_pipes_and_columns() {
        let result = make_multi_function_result();
        let out = md(&make_view_default(&result));
        assert!(out.contains("| File | Function | CC | Cov% | CRAP | Risk |"));
        assert!(out.contains("|------|"));
    }

    #[test]
    fn empty_analysis_says_no_functions() {
        let result = make_empty_result();
        let out = md(&make_view_default(&result));
        assert!(out.contains("No functions analyzed"));
        assert!(!out.contains("| File |"));
    }

    #[test]
    fn pipe_in_function_name_is_escaped() {
        let result =
            make_single_function_result("a|b", "src/lib.rs", 1, 100.0, 1.0, RiskLevel::Low, 8.0);
        let out = md(&make_view_default(&result));
        assert!(out.contains("a\\|b"), "expected escaped pipe in: {out}");
    }

    #[test]
    fn summary_reflects_full_analysis_not_view() {
        let result = make_multi_function_result();
        let out = md(&make_view_default(&result));
        assert!(out.contains("**Result:** FAIL"));
        assert!(out.contains("**Functions:** 3"));
        assert!(out.contains("**Above threshold (8):** 2"));
    }

    #[test]
    fn full_markdown_snapshot() {
        let result = make_multi_function_result();
        let out = md(&make_view_default(&result));
        insta::assert_snapshot!(out);
    }

    #[test]
    fn md_full_table_renders_all_functions_section() {
        let result = make_multi_function_result();
        let out = format_markdown(
            &make_view_default(&result),
            None,
            8.0,
            false,
            false,
            true,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        assert!(out.contains("## Summary"));
        assert!(out.contains("## All functions"));
        assert!(out.contains("complex_fn"));
        assert!(out.contains("parse_record"));
        assert!(out.contains("simple_fn"));
        assert!(!out.contains("## Failures"));
        assert!(!out.contains("## Top "));
    }

    #[test]
    fn md_full_table_with_breakdown_includes_contributors_and_legend() {
        use crate::domain::types::{AnalysisResult, ComplexityContributor, ContributorKind};
        let verdict = make_verdict_with_contributors(
            make_verdict(
                "risky_fn",
                "src/lib.rs",
                5,
                30.0,
                45.0,
                RiskLevel::High,
                8.0,
            ),
            vec![
                ComplexityContributor {
                    kind: ContributorKind::IfBranch,
                    line: 12,
                    column: None,
                    increment: 1,
                    end_line: 12,
                    nesting_depth: 0,
                },
                ComplexityContributor {
                    kind: ContributorKind::Match,
                    line: 18,
                    column: None,
                    increment: 2,
                    end_line: 18,
                    nesting_depth: 1,
                },
            ],
        );
        let result = AnalysisResult {
            functions: vec![verdict.clone()],
            summary: crate::domain::summary::compute_summary(std::slice::from_ref(&verdict)),
            passed: false,
        };
        let out = format_markdown(
            &make_view_default(&result),
            None,
            8.0,
            true,
            true,
            true,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        assert!(out.contains("## All functions"));
        assert!(out.contains("L12 if-branch +1"));
        assert!(out.contains("L18 match +2"));
        assert!(out.contains("Legend:"));
    }

    #[test]
    fn full_markdown_breakdown_snapshot() {
        use crate::domain::types::{AnalysisResult, ComplexityContributor, ContributorKind};
        let verdict = make_verdict_with_contributors(
            make_verdict(
                "risky_fn",
                "src/lib.rs",
                5,
                30.0,
                45.0,
                RiskLevel::High,
                8.0,
            ),
            vec![
                ComplexityContributor {
                    kind: ContributorKind::IfBranch,
                    line: 5,
                    column: Some(4),
                    increment: 1,
                    end_line: 5,
                    nesting_depth: 0,
                },
                ComplexityContributor {
                    kind: ContributorKind::ForLoop,
                    line: 10,
                    column: Some(4),
                    increment: 2,
                    end_line: 10,
                    nesting_depth: 1,
                },
            ],
        );
        let result = AnalysisResult {
            functions: vec![verdict],
            summary: make_multi_function_result().summary,
            passed: false,
        };
        let out = format_markdown(
            &make_view_default(&result),
            None,
            8.0,
            true,
            true,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        insta::assert_snapshot!(out);
    }

    use crate::domain::types::RiskLevel;

    #[test]
    fn grouped_markdown_has_per_file_header() {
        use crate::domain::view::{self, GroupKey, ViewSpec};
        let result = make_multi_function_result();
        let view = view::apply(
            &result,
            ViewSpec {
                group_by: Some(GroupKey::File),
                ..Default::default()
            },
        );
        let out = md(&view);
        assert!(out.contains("| File | Functions | Failing | Avg CRAP | Worst CRAP | Worst Fn |"));
        assert!(!out.contains("| File | Function | CC |"));
        assert!(out.contains("**Functions:** 3"));
        assert!(out.contains("**Above threshold (8):** 2"));
    }

    #[test]
    fn grouped_markdown_snapshot() {
        use crate::domain::view::{self, GroupKey, ViewSpec};
        let result = make_multi_function_result();
        let view = view::apply(
            &result,
            ViewSpec {
                group_by: Some(GroupKey::File),
                ..Default::default()
            },
        );
        let out = md(&view);
        insta::assert_snapshot!(out);
    }

    // ── Delta scorecard (VS5) ───────────────────────────────────────

    #[test]
    fn delta_scorecard_includes_status_and_counts() {
        let delta = make_sample_delta();
        let dview = make_delta_view_default(&delta);
        let out = format_markdown(
            &make_view_default(&delta.current),
            Some(&dview),
            8.0,
            false,
            false,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        assert!(out.contains("## CRAP Scorecard"));
        assert!(out.contains("- **Delta status:** FAIL"));
        assert!(out.contains("+1 added, 1 removed, 2 modified"));
        assert!(out.contains("**New violations:** 1"));
    }

    #[test]
    fn delta_scorecard_renders_regressions_table_when_present() {
        let delta = make_sample_delta();
        let dview = make_delta_view_default(&delta);
        let out = format_markdown(
            &make_view_default(&delta.current),
            Some(&dview),
            8.0,
            false,
            false,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        assert!(out.contains("### Regressions"));
        assert!(out.contains("parse_record"));
        assert!(out.contains("+7.00"));
    }

    #[test]
    fn delta_scorecard_renders_new_violations_table() {
        let delta = make_sample_delta();
        let dview = make_delta_view_default(&delta);
        let out = format_markdown(
            &make_view_default(&delta.current),
            Some(&dview),
            8.0,
            false,
            false,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        assert!(out.contains("### New violations"));
        assert!(out.contains("new_fn"));
    }

    #[test]
    fn no_baseline_means_no_scorecard_block() {
        let result = make_multi_function_result();
        let out = md(&make_view_default(&result));
        assert!(!out.contains("CRAP Scorecard"));
        assert!(!out.contains("Delta status"));
    }

    #[test]
    fn full_markdown_with_delta_snapshot() {
        let delta = make_sample_delta();
        let dview = make_delta_view_default(&delta);
        let out = format_markdown(
            &make_view_default(&delta.current),
            Some(&dview),
            8.0,
            false,
            false,
            false,
            10,
            &test_meta(),
            ComplexityMetric::Cognitive,
        );
        insta::assert_snapshot!(out);
    }
}