Skip to main content

fallow_api/
health_codeclimate.rs

1//! Shared health CodeClimate issue construction.
2
3use std::path::Path;
4
5use fallow_output::{
6    CodeClimateIssue, CodeClimateIssueInput, CodeClimateSeverity, ComplexityViolation,
7    CoverageIntelligenceFinding, CoverageIntelligenceRecommendation, CoverageIntelligenceVerdict,
8    ExceededThreshold, FindingSeverity, HealthReport, HealthSummary, RuntimeCoverageFinding,
9    RuntimeCoverageVerdict, StylingFinding, StylingFindingSeverity, UntestedExportFinding,
10    UntestedFileFinding, build_codeclimate_issue, codeclimate_fingerprint_hash, normalize_uri,
11};
12use fallow_types::output_dead_code::EffectiveSeverity;
13
14struct HealthCodeClimateContext<'a> {
15    root: &'a Path,
16    /// Held instead of the three run-global ceilings so every description
17    /// resolves per finding: an override-affected finding must never be
18    /// described against a ceiling it was not measured with (issue #2163).
19    summary: &'a HealthSummary,
20}
21
22impl HealthCodeClimateContext<'_> {
23    fn complexity_issue(&self, finding: &ComplexityViolation) -> CodeClimateIssue {
24        let path = codeclimate_path(&finding.path, self.root);
25        let check_name = complexity_check_name(finding);
26        let line_str = finding.line.to_string();
27        let fp = codeclimate_fingerprint_hash(&[check_name, &path, &line_str, &finding.name]);
28        build_codeclimate_issue(CodeClimateIssueInput {
29            check_name,
30            description: &self.complexity_description(finding),
31            severity: complexity_codeclimate_severity(finding),
32            category: "Complexity",
33            path: &path,
34            begin_line: Some(finding.line),
35            fingerprint: &fp,
36        })
37    }
38
39    fn styling_issue(&self, finding: &StylingFinding) -> CodeClimateIssue {
40        let path = codeclimate_path(Path::new(&finding.path), self.root);
41        let check_name = format!("fallow/{}", finding.code);
42        let description = format!("[{}] {}: {}", finding.code, finding.sub_kind, finding.value);
43        let line_str = finding.line.to_string();
44        let fp = codeclimate_fingerprint_hash(&[
45            &check_name,
46            &path,
47            &line_str,
48            &finding.sub_kind,
49            &finding.value,
50        ]);
51        build_codeclimate_issue(CodeClimateIssueInput {
52            check_name: &check_name,
53            description: &description,
54            severity: styling_finding_severity(finding.effective_severity),
55            category: "Style",
56            path: &path,
57            begin_line: Some(finding.line),
58            fingerprint: &fp,
59        })
60    }
61
62    fn complexity_description(&self, finding: &ComplexityViolation) -> String {
63        let thresholds = finding.resolved_thresholds(self.summary);
64        match finding.exceeded {
65            ExceededThreshold::Both => format!(
66                "'{}' has cyclomatic complexity {} (threshold: {}) and cognitive complexity {} (threshold: {})",
67                finding.name,
68                finding.cyclomatic,
69                thresholds.max_cyclomatic,
70                finding.cognitive,
71                thresholds.max_cognitive
72            ),
73            ExceededThreshold::Cyclomatic => format!(
74                "'{}' has cyclomatic complexity {} (threshold: {})",
75                finding.name, finding.cyclomatic, thresholds.max_cyclomatic
76            ),
77            ExceededThreshold::Cognitive => format!(
78                "'{}' has cognitive complexity {} (threshold: {})",
79                finding.name, finding.cognitive, thresholds.max_cognitive
80            ),
81            ExceededThreshold::Crap
82            | ExceededThreshold::CyclomaticCrap
83            | ExceededThreshold::CognitiveCrap
84            | ExceededThreshold::All => {
85                let crap = finding.crap.unwrap_or(0.0);
86                let coverage = finding
87                    .coverage_pct
88                    .map(|pct| format!(", coverage {pct:.0}%"))
89                    .unwrap_or_default();
90                format!(
91                    "'{}' has CRAP score {crap:.1} (threshold: {:.1}, cyclomatic {}{coverage})",
92                    finding.name, thresholds.max_crap, finding.cyclomatic,
93                )
94            }
95            ExceededThreshold::FileLines => format!(
96                "File has {} lines (threshold: {})",
97                finding.line_count,
98                finding.max_file_lines.unwrap_or_default()
99            ),
100        }
101    }
102
103    fn runtime_coverage_issue(&self, finding: &RuntimeCoverageFinding) -> CodeClimateIssue {
104        let path = codeclimate_path(&finding.path, self.root);
105        let check_name = runtime_coverage_check_name(finding.verdict);
106        let invocations_hint = finding.invocations.map_or_else(
107            || "untracked".to_owned(),
108            |hits| format!("{hits} invocations"),
109        );
110        let description = format!(
111            "'{}' runtime coverage verdict: {} ({})",
112            finding.function,
113            finding.verdict.human_label(),
114            invocations_hint,
115        );
116        let fp = codeclimate_fingerprint_hash(&[
117            check_name,
118            &path,
119            &finding.line.to_string(),
120            &finding.function,
121        ]);
122        build_codeclimate_issue(CodeClimateIssueInput {
123            check_name,
124            description: &description,
125            severity: runtime_coverage_severity(finding.verdict),
126            category: "Bug Risk",
127            path: &path,
128            begin_line: Some(finding.line),
129            fingerprint: &fp,
130        })
131    }
132
133    fn coverage_intelligence_issue(
134        &self,
135        finding: &CoverageIntelligenceFinding,
136    ) -> Option<CodeClimateIssue> {
137        let severity = coverage_intelligence_severity(finding.verdict)?;
138        let path = codeclimate_path(&finding.path, self.root);
139        let check_name = coverage_intelligence_check_name(finding.recommendation);
140        let identity = finding.identity.as_deref().unwrap_or("code");
141        let description = format!(
142            "'{}' coverage intelligence verdict: {} ({})",
143            identity, finding.verdict, finding.recommendation,
144        );
145        let fp = codeclimate_fingerprint_hash(&[
146            check_name,
147            &path,
148            &finding.line.to_string(),
149            identity,
150            &finding.id,
151        ]);
152        Some(build_codeclimate_issue(CodeClimateIssueInput {
153            check_name,
154            description: &description,
155            severity,
156            category: "Bug Risk",
157            path: &path,
158            begin_line: Some(finding.line),
159            fingerprint: &fp,
160        }))
161    }
162
163    fn untested_file_issue(&self, item: &UntestedFileFinding) -> CodeClimateIssue {
164        let path = codeclimate_path(&item.file.path, self.root);
165        let description = format!(
166            "File is runtime-reachable but has no test dependency path ({} value export{})",
167            item.file.value_export_count,
168            if item.file.value_export_count == 1 {
169                ""
170            } else {
171                "s"
172            },
173        );
174        let fp = codeclimate_fingerprint_hash(&["fallow/untested-file", &path]);
175        build_codeclimate_issue(CodeClimateIssueInput {
176            check_name: "fallow/untested-file",
177            description: &description,
178            severity: CodeClimateSeverity::Minor,
179            category: "Coverage",
180            path: &path,
181            begin_line: None,
182            fingerprint: &fp,
183        })
184    }
185
186    fn untested_export_issue(&self, item: &UntestedExportFinding) -> CodeClimateIssue {
187        let path = codeclimate_path(&item.export.path, self.root);
188        let description = format!(
189            "Export '{}' is runtime-reachable but never referenced by test-reachable modules",
190            item.export.export_name
191        );
192        let line_str = item.export.line.to_string();
193        let fp = codeclimate_fingerprint_hash(&[
194            "fallow/untested-export",
195            &path,
196            &line_str,
197            &item.export.export_name,
198        ]);
199        build_codeclimate_issue(CodeClimateIssueInput {
200            check_name: "fallow/untested-export",
201            description: &description,
202            severity: CodeClimateSeverity::Minor,
203            category: "Coverage",
204            path: &path,
205            begin_line: Some(item.export.line),
206            fingerprint: &fp,
207        })
208    }
209}
210
211/// Build CodeClimate issues from health / complexity analysis results.
212#[must_use]
213pub fn build_health_codeclimate(report: &HealthReport, root: &Path) -> Vec<CodeClimateIssue> {
214    let mut issues = Vec::new();
215    let ctx = HealthCodeClimateContext {
216        root,
217        summary: &report.summary,
218    };
219
220    for finding in &report.findings {
221        let mut issue = ctx.complexity_issue(finding);
222        // Audit only: name the measured values that grew against the base
223        // finding. The fingerprint does not read the description.
224        if !finding.worsened_metrics.is_empty() {
225            let class =
226                if finding.attribution == Some(fallow_output::AuditFindingAttribution::Worsened) {
227                    "worsened"
228                } else {
229                    "introduced"
230                };
231            issue.description = format!(
232                "{} ({class} against the base: {})",
233                issue.description,
234                fallow_output::describe_worsened_metrics(&finding.worsened_metrics)
235            );
236        }
237        if finding.gate_exemption == Some(fallow_output::AuditGateExemption::TestFile) {
238            issue.description =
239                format!("{} (test file: audit does not gate it)", issue.description);
240        }
241        issues.push(issue);
242    }
243    for finding in &report.styling_findings {
244        issues.push(ctx.styling_issue(finding));
245    }
246
247    if let Some(ref production) = report.runtime_coverage {
248        for finding in &production.findings {
249            issues.push(ctx.runtime_coverage_issue(finding));
250        }
251    }
252
253    if let Some(ref intelligence) = report.coverage_intelligence {
254        for finding in &intelligence.findings {
255            if let Some(issue) = ctx.coverage_intelligence_issue(finding) {
256                issues.push(issue);
257            }
258        }
259    }
260
261    if let Some(ref gaps) = report.coverage_gaps {
262        for item in &gaps.files {
263            issues.push(ctx.untested_file_issue(item));
264        }
265
266        for item in &gaps.exports {
267            issues.push(ctx.untested_export_issue(item));
268        }
269    }
270
271    issues
272}
273
274fn codeclimate_path(path: &Path, root: &Path) -> String {
275    normalize_uri(
276        &path
277            .strip_prefix(root)
278            .unwrap_or(path)
279            .display()
280            .to_string(),
281    )
282}
283
284const fn coverage_intelligence_check_name(
285    recommendation: CoverageIntelligenceRecommendation,
286) -> &'static str {
287    match recommendation {
288        CoverageIntelligenceRecommendation::AddTestOrSplitBeforeMerge => {
289            "fallow/coverage-intelligence-risky-change"
290        }
291        CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner => {
292            "fallow/coverage-intelligence-delete"
293        }
294        CoverageIntelligenceRecommendation::ReviewBeforeChanging => {
295            "fallow/coverage-intelligence-review"
296        }
297        CoverageIntelligenceRecommendation::RefactorCarefullyKeepBehavior => {
298            "fallow/coverage-intelligence-refactor"
299        }
300    }
301}
302
303const fn complexity_check_name(finding: &ComplexityViolation) -> &'static str {
304    match finding.exceeded {
305        ExceededThreshold::Both => "fallow/high-complexity",
306        ExceededThreshold::Cyclomatic => "fallow/high-cyclomatic-complexity",
307        ExceededThreshold::Cognitive => "fallow/high-cognitive-complexity",
308        ExceededThreshold::Crap
309        | ExceededThreshold::CyclomaticCrap
310        | ExceededThreshold::CognitiveCrap
311        | ExceededThreshold::All => "fallow/high-crap-score",
312        ExceededThreshold::FileLines => "fallow/long-file",
313    }
314}
315
316/// The CodeClimate severity of a complexity finding.
317///
318/// The gate severity from the `complexity-*` rules sets it: `error` gives
319/// `major` and `warn` gives `minor`, as for dead-code and styling findings.
320/// A finding without a gate severity (a saved report from an older version)
321/// keeps the band mapping.
322const fn complexity_codeclimate_severity(finding: &ComplexityViolation) -> CodeClimateSeverity {
323    match finding.effective_severity {
324        Some(EffectiveSeverity::Error) => CodeClimateSeverity::Major,
325        Some(EffectiveSeverity::Warn) => CodeClimateSeverity::Minor,
326        None => health_finding_severity(finding.severity),
327    }
328}
329
330const fn health_finding_severity(severity: FindingSeverity) -> CodeClimateSeverity {
331    match severity {
332        FindingSeverity::Critical => CodeClimateSeverity::Critical,
333        FindingSeverity::High => CodeClimateSeverity::Major,
334        FindingSeverity::Moderate => CodeClimateSeverity::Minor,
335    }
336}
337
338const fn styling_finding_severity(severity: StylingFindingSeverity) -> CodeClimateSeverity {
339    match severity {
340        StylingFindingSeverity::Error => CodeClimateSeverity::Major,
341        StylingFindingSeverity::Warn => CodeClimateSeverity::Minor,
342    }
343}
344
345const fn runtime_coverage_check_name(verdict: RuntimeCoverageVerdict) -> &'static str {
346    match verdict {
347        RuntimeCoverageVerdict::SafeToDelete => "fallow/runtime-safe-to-delete",
348        RuntimeCoverageVerdict::ReviewRequired => "fallow/runtime-review-required",
349        RuntimeCoverageVerdict::LowTraffic => "fallow/runtime-low-traffic",
350        RuntimeCoverageVerdict::CoverageUnavailable => "fallow/runtime-coverage-unavailable",
351        RuntimeCoverageVerdict::Active | RuntimeCoverageVerdict::Unknown => {
352            "fallow/runtime-coverage"
353        }
354    }
355}
356
357const fn runtime_coverage_severity(verdict: RuntimeCoverageVerdict) -> CodeClimateSeverity {
358    match verdict {
359        RuntimeCoverageVerdict::SafeToDelete => CodeClimateSeverity::Critical,
360        RuntimeCoverageVerdict::ReviewRequired => CodeClimateSeverity::Major,
361        _ => CodeClimateSeverity::Minor,
362    }
363}
364
365const fn coverage_intelligence_severity(
366    verdict: CoverageIntelligenceVerdict,
367) -> Option<CodeClimateSeverity> {
368    match verdict {
369        CoverageIntelligenceVerdict::RiskyChangeDetected
370        | CoverageIntelligenceVerdict::HighConfidenceDelete => Some(CodeClimateSeverity::Major),
371        CoverageIntelligenceVerdict::ReviewRequired
372        | CoverageIntelligenceVerdict::RefactorCarefully => Some(CodeClimateSeverity::Minor),
373        CoverageIntelligenceVerdict::Clean | CoverageIntelligenceVerdict::Unknown => None,
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use std::path::{Path, PathBuf};
380
381    use fallow_output::{
382        ComplexityViolation, ExceededThreshold, FindingSeverity, HealthReport, HealthSummary,
383        StylingFinding, StylingFindingSeverity,
384    };
385
386    use super::*;
387
388    #[test]
389    fn health_codeclimate_uses_relative_normalized_paths() {
390        let report = HealthReport {
391            summary: HealthSummary {
392                max_cyclomatic_threshold: 10,
393                max_cognitive_threshold: 8,
394                max_crap_threshold: 30.0,
395                ..HealthSummary::default()
396            },
397            findings: vec![
398                ComplexityViolation {
399                    path: PathBuf::from("/root/app/[id]/page.tsx"),
400                    name: "render".to_string(),
401                    line: 7,
402                    col: 0,
403                    cyclomatic: 12,
404                    standard_cyclomatic: None,
405                    cognitive: 9,
406                    line_count: 20,
407                    param_count: 1,
408                    react_hook_count: 0,
409                    react_jsx_max_depth: 0,
410                    react_prop_count: 0,
411                    react_hook_profile: None,
412                    exceeded: ExceededThreshold::Both,
413                    effective_severity: None,
414                    severity: FindingSeverity::High,
415                    mutation: None,
416                    coverage_pct: None,
417                    crap: None,
418                    coverage_tier: None,
419                    coverage_source: None,
420                    inherited_from: None,
421                    component_rollup: None,
422                    contributions: Vec::new(),
423                    effective_thresholds: None,
424                    threshold_source: None,
425                    max_file_lines: None,
426                }
427                .into(),
428            ],
429            ..HealthReport::default()
430        };
431
432        let issues = build_health_codeclimate(&report, Path::new("/root"));
433
434        assert_eq!(issues.len(), 1);
435        let issue = &issues[0];
436        assert_eq!(issue.check_name, "fallow/high-complexity");
437        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
438        assert_eq!(issue.location.lines.begin, 7);
439        assert_eq!(issue.severity, CodeClimateSeverity::Major);
440    }
441
442    #[test]
443    fn health_codeclimate_includes_styling_findings() {
444        let report = HealthReport {
445            styling_findings: vec![StylingFinding {
446                internal: fallow_output::StylingFindingInternal::default(),
447                code: "css-selector-complexity".to_string(),
448                sub_kind: "high-specificity".to_string(),
449                path: "src/styles.css".to_string(),
450                line: 4,
451                value: "#app .card .title".to_string(),
452                effective_severity: StylingFindingSeverity::Error,
453                blast_radius: None,
454                confidence: None,
455                agent_disposition: None,
456                nearest_token: None,
457                fix_hint: None,
458                actions: Vec::new(),
459            }],
460            ..HealthReport::default()
461        };
462
463        let issues = build_health_codeclimate(&report, Path::new("/root"));
464
465        assert_eq!(issues.len(), 1);
466        let issue = &issues[0];
467        assert_eq!(issue.check_name, "fallow/css-selector-complexity");
468        assert_eq!(issue.location.path, "src/styles.css");
469        assert_eq!(issue.location.lines.begin, 4);
470        assert_eq!(issue.severity, CodeClimateSeverity::Major);
471    }
472
473    fn crap_violation(
474        effective_thresholds: Option<fallow_output::HealthEffectiveThresholds>,
475    ) -> ComplexityViolation {
476        ComplexityViolation {
477            path: PathBuf::from("/root/src/Board.astro"),
478            name: "<template>".to_string(),
479            line: 6,
480            col: 3,
481            cyclomatic: 11,
482            standard_cyclomatic: None,
483            cognitive: 4,
484            line_count: 20,
485            param_count: 0,
486            react_hook_count: 0,
487            react_jsx_max_depth: 0,
488            react_prop_count: 0,
489            react_hook_profile: None,
490            exceeded: ExceededThreshold::Crap,
491            effective_severity: None,
492            severity: FindingSeverity::Critical,
493            mutation: None,
494            coverage_pct: None,
495            crap: Some(132.0),
496            coverage_tier: None,
497            coverage_source: None,
498            inherited_from: None,
499            component_rollup: None,
500            contributions: Vec::new(),
501            threshold_source: effective_thresholds
502                .map(|_| fallow_output::ThresholdSource::Override),
503            max_file_lines: None,
504            effective_thresholds,
505        }
506    }
507
508    fn crap_report(
509        effective_thresholds: Option<fallow_output::HealthEffectiveThresholds>,
510    ) -> HealthReport {
511        HealthReport {
512            summary: HealthSummary {
513                max_crap_threshold: 30.0,
514                ..HealthSummary::default()
515            },
516            findings: vec![crap_violation(effective_thresholds).into()],
517            ..HealthReport::default()
518        }
519    }
520
521    /// The CodeClimate description feeds `pr-comment-*` and `review-*` too, so
522    /// it must quote the ceiling the finding was measured with, matching SARIF
523    /// (issue #2163).
524    #[test]
525    fn codeclimate_description_uses_the_override_ceiling_not_the_global_one() {
526        let report = crap_report(Some(fallow_output::HealthEffectiveThresholds {
527            max_cyclomatic: 20,
528            max_cognitive: 15,
529            max_crap: 100.0,
530            max_unit_size: 60,
531        }));
532
533        let issues = build_health_codeclimate(&report, Path::new("/root"));
534
535        assert_eq!(issues.len(), 1);
536        assert!(
537            issues[0].description.contains("threshold: 100.0"),
538            "{}",
539            issues[0].description
540        );
541        assert!(
542            !issues[0].description.contains("threshold: 30.0"),
543            "{}",
544            issues[0].description
545        );
546    }
547
548    #[test]
549    fn codeclimate_description_falls_back_to_the_global_ceiling() {
550        let issues = build_health_codeclimate(&crap_report(None), Path::new("/root"));
551
552        assert_eq!(issues.len(), 1);
553        assert!(
554            issues[0].description.contains("threshold: 30.0"),
555            "{}",
556            issues[0].description
557        );
558    }
559
560    #[test]
561    fn health_severities_reach_serialized_codeclimate_issues() {
562        for (severity, expected) in [
563            (FindingSeverity::Critical, "critical"),
564            (FindingSeverity::High, "major"),
565            (FindingSeverity::Moderate, "minor"),
566        ] {
567            let mut violation = crap_violation(None);
568            violation.severity = severity;
569            let report = HealthReport {
570                findings: vec![violation.into()],
571                ..HealthReport::default()
572            };
573            let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
574                &report,
575                Path::new("/root"),
576            ));
577            let issues = issues
578                .as_array()
579                .expect("CodeClimate output must be an array");
580            assert_eq!(issues.len(), 1);
581            assert_eq!(issues[0]["severity"], expected);
582            assert_eq!(issues[0]["check_name"], "fallow/high-crap-score");
583        }
584    }
585
586    #[test]
587    fn runtime_verdicts_reach_serialized_codeclimate_issues() {
588        use fallow_output::{
589            RuntimeCoverageConfidence, RuntimeCoverageEvidence, RuntimeCoverageReport,
590        };
591
592        for (verdict, check_name, severity) in [
593            (
594                RuntimeCoverageVerdict::SafeToDelete,
595                "fallow/runtime-safe-to-delete",
596                "critical",
597            ),
598            (
599                RuntimeCoverageVerdict::ReviewRequired,
600                "fallow/runtime-review-required",
601                "major",
602            ),
603            (
604                RuntimeCoverageVerdict::LowTraffic,
605                "fallow/runtime-low-traffic",
606                "minor",
607            ),
608            (
609                RuntimeCoverageVerdict::CoverageUnavailable,
610                "fallow/runtime-coverage-unavailable",
611                "minor",
612            ),
613            (
614                RuntimeCoverageVerdict::Active,
615                "fallow/runtime-coverage",
616                "minor",
617            ),
618            (
619                RuntimeCoverageVerdict::Unknown,
620                "fallow/runtime-coverage",
621                "minor",
622            ),
623        ] {
624            let report = HealthReport {
625                runtime_coverage: Some(RuntimeCoverageReport {
626                    findings: vec![RuntimeCoverageFinding {
627                        id: "runtime-fixture".to_string(),
628                        stable_id: None,
629                        source_hash: None,
630                        path: PathBuf::from("/root/src/legacy.ts"),
631                        function: "legacyHelper".to_string(),
632                        line: 12,
633                        verdict,
634                        invocations: Some(0),
635                        confidence: RuntimeCoverageConfidence::High,
636                        evidence: RuntimeCoverageEvidence {
637                            static_status: "unused".to_string(),
638                            test_coverage: "not_covered".to_string(),
639                            test_only_reference: None,
640                            v8_tracking: "tracked".to_string(),
641                            untracked_reason: None,
642                            observation_days: 30,
643                            deployments_observed: 3,
644                        },
645                        actions: Vec::new(),
646                        discriminators: None,
647                    }],
648                    ..RuntimeCoverageReport::default()
649                }),
650                ..HealthReport::default()
651            };
652            let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
653                &report,
654                Path::new("/root"),
655            ));
656            let issues = issues
657                .as_array()
658                .expect("CodeClimate output must be an array");
659            assert_eq!(issues.len(), 1, "{verdict:?}");
660            assert_eq!(issues[0]["check_name"], check_name);
661            assert_eq!(issues[0]["severity"], severity);
662            assert_eq!(issues[0]["location"]["path"], "src/legacy.ts");
663            assert_eq!(issues[0]["location"]["lines"]["begin"], 12);
664        }
665    }
666
667    #[test]
668    fn coverage_intelligence_verdicts_and_recommendations_reach_serialized_issues() {
669        use fallow_output::{
670            CoverageIntelligenceConfidence, CoverageIntelligenceEvidence,
671            CoverageIntelligenceReport,
672        };
673
674        let recommendations = [
675            (
676                CoverageIntelligenceRecommendation::AddTestOrSplitBeforeMerge,
677                "fallow/coverage-intelligence-risky-change",
678            ),
679            (
680                CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner,
681                "fallow/coverage-intelligence-delete",
682            ),
683            (
684                CoverageIntelligenceRecommendation::ReviewBeforeChanging,
685                "fallow/coverage-intelligence-review",
686            ),
687            (
688                CoverageIntelligenceRecommendation::RefactorCarefullyKeepBehavior,
689                "fallow/coverage-intelligence-refactor",
690            ),
691        ];
692        for (verdict, severity) in [
693            (
694                CoverageIntelligenceVerdict::RiskyChangeDetected,
695                Some("major"),
696            ),
697            (
698                CoverageIntelligenceVerdict::HighConfidenceDelete,
699                Some("major"),
700            ),
701            (CoverageIntelligenceVerdict::ReviewRequired, Some("minor")),
702            (
703                CoverageIntelligenceVerdict::RefactorCarefully,
704                Some("minor"),
705            ),
706            (CoverageIntelligenceVerdict::Clean, None),
707            (CoverageIntelligenceVerdict::Unknown, None),
708        ] {
709            for (recommendation, check_name) in recommendations {
710                let report = HealthReport {
711                    coverage_intelligence: Some(CoverageIntelligenceReport {
712                        schema_version: fallow_output::CoverageIntelligenceSchemaVersion::default(),
713                        verdict,
714                        summary: fallow_output::CoverageIntelligenceSummary::default(),
715                        findings: vec![CoverageIntelligenceFinding {
716                            id: "coverage-fixture".to_string(),
717                            path: PathBuf::from("/root/src/legacy.ts"),
718                            identity: Some("legacyHelper".to_string()),
719                            line: 12,
720                            verdict,
721                            signals: Vec::new(),
722                            recommendation,
723                            confidence: CoverageIntelligenceConfidence::High,
724                            related_ids: Vec::new(),
725                            evidence: CoverageIntelligenceEvidence::default(),
726                            actions: Vec::new(),
727                        }],
728                    }),
729                    ..HealthReport::default()
730                };
731                let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
732                    &report,
733                    Path::new("/root"),
734                ));
735                let issues = issues
736                    .as_array()
737                    .expect("CodeClimate output must be an array");
738                if let Some(severity) = severity {
739                    assert_eq!(issues.len(), 1, "{verdict:?}");
740                    assert_eq!(issues[0]["check_name"], check_name);
741                    assert_eq!(issues[0]["severity"], severity);
742                    assert_eq!(issues[0]["location"]["path"], "src/legacy.ts");
743                } else {
744                    assert!(issues.is_empty(), "{verdict:?}");
745                }
746            }
747        }
748    }
749}