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. An inherited finding names the base and head values of its
224        // exceeded metrics. The fingerprint does not read the description.
225        if !finding.worsened_metrics.is_empty() {
226            let class =
227                if finding.attribution == Some(fallow_output::AuditFindingAttribution::Worsened) {
228                    "worsened"
229                } else {
230                    "introduced"
231                };
232            issue.description = format!(
233                "{} ({class} against the base: {})",
234                issue.description,
235                fallow_output::describe_worsened_metrics(&finding.worsened_metrics)
236            );
237        } else if let Some(metrics) = finding
238            .audit_base
239            .and_then(|base| base.describe_exceeded(&finding.violation))
240        {
241            issue.description =
242                format!("{} (inherited from the base: {metrics})", issue.description);
243        }
244        if finding.gate_exemption == Some(fallow_output::AuditGateExemption::TestFile) {
245            issue.description =
246                format!("{} (test file: audit does not gate it)", issue.description);
247        }
248        issue.audit = finding
249            .attribution
250            .map(|attribution| fallow_output::AuditReviewContext {
251                attribution,
252                gate_exemption: finding.gate_exemption,
253                gate: None,
254            });
255        issues.push(issue);
256    }
257    for finding in &report.styling_findings {
258        let mut issue = ctx.styling_issue(finding);
259        issue.audit = finding
260            .internal
261            .introduced
262            .map(crate::dead_code_codeclimate::audit_review_context);
263        issues.push(issue);
264    }
265
266    if let Some(ref production) = report.runtime_coverage {
267        for finding in &production.findings {
268            issues.push(ctx.runtime_coverage_issue(finding));
269        }
270    }
271
272    if let Some(ref intelligence) = report.coverage_intelligence {
273        for finding in &intelligence.findings {
274            if let Some(issue) = ctx.coverage_intelligence_issue(finding) {
275                issues.push(issue);
276            }
277        }
278    }
279
280    if let Some(ref gaps) = report.coverage_gaps {
281        for item in &gaps.files {
282            issues.push(ctx.untested_file_issue(item));
283        }
284
285        for item in &gaps.exports {
286            issues.push(ctx.untested_export_issue(item));
287        }
288    }
289
290    issues
291}
292
293fn codeclimate_path(path: &Path, root: &Path) -> String {
294    normalize_uri(
295        &path
296            .strip_prefix(root)
297            .unwrap_or(path)
298            .display()
299            .to_string(),
300    )
301}
302
303const fn coverage_intelligence_check_name(
304    recommendation: CoverageIntelligenceRecommendation,
305) -> &'static str {
306    match recommendation {
307        CoverageIntelligenceRecommendation::AddTestOrSplitBeforeMerge => {
308            "fallow/coverage-intelligence-risky-change"
309        }
310        CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner => {
311            "fallow/coverage-intelligence-delete"
312        }
313        CoverageIntelligenceRecommendation::ReviewBeforeChanging => {
314            "fallow/coverage-intelligence-review"
315        }
316        CoverageIntelligenceRecommendation::RefactorCarefullyKeepBehavior => {
317            "fallow/coverage-intelligence-refactor"
318        }
319    }
320}
321
322const fn complexity_check_name(finding: &ComplexityViolation) -> &'static str {
323    match finding.exceeded {
324        ExceededThreshold::Both => "fallow/high-complexity",
325        ExceededThreshold::Cyclomatic => "fallow/high-cyclomatic-complexity",
326        ExceededThreshold::Cognitive => "fallow/high-cognitive-complexity",
327        ExceededThreshold::Crap
328        | ExceededThreshold::CyclomaticCrap
329        | ExceededThreshold::CognitiveCrap
330        | ExceededThreshold::All => "fallow/high-crap-score",
331        ExceededThreshold::FileLines => "fallow/long-file",
332    }
333}
334
335/// The CodeClimate severity of a complexity finding.
336///
337/// The gate severity from the `complexity-*` rules sets it: `error` gives
338/// `major` and `warn` gives `minor`, as for dead-code and styling findings.
339/// A finding without a gate severity (a saved report from an older version)
340/// keeps the band mapping.
341const fn complexity_codeclimate_severity(finding: &ComplexityViolation) -> CodeClimateSeverity {
342    match finding.effective_severity {
343        Some(EffectiveSeverity::Error) => CodeClimateSeverity::Major,
344        Some(EffectiveSeverity::Warn) => CodeClimateSeverity::Minor,
345        None => health_finding_severity(finding.severity),
346    }
347}
348
349const fn health_finding_severity(severity: FindingSeverity) -> CodeClimateSeverity {
350    match severity {
351        FindingSeverity::Critical => CodeClimateSeverity::Critical,
352        FindingSeverity::High => CodeClimateSeverity::Major,
353        FindingSeverity::Moderate => CodeClimateSeverity::Minor,
354    }
355}
356
357const fn styling_finding_severity(severity: StylingFindingSeverity) -> CodeClimateSeverity {
358    match severity {
359        StylingFindingSeverity::Error => CodeClimateSeverity::Major,
360        StylingFindingSeverity::Warn => CodeClimateSeverity::Minor,
361    }
362}
363
364const fn runtime_coverage_check_name(verdict: RuntimeCoverageVerdict) -> &'static str {
365    match verdict {
366        RuntimeCoverageVerdict::SafeToDelete => "fallow/runtime-safe-to-delete",
367        RuntimeCoverageVerdict::ReviewRequired => "fallow/runtime-review-required",
368        RuntimeCoverageVerdict::LowTraffic => "fallow/runtime-low-traffic",
369        RuntimeCoverageVerdict::CoverageUnavailable => "fallow/runtime-coverage-unavailable",
370        RuntimeCoverageVerdict::Active | RuntimeCoverageVerdict::Unknown => {
371            "fallow/runtime-coverage"
372        }
373    }
374}
375
376const fn runtime_coverage_severity(verdict: RuntimeCoverageVerdict) -> CodeClimateSeverity {
377    match verdict {
378        RuntimeCoverageVerdict::SafeToDelete => CodeClimateSeverity::Critical,
379        RuntimeCoverageVerdict::ReviewRequired => CodeClimateSeverity::Major,
380        _ => CodeClimateSeverity::Minor,
381    }
382}
383
384const fn coverage_intelligence_severity(
385    verdict: CoverageIntelligenceVerdict,
386) -> Option<CodeClimateSeverity> {
387    match verdict {
388        CoverageIntelligenceVerdict::RiskyChangeDetected
389        | CoverageIntelligenceVerdict::HighConfidenceDelete => Some(CodeClimateSeverity::Major),
390        CoverageIntelligenceVerdict::ReviewRequired
391        | CoverageIntelligenceVerdict::RefactorCarefully => Some(CodeClimateSeverity::Minor),
392        CoverageIntelligenceVerdict::Clean | CoverageIntelligenceVerdict::Unknown => None,
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use std::path::{Path, PathBuf};
399
400    use fallow_output::{
401        ComplexityViolation, ExceededThreshold, FindingSeverity, HealthReport, HealthSummary,
402        StylingFinding, StylingFindingSeverity,
403    };
404
405    use super::*;
406
407    #[test]
408    fn health_codeclimate_uses_relative_normalized_paths() {
409        let report = HealthReport {
410            summary: HealthSummary {
411                max_cyclomatic_threshold: 10,
412                max_cognitive_threshold: 8,
413                max_crap_threshold: 30.0,
414                ..HealthSummary::default()
415            },
416            findings: vec![
417                ComplexityViolation {
418                    path: PathBuf::from("/root/app/[id]/page.tsx"),
419                    name: "render".to_string(),
420                    line: 7,
421                    col: 0,
422                    cyclomatic: 12,
423                    standard_cyclomatic: None,
424                    cognitive: 9,
425                    line_count: 20,
426                    param_count: 1,
427                    react_hook_count: 0,
428                    react_jsx_max_depth: 0,
429                    react_prop_count: 0,
430                    react_hook_profile: None,
431                    exceeded: ExceededThreshold::Both,
432                    effective_severity: None,
433                    severity: FindingSeverity::High,
434                    mutation: None,
435                    coverage_pct: None,
436                    crap: None,
437                    coverage_tier: None,
438                    coverage_source: None,
439                    inherited_from: None,
440                    component_rollup: None,
441                    contributions: Vec::new(),
442                    effective_thresholds: None,
443                    threshold_source: None,
444                    max_file_lines: None,
445                }
446                .into(),
447            ],
448            ..HealthReport::default()
449        };
450
451        let issues = build_health_codeclimate(&report, Path::new("/root"));
452
453        assert_eq!(issues.len(), 1);
454        let issue = &issues[0];
455        assert_eq!(issue.check_name, "fallow/high-complexity");
456        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
457        assert_eq!(issue.location.lines.begin, 7);
458        assert_eq!(issue.severity, CodeClimateSeverity::Major);
459    }
460
461    #[test]
462    fn health_codeclimate_includes_styling_findings() {
463        let report = HealthReport {
464            styling_findings: vec![StylingFinding {
465                internal: fallow_output::StylingFindingInternal::default(),
466                code: "css-selector-complexity".to_string(),
467                sub_kind: "high-specificity".to_string(),
468                path: "src/styles.css".to_string(),
469                line: 4,
470                value: "#app .card .title".to_string(),
471                effective_severity: StylingFindingSeverity::Error,
472                blast_radius: None,
473                confidence: None,
474                agent_disposition: None,
475                nearest_token: None,
476                fix_hint: None,
477                actions: Vec::new(),
478            }],
479            ..HealthReport::default()
480        };
481
482        let issues = build_health_codeclimate(&report, Path::new("/root"));
483
484        assert_eq!(issues.len(), 1);
485        let issue = &issues[0];
486        assert_eq!(issue.check_name, "fallow/css-selector-complexity");
487        assert_eq!(issue.location.path, "src/styles.css");
488        assert_eq!(issue.location.lines.begin, 4);
489        assert_eq!(issue.severity, CodeClimateSeverity::Major);
490        assert_eq!(
491            issue.audit, None,
492            "outside an audit there is no attribution"
493        );
494
495        let mut inherited = report;
496        inherited.styling_findings[0].internal.introduced = Some(false);
497        let issues = build_health_codeclimate(&inherited, Path::new("/root"));
498        assert_eq!(
499            issues[0].audit.map(|context| context.attribution),
500            Some(fallow_output::AuditFindingAttribution::Inherited)
501        );
502        assert_eq!(issues[0].fingerprint, issue.fingerprint);
503    }
504
505    fn crap_violation(
506        effective_thresholds: Option<fallow_output::HealthEffectiveThresholds>,
507    ) -> ComplexityViolation {
508        ComplexityViolation {
509            path: PathBuf::from("/root/src/Board.astro"),
510            name: "<template>".to_string(),
511            line: 6,
512            col: 3,
513            cyclomatic: 11,
514            standard_cyclomatic: None,
515            cognitive: 4,
516            line_count: 20,
517            param_count: 0,
518            react_hook_count: 0,
519            react_jsx_max_depth: 0,
520            react_prop_count: 0,
521            react_hook_profile: None,
522            exceeded: ExceededThreshold::Crap,
523            effective_severity: None,
524            severity: FindingSeverity::Critical,
525            mutation: None,
526            coverage_pct: None,
527            crap: Some(132.0),
528            coverage_tier: None,
529            coverage_source: None,
530            inherited_from: None,
531            component_rollup: None,
532            contributions: Vec::new(),
533            threshold_source: effective_thresholds
534                .map(|_| fallow_output::ThresholdSource::Override),
535            max_file_lines: None,
536            effective_thresholds,
537        }
538    }
539
540    fn crap_report(
541        effective_thresholds: Option<fallow_output::HealthEffectiveThresholds>,
542    ) -> HealthReport {
543        HealthReport {
544            summary: HealthSummary {
545                max_crap_threshold: 30.0,
546                ..HealthSummary::default()
547            },
548            findings: vec![crap_violation(effective_thresholds).into()],
549            ..HealthReport::default()
550        }
551    }
552
553    /// The CodeClimate description feeds `pr-comment-*` and `review-*` too, so
554    /// it must quote the ceiling the finding was measured with, matching SARIF
555    /// (issue #2163).
556    #[test]
557    fn codeclimate_description_uses_the_override_ceiling_not_the_global_one() {
558        let report = crap_report(Some(fallow_output::HealthEffectiveThresholds {
559            max_cyclomatic: 20,
560            max_cognitive: 15,
561            max_crap: 100.0,
562            max_unit_size: 60,
563        }));
564
565        let issues = build_health_codeclimate(&report, Path::new("/root"));
566
567        assert_eq!(issues.len(), 1);
568        assert!(
569            issues[0].description.contains("threshold: 100.0"),
570            "{}",
571            issues[0].description
572        );
573        assert!(
574            !issues[0].description.contains("threshold: 30.0"),
575            "{}",
576            issues[0].description
577        );
578    }
579
580    #[test]
581    fn codeclimate_description_falls_back_to_the_global_ceiling() {
582        let issues = build_health_codeclimate(&crap_report(None), Path::new("/root"));
583
584        assert_eq!(issues.len(), 1);
585        assert!(
586            issues[0].description.contains("threshold: 30.0"),
587            "{}",
588            issues[0].description
589        );
590    }
591
592    #[test]
593    fn health_severities_reach_serialized_codeclimate_issues() {
594        for (severity, expected) in [
595            (FindingSeverity::Critical, "critical"),
596            (FindingSeverity::High, "major"),
597            (FindingSeverity::Moderate, "minor"),
598        ] {
599            let mut violation = crap_violation(None);
600            violation.severity = severity;
601            let report = HealthReport {
602                findings: vec![violation.into()],
603                ..HealthReport::default()
604            };
605            let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
606                &report,
607                Path::new("/root"),
608            ));
609            let issues = issues
610                .as_array()
611                .expect("CodeClimate output must be an array");
612            assert_eq!(issues.len(), 1);
613            assert_eq!(issues[0]["severity"], expected);
614            assert_eq!(issues[0]["check_name"], "fallow/high-crap-score");
615        }
616    }
617
618    #[test]
619    fn runtime_verdicts_reach_serialized_codeclimate_issues() {
620        use fallow_output::{
621            RuntimeCoverageConfidence, RuntimeCoverageEvidence, RuntimeCoverageReport,
622        };
623
624        for (verdict, check_name, severity) in [
625            (
626                RuntimeCoverageVerdict::SafeToDelete,
627                "fallow/runtime-safe-to-delete",
628                "critical",
629            ),
630            (
631                RuntimeCoverageVerdict::ReviewRequired,
632                "fallow/runtime-review-required",
633                "major",
634            ),
635            (
636                RuntimeCoverageVerdict::LowTraffic,
637                "fallow/runtime-low-traffic",
638                "minor",
639            ),
640            (
641                RuntimeCoverageVerdict::CoverageUnavailable,
642                "fallow/runtime-coverage-unavailable",
643                "minor",
644            ),
645            (
646                RuntimeCoverageVerdict::Active,
647                "fallow/runtime-coverage",
648                "minor",
649            ),
650            (
651                RuntimeCoverageVerdict::Unknown,
652                "fallow/runtime-coverage",
653                "minor",
654            ),
655        ] {
656            let report = HealthReport {
657                runtime_coverage: Some(RuntimeCoverageReport {
658                    findings: vec![RuntimeCoverageFinding {
659                        cloud_context: None,
660                        id: "runtime-fixture".to_string(),
661                        stable_id: None,
662                        source_hash: None,
663                        path: PathBuf::from("/root/src/legacy.ts"),
664                        function: "legacyHelper".to_string(),
665                        line: 12,
666                        verdict,
667                        invocations: Some(0),
668                        confidence: RuntimeCoverageConfidence::High,
669                        evidence: RuntimeCoverageEvidence {
670                            static_status: "unused".to_string(),
671                            test_coverage: "not_covered".to_string(),
672                            test_only_reference: None,
673                            v8_tracking: "tracked".to_string(),
674                            untracked_reason: None,
675                            observation_days: 30,
676                            deployments_observed: 3,
677                        },
678                        actions: Vec::new(),
679                        discriminators: None,
680                    }],
681                    ..RuntimeCoverageReport::default()
682                }),
683                ..HealthReport::default()
684            };
685            let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
686                &report,
687                Path::new("/root"),
688            ));
689            let issues = issues
690                .as_array()
691                .expect("CodeClimate output must be an array");
692            assert_eq!(issues.len(), 1, "{verdict:?}");
693            assert_eq!(issues[0]["check_name"], check_name);
694            assert_eq!(issues[0]["severity"], severity);
695            assert_eq!(issues[0]["location"]["path"], "src/legacy.ts");
696            assert_eq!(issues[0]["location"]["lines"]["begin"], 12);
697        }
698    }
699
700    #[test]
701    fn coverage_intelligence_verdicts_and_recommendations_reach_serialized_issues() {
702        use fallow_output::{
703            CoverageIntelligenceConfidence, CoverageIntelligenceEvidence,
704            CoverageIntelligenceReport,
705        };
706
707        let recommendations = [
708            (
709                CoverageIntelligenceRecommendation::AddTestOrSplitBeforeMerge,
710                "fallow/coverage-intelligence-risky-change",
711            ),
712            (
713                CoverageIntelligenceRecommendation::DeleteAfterConfirmingOwner,
714                "fallow/coverage-intelligence-delete",
715            ),
716            (
717                CoverageIntelligenceRecommendation::ReviewBeforeChanging,
718                "fallow/coverage-intelligence-review",
719            ),
720            (
721                CoverageIntelligenceRecommendation::RefactorCarefullyKeepBehavior,
722                "fallow/coverage-intelligence-refactor",
723            ),
724        ];
725        for (verdict, severity) in [
726            (
727                CoverageIntelligenceVerdict::RiskyChangeDetected,
728                Some("major"),
729            ),
730            (
731                CoverageIntelligenceVerdict::HighConfidenceDelete,
732                Some("major"),
733            ),
734            (CoverageIntelligenceVerdict::ReviewRequired, Some("minor")),
735            (
736                CoverageIntelligenceVerdict::RefactorCarefully,
737                Some("minor"),
738            ),
739            (CoverageIntelligenceVerdict::Clean, None),
740            (CoverageIntelligenceVerdict::Unknown, None),
741        ] {
742            for (recommendation, check_name) in recommendations {
743                let report = HealthReport {
744                    coverage_intelligence: Some(CoverageIntelligenceReport {
745                        schema_version: fallow_output::CoverageIntelligenceSchemaVersion::default(),
746                        verdict,
747                        summary: fallow_output::CoverageIntelligenceSummary::default(),
748                        findings: vec![CoverageIntelligenceFinding {
749                            id: "coverage-fixture".to_string(),
750                            path: PathBuf::from("/root/src/legacy.ts"),
751                            identity: Some("legacyHelper".to_string()),
752                            line: 12,
753                            verdict,
754                            signals: Vec::new(),
755                            recommendation,
756                            confidence: CoverageIntelligenceConfidence::High,
757                            related_ids: Vec::new(),
758                            evidence: CoverageIntelligenceEvidence::default(),
759                            actions: Vec::new(),
760                        }],
761                    }),
762                    ..HealthReport::default()
763                };
764                let issues = fallow_output::codeclimate_issues_to_value(&build_health_codeclimate(
765                    &report,
766                    Path::new("/root"),
767                ));
768                let issues = issues
769                    .as_array()
770                    .expect("CodeClimate output must be an array");
771                if let Some(severity) = severity {
772                    assert_eq!(issues.len(), 1, "{verdict:?}");
773                    assert_eq!(issues[0]["check_name"], check_name);
774                    assert_eq!(issues[0]["severity"], severity);
775                    assert_eq!(issues[0]["location"]["path"], "src/legacy.ts");
776                } else {
777                    assert!(issues.is_empty(), "{verdict:?}");
778                }
779            }
780        }
781    }
782}