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