Skip to main content

fallow_api/
dead_code_codeclimate.rs

1//! Shared dead-code CodeClimate issue construction.
2
3#[path = "dead_code_codeclimate_component_health.rs"]
4mod component_health;
5
6use std::path::Path;
7
8use fallow_config::{RulesConfig, Severity};
9use fallow_output::{
10    CodeClimateIssue, CodeClimateIssueInput, CodeClimateSeverity, build_codeclimate_issue,
11    codeclimate_fingerprint_hash, normalize_uri,
12};
13use fallow_types::envelope::AuditIntroduced;
14use fallow_types::identity::dead_code_finding_id;
15use fallow_types::output_dead_code::{
16    EffectiveSeverity, GatedFinding, ReachabilityCaveat, caveat_suffix,
17};
18use fallow_types::results::AnalysisResults;
19
20#[path = "dead_code_codeclimate_catalog.rs"]
21mod catalog_issues;
22#[path = "dead_code_codeclimate_component_io.rs"]
23mod component_io;
24use catalog_issues::{
25    push_empty_catalog_group_issues, push_misconfigured_dependency_override_issues,
26    push_unresolved_catalog_reference_issues, push_unused_catalog_entry_issues,
27    push_unused_dependency_override_issues,
28};
29use component_io::{
30    push_unused_component_input_issues, push_unused_component_output_issues,
31    push_unused_svelte_event_issues,
32};
33
34fn severity_to_codeclimate(s: Severity) -> CodeClimateSeverity {
35    match s {
36        Severity::Error => CodeClimateSeverity::Major,
37        Severity::Warn => CodeClimateSeverity::Minor,
38        Severity::Off => unreachable!(),
39    }
40}
41
42/// The CodeClimate severity for one finding: its gate severity when the
43/// finding carries one, otherwise the configured rule severity (a saved report
44/// from an older version has no gate severity).
45///
46/// A saved finding exists, so its rule was on when it was reported. When the
47/// config at render time sets the rule `off`, the severity is `minor`.
48fn gate_codeclimate(effective: Option<EffectiveSeverity>, rule: Severity) -> CodeClimateSeverity {
49    match effective {
50        Some(EffectiveSeverity::Error) => CodeClimateSeverity::Major,
51        Some(EffectiveSeverity::Warn) => CodeClimateSeverity::Minor,
52        None => match rule {
53            Severity::Off => CodeClimateSeverity::Minor,
54            Severity::Error | Severity::Warn => severity_to_codeclimate(rule),
55        },
56    }
57}
58
59fn finding_codeclimate(finding: &impl GatedFinding, rule: Severity) -> CodeClimateSeverity {
60    gate_codeclimate(finding.effective_severity(), rule)
61}
62
63fn cc_path(path: &Path, root: &Path) -> String {
64    normalize_uri(
65        &path
66            .strip_prefix(root)
67            .unwrap_or(path)
68            .display()
69            .to_string(),
70    )
71}
72
73/// The caveat parenthetical a CodeClimate `description` ends with, or an empty
74/// string when the verdict rests on a fully analyzed run.
75///
76/// `description` is the one field GitLab renders inline on the MR diff, and it
77/// is also what `CiIssue` carries into the PR-comment and review-comment
78/// bodies. Those bodies offer a mutation, so the sentence that offers it has to
79/// say when the evidence behind it is incomplete. The suffix is the same
80/// parenthetical the human report and the SARIF message already use, so one
81/// finding reads identically across every surface.
82///
83/// Deliberately NOT part of the fingerprint: `codeclimate_fingerprint_hash` is
84/// fed rule id plus location by every call site in this file, never the
85/// description, so a finding that gains or loses a caveat keeps its identity
86/// and no previously resolved review thread reopens.
87fn cc_caveat_suffix(caveats: &[ReachabilityCaveat]) -> String {
88    caveat_suffix(caveats).unwrap_or_default()
89}
90
91/// Build one dead-code issue with its stable fingerprint.
92///
93/// `input.fingerprint` is the legacy fingerprint: the value that Fallow gave
94/// this issue before findings had a `finding_id`. For most kinds it holds the
95/// line, so a line shift above the finding changed it.
96///
97/// When the finding has a `finding_id`, the fingerprint is the FNV-1a 64 hash
98/// of that id plus `discriminator`, as 16 lowercase hex digits. The id holds
99/// no line and no column, so a line shift keeps the fingerprint. The hash
100/// covers the full id, not only the hex part of the id, so the `~k` tiebreak
101/// suffix keeps two findings with the same base id apart. The 16-hex form is
102/// the form that GitLab Code Quality and the review marker regex accept.
103/// `discriminator` separates the issues of one finding that emits one issue
104/// per location (duplicate exports, unlisted-dependency import sites). See
105/// [`location_discriminators`].
106///
107/// A finding without an id (a saved report from an older version) keeps the
108/// legacy fingerprint, so its review threads stay matched.
109///
110/// `introduced` is the audit flag of the finding. An audit sets it when it
111/// compares the run with a base snapshot. The issue then carries the
112/// attribution for the inline review comment.
113fn dead_code_issue(
114    finding_id: Option<&str>,
115    introduced: Option<AuditIntroduced>,
116    discriminator: &[&str],
117    input: CodeClimateIssueInput<'_>,
118) -> CodeClimateIssue {
119    let mut issue = build_codeclimate_issue(input);
120    issue.audit = introduced.map(|AuditIntroduced(introduced)| audit_review_context(introduced));
121    if let Some(id) = finding_id {
122        let mut parts = Vec::with_capacity(discriminator.len() + 1);
123        parts.push(id);
124        parts.extend_from_slice(discriminator);
125        let stable = codeclimate_fingerprint_hash(&parts);
126        if stable != issue.fingerprint {
127            issue.legacy_fingerprint = Some(std::mem::replace(&mut issue.fingerprint, stable));
128        }
129    }
130    issue
131}
132
133/// The audit facts of an inline review comment for a finding that an audit
134/// compared with the base snapshot. `introduced` is the audit flag.
135pub(crate) const fn audit_review_context(introduced: bool) -> fallow_output::AuditReviewContext {
136    fallow_output::AuditReviewContext {
137        attribution: if introduced {
138            fallow_output::AuditFindingAttribution::Introduced
139        } else {
140            fallow_output::AuditFindingAttribution::Inherited
141        },
142        gate_exemption: None,
143        gate: None,
144    }
145}
146
147/// The discriminator of each location of one finding, in input order.
148///
149/// A location is named by what it is, not by where it is. The only content a
150/// location carries next to the finding id is its path: the engine reports
151/// one unlisted-dependency import site per file, and every location of a
152/// duplicate export has the same export name, which the id already holds. So
153/// the discriminator is the path. Only locations with the same path (the same
154/// content) also get a position: the first by line keeps the bare path, the
155/// next one gets `~1`, and so on. A location added to or removed from another
156/// file, or after this one in the same file, never changes it.
157fn location_discriminators(locations: &[(String, u32, u32)]) -> Vec<Vec<String>> {
158    locations
159        .iter()
160        .enumerate()
161        .map(|(index, (path, line, col))| {
162            let earlier = locations
163                .iter()
164                .enumerate()
165                .filter(|(other, (other_path, other_line, other_col))| {
166                    other_path == path && (other_line, other_col, *other) < (line, col, index)
167                })
168                .count();
169            if earlier == 0 {
170                vec![path.clone()]
171            } else {
172                vec![path.clone(), format!("~{earlier}")]
173            }
174        })
175        .collect()
176}
177
178/// Push CodeClimate issues for unused dependencies with a shared structure.
179fn push_dep_cc_issues<'a, I>(
180    issues: &mut Vec<CodeClimateIssue>,
181    deps: I,
182    root: &Path,
183    rule_id: &str,
184    location_label: &str,
185    severity: Severity,
186) where
187    I: IntoIterator<
188        Item = (
189            &'a fallow_types::results::UnusedDependency,
190            &'a [ReachabilityCaveat],
191            Option<EffectiveSeverity>,
192            Option<&'a str>,
193            Option<AuditIntroduced>,
194        ),
195    >,
196{
197    for (dep, caveats, effective, finding_id, introduced) in deps {
198        let level = gate_codeclimate(effective, severity);
199        let path = cc_path(&dep.path, root);
200        let line = if dep.line > 0 { Some(dep.line) } else { None };
201        let fp = codeclimate_fingerprint_hash(&[rule_id, &dep.package_name]);
202        let workspace_context = if dep.used_in_workspaces.is_empty() {
203            String::new()
204        } else {
205            let workspaces = dep
206                .used_in_workspaces
207                .iter()
208                .map(|path| cc_path(path, root))
209                .collect::<Vec<_>>()
210                .join(", ");
211            format!("; imported in other workspaces: {workspaces}")
212        };
213        issues.push(dead_code_issue(
214            finding_id,
215            introduced,
216            &[],
217            CodeClimateIssueInput {
218                check_name: rule_id,
219                description: &format!(
220                    "Package '{}' is in {location_label} but never imported{workspace_context}{}",
221                    dep.package_name,
222                    cc_caveat_suffix(caveats)
223                ),
224                severity: level,
225                category: "Bug Risk",
226                path: &path,
227                begin_line: line,
228                fingerprint: &fp,
229            },
230        ));
231    }
232}
233
234fn push_unused_file_issues(
235    issues: &mut Vec<CodeClimateIssue>,
236    files: &[fallow_types::output_dead_code::UnusedFileFinding],
237    root: &Path,
238    severity: Severity,
239) {
240    if files.is_empty() {
241        return;
242    }
243    for entry in files {
244        let level = finding_codeclimate(entry, severity);
245        let path = cc_path(&entry.file.path, root);
246        let fp = codeclimate_fingerprint_hash(&["fallow/unused-file", &path]);
247        issues.push(dead_code_issue(
248            entry.finding_id.as_deref(),
249            entry.introduced,
250            &[],
251            CodeClimateIssueInput {
252                check_name: "fallow/unused-file",
253                description: &format!(
254                    "File is not reachable from any entry point{}",
255                    cc_caveat_suffix(&entry.reachability_caveats)
256                ),
257                severity: level,
258                category: "Bug Risk",
259                path: &path,
260                begin_line: None,
261                fingerprint: &fp,
262            },
263        ));
264    }
265}
266
267/// Push CodeClimate issues for unused exports or unused types.
268///
269/// `direct_label` / `re_export_label` let the same helper produce the right
270/// prose for both `unused-export` (Export / Re-export) and `unused-type`
271/// (Type export / Type re-export) rule ids.
272struct UnusedExportIssuesInput<'a, I> {
273    issues: &'a mut Vec<CodeClimateIssue>,
274    exports: I,
275    root: &'a Path,
276    rule_id: &'a str,
277    direct_label: &'a str,
278    re_export_label: &'a str,
279    severity: Severity,
280}
281
282fn push_unused_export_issues<'a, I>(input: UnusedExportIssuesInput<'a, I>)
283where
284    I: IntoIterator<
285        Item = (
286            &'a fallow_types::results::UnusedExport,
287            &'a [ReachabilityCaveat],
288            Option<EffectiveSeverity>,
289            Option<&'a str>,
290            Option<AuditIntroduced>,
291        ),
292    >,
293{
294    for (export, caveats, effective, finding_id, introduced) in input.exports {
295        let level = gate_codeclimate(effective, input.severity);
296        let path = cc_path(&export.path, input.root);
297        let kind = if export.is_re_export {
298            input.re_export_label
299        } else {
300            input.direct_label
301        };
302        let line_str = export.line.to_string();
303        let fp =
304            codeclimate_fingerprint_hash(&[input.rule_id, &path, &line_str, &export.export_name]);
305        input.issues.push(dead_code_issue(
306            finding_id,
307            introduced,
308            &[],
309            CodeClimateIssueInput {
310                check_name: input.rule_id,
311                description: &format!(
312                    "{kind} '{}' is never imported by other modules{}",
313                    export.export_name,
314                    cc_caveat_suffix(caveats)
315                ),
316                severity: level,
317                category: "Bug Risk",
318                path: &path,
319                begin_line: Some(export.line),
320                fingerprint: &fp,
321            },
322        ));
323    }
324}
325
326fn push_private_type_leak_issues(
327    issues: &mut Vec<CodeClimateIssue>,
328    leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
329    root: &Path,
330    severity: Severity,
331) {
332    if leaks.is_empty() {
333        return;
334    }
335    for entry in leaks {
336        let level = finding_codeclimate(entry, severity);
337        let leak = &entry.leak;
338        let path = cc_path(&leak.path, root);
339        let line_str = leak.line.to_string();
340        let fp = codeclimate_fingerprint_hash(&[
341            "fallow/private-type-leak",
342            &path,
343            &line_str,
344            &leak.export_name,
345            &leak.type_name,
346        ]);
347        issues.push(dead_code_issue(
348            entry.finding_id.as_deref(),
349            entry.introduced,
350            &[],
351            CodeClimateIssueInput {
352                check_name: "fallow/private-type-leak",
353                description: &format!(
354                    "Export '{}' references private type '{}'",
355                    leak.export_name, leak.type_name
356                ),
357                severity: level,
358                category: "Bug Risk",
359                path: &path,
360                begin_line: Some(leak.line),
361                fingerprint: &fp,
362            },
363        ));
364    }
365}
366
367fn push_deprecated_export_issues(
368    issues: &mut Vec<CodeClimateIssue>,
369    findings: &[fallow_types::output_dead_code::DeprecatedExportInUseFinding],
370    root: &Path,
371    severity: Severity,
372) {
373    for entry in findings {
374        let level = finding_codeclimate(entry, severity);
375        let export = &entry.export;
376        let path = cc_path(&export.path, root);
377        let line_str = export.line.to_string();
378        let fp = codeclimate_fingerprint_hash(&[
379            "fallow/deprecated-export-in-use",
380            &path,
381            &line_str,
382            &export.export_name,
383        ]);
384        issues.push(dead_code_issue(
385            entry.finding_id.as_deref(),
386            entry.introduced,
387            &[],
388            CodeClimateIssueInput {
389                check_name: "fallow/deprecated-export-in-use",
390                description: &export.description(),
391                severity: level,
392                category: "Compatibility",
393                path: &path,
394                begin_line: Some(export.line),
395                fingerprint: &fp,
396            },
397        ));
398    }
399}
400
401fn push_type_only_dep_issues(
402    issues: &mut Vec<CodeClimateIssue>,
403    deps: &[fallow_types::output_dead_code::TypeOnlyDependencyFinding],
404    root: &Path,
405    severity: Severity,
406) {
407    if deps.is_empty() {
408        return;
409    }
410    for entry in deps {
411        let level = finding_codeclimate(entry, severity);
412        let dep = &entry.dep;
413        let path = cc_path(&dep.path, root);
414        let line = if dep.line > 0 { Some(dep.line) } else { None };
415        let fp = codeclimate_fingerprint_hash(&["fallow/type-only-dependency", &dep.package_name]);
416        issues.push(dead_code_issue(
417            entry.finding_id.as_deref(),
418            entry.introduced,
419            &[],
420            CodeClimateIssueInput {
421                check_name: "fallow/type-only-dependency",
422                description: &format!(
423                    "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
424                    dep.package_name
425                ),
426                severity: level,
427                category: "Bug Risk",
428                path: &path,
429                begin_line: line,
430                fingerprint: &fp,
431            },
432        ));
433    }
434}
435
436fn push_test_only_dep_issues(
437    issues: &mut Vec<CodeClimateIssue>,
438    deps: &[fallow_types::output_dead_code::TestOnlyDependencyFinding],
439    root: &Path,
440    severity: Severity,
441) {
442    if deps.is_empty() {
443        return;
444    }
445    for entry in deps {
446        let level = finding_codeclimate(entry, severity);
447        let dep = &entry.dep;
448        let path = cc_path(&dep.path, root);
449        let line = if dep.line > 0 { Some(dep.line) } else { None };
450        let fp = codeclimate_fingerprint_hash(&["fallow/test-only-dependency", &dep.package_name]);
451        issues.push(dead_code_issue(
452            entry.finding_id.as_deref(),
453            entry.introduced,
454            &[],
455            CodeClimateIssueInput {
456                check_name: "fallow/test-only-dependency",
457                description: &format!(
458                    "Package '{}' is only imported by test files (consider moving to devDependencies)",
459                    dep.package_name
460                ),
461                severity: level,
462                category: "Bug Risk",
463                path: &path,
464                begin_line: line,
465                fingerprint: &fp,
466            },
467        ));
468    }
469}
470
471fn push_dev_dep_in_prod_issues(
472    issues: &mut Vec<CodeClimateIssue>,
473    deps: &[fallow_types::output_dead_code::DevDependencyInProductionFinding],
474    root: &Path,
475    severity: Severity,
476) {
477    if deps.is_empty() {
478        return;
479    }
480    for entry in deps {
481        let level = finding_codeclimate(entry, severity);
482        let dep = &entry.dep;
483        let path = cc_path(&dep.path, root);
484        let line = if dep.line > 0 { Some(dep.line) } else { None };
485        let fp = codeclimate_fingerprint_hash(&[
486            "fallow/dev-dependency-in-production",
487            &dep.package_name,
488        ]);
489        issues.push(dead_code_issue(
490            entry.finding_id.as_deref(),
491            entry.introduced,
492            &[],
493            CodeClimateIssueInput {
494                check_name: "fallow/dev-dependency-in-production",
495                description: &format!(
496                    "devDependency '{}' is imported by production code at runtime (consider moving to dependencies)",
497                    dep.package_name
498                ),
499                severity: level,
500                category: "Bug Risk",
501                path: &path,
502                begin_line: line,
503                fingerprint: &fp,
504            },
505        ));
506    }
507}
508
509/// Push CodeClimate issues for unused enum or class members.
510///
511/// `entity_label` is `"Enum"` or `"Class"` so the rendered description reads
512/// "Enum member ..." or "Class member ..." accordingly.
513fn push_unused_member_issues<'a, I>(
514    issues: &mut Vec<CodeClimateIssue>,
515    members: I,
516    root: &Path,
517    rule_id: &str,
518    entity_label: &str,
519    severity: Severity,
520) where
521    I: IntoIterator<
522        Item = (
523            &'a fallow_types::results::UnusedMember,
524            &'a [ReachabilityCaveat],
525            Option<EffectiveSeverity>,
526            Option<&'a str>,
527            Option<AuditIntroduced>,
528        ),
529    >,
530{
531    for (member, caveats, effective, finding_id, introduced) in members {
532        let level = gate_codeclimate(effective, severity);
533        let path = cc_path(&member.path, root);
534        let line_str = member.line.to_string();
535        let fp = codeclimate_fingerprint_hash(&[
536            rule_id,
537            &path,
538            &line_str,
539            &member.parent_name,
540            &member.member_name,
541        ]);
542        issues.push(dead_code_issue(
543            finding_id,
544            introduced,
545            &[],
546            CodeClimateIssueInput {
547                check_name: rule_id,
548                description: &format!(
549                    "{entity_label} member '{}.{}' is never referenced{}",
550                    member.parent_name,
551                    member.member_name,
552                    cc_caveat_suffix(caveats)
553                ),
554                severity: level,
555                category: "Bug Risk",
556                path: &path,
557                begin_line: Some(member.line),
558                fingerprint: &fp,
559            },
560        ));
561    }
562}
563
564fn push_unresolved_import_issues(
565    issues: &mut Vec<CodeClimateIssue>,
566    imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
567    root: &Path,
568    severity: Severity,
569) {
570    if imports.is_empty() {
571        return;
572    }
573    for entry in imports {
574        let level = finding_codeclimate(entry, severity);
575        let import = &entry.import;
576        let path = cc_path(&import.path, root);
577        let line_str = import.line.to_string();
578        let fp = codeclimate_fingerprint_hash(&[
579            "fallow/unresolved-import",
580            &path,
581            &line_str,
582            &import.specifier,
583        ]);
584        issues.push(dead_code_issue(
585            entry.finding_id.as_deref(),
586            entry.introduced,
587            &[],
588            CodeClimateIssueInput {
589                check_name: "fallow/unresolved-import",
590                description: &format!("Import '{}' could not be resolved", import.specifier),
591                severity: level,
592                category: "Bug Risk",
593                path: &path,
594                begin_line: Some(import.line),
595                fingerprint: &fp,
596            },
597        ));
598    }
599}
600
601fn push_unlisted_dep_issues(
602    issues: &mut Vec<CodeClimateIssue>,
603    deps: &[fallow_types::output_dead_code::UnlistedDependencyFinding],
604    root: &Path,
605    severity: Severity,
606) {
607    if deps.is_empty() {
608        return;
609    }
610    for entry in deps {
611        let level = finding_codeclimate(entry, severity);
612        let dep = &entry.dep;
613        let sites: Vec<(String, u32, u32)> = dep
614            .imported_from
615            .iter()
616            .map(|site| (cc_path(&site.path, root), site.line, site.col))
617            .collect();
618        let discriminators = location_discriminators(&sites);
619        for ((path, line, _), discriminator) in sites.iter().zip(&discriminators) {
620            let line_str = line.to_string();
621            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
622            let fp = codeclimate_fingerprint_hash(&[
623                "fallow/unlisted-dependency",
624                path,
625                &line_str,
626                &dep.package_name,
627            ]);
628            issues.push(dead_code_issue(
629                entry.finding_id.as_deref(),
630                entry.introduced,
631                &discriminator,
632                CodeClimateIssueInput {
633                    check_name: "fallow/unlisted-dependency",
634                    description: &format!(
635                        "Package '{}' is imported but not listed in package.json",
636                        dep.package_name
637                    ),
638                    severity: level,
639                    category: "Bug Risk",
640                    path,
641                    begin_line: Some(*line),
642                    fingerprint: &fp,
643                },
644            ));
645        }
646    }
647}
648
649fn push_unlisted_binary_issues(
650    issues: &mut Vec<CodeClimateIssue>,
651    binaries: &[fallow_types::output_dead_code::UnlistedBinaryFinding],
652    root: &Path,
653    severity: Severity,
654) {
655    for entry in binaries {
656        let level = finding_codeclimate(entry, severity);
657        let binary = &entry.binary;
658        let sites: Vec<(String, u32, u32)> = binary
659            .used_in
660            .iter()
661            .map(|site| (cc_path(&site.path, root), site.line, site.col))
662            .collect();
663        let discriminators = location_discriminators(&sites);
664        for ((path, line, _), discriminator) in sites.iter().zip(&discriminators) {
665            let line_str = line.to_string();
666            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
667            let fp = codeclimate_fingerprint_hash(&[
668                "fallow/unlisted-binary",
669                path,
670                &line_str,
671                &binary.binary_name,
672            ]);
673            issues.push(dead_code_issue(
674                entry.finding_id.as_deref(),
675                entry.introduced,
676                &discriminator,
677                CodeClimateIssueInput {
678                    check_name: "fallow/unlisted-binary",
679                    description: &format!(
680                        "Binary '{}' is used but no installed or listed package provides it",
681                        binary.binary_name
682                    ),
683                    severity: level,
684                    category: "Bug Risk",
685                    path,
686                    begin_line: Some(*line),
687                    fingerprint: &fp,
688                },
689            ));
690        }
691    }
692}
693
694fn push_duplicate_export_issues(
695    issues: &mut Vec<CodeClimateIssue>,
696    dups: &[fallow_types::output_dead_code::DuplicateExportFinding],
697    root: &Path,
698    severity: Severity,
699) {
700    if dups.is_empty() {
701        return;
702    }
703    for dup in dups {
704        let level = finding_codeclimate(dup, severity);
705        // The finding id of a duplicate export holds the set of its paths, so
706        // one more or one less location gives the finding a new id. Each
707        // issue is one location, so its fingerprint uses the part of the id
708        // that stays: the rule and the export name. The location discriminator
709        // adds the path. A saved finding without an id keeps the legacy
710        // fingerprint.
711        let location_identity = dup
712            .finding_id
713            .is_some()
714            .then(|| dead_code_finding_id("duplicate-export", &[&dup.export.export_name]));
715        let finding_id = location_identity.as_deref();
716        let introduced = dup.introduced;
717        let dup = &dup.export;
718        let locations: Vec<(String, u32, u32)> = dup
719            .locations
720            .iter()
721            .map(|loc| (cc_path(&loc.path, root), loc.line, loc.col))
722            .collect();
723        let discriminators = location_discriminators(&locations);
724        for ((path, line, _), discriminator) in locations.iter().zip(&discriminators) {
725            let line_str = line.to_string();
726            let discriminator: Vec<&str> = discriminator.iter().map(String::as_str).collect();
727            let fp = codeclimate_fingerprint_hash(&[
728                "fallow/duplicate-export",
729                path,
730                &line_str,
731                &dup.export_name,
732            ]);
733            issues.push(dead_code_issue(
734                finding_id,
735                introduced,
736                &discriminator,
737                CodeClimateIssueInput {
738                    check_name: "fallow/duplicate-export",
739                    description: &format!(
740                        "Export '{}' appears in multiple modules",
741                        dup.export_name
742                    ),
743                    severity: level,
744                    category: "Bug Risk",
745                    path,
746                    begin_line: Some(*line),
747                    fingerprint: &fp,
748                },
749            ));
750        }
751    }
752}
753
754fn push_circular_dep_issues(
755    issues: &mut Vec<CodeClimateIssue>,
756    cycles: &[fallow_types::output_dead_code::CircularDependencyFinding],
757    root: &Path,
758    severity: Severity,
759) {
760    if cycles.is_empty() {
761        return;
762    }
763    for entry in cycles {
764        let level = finding_codeclimate(entry, severity);
765        let cycle = &entry.cycle;
766        let Some(first) = cycle.files.first() else {
767            continue;
768        };
769        let path = cc_path(first, root);
770        let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
771        let chain_str = chain.join(":");
772        let fp = codeclimate_fingerprint_hash(&["fallow/circular-dependency", &chain_str]);
773        let line = if cycle.line > 0 {
774            Some(cycle.line)
775        } else {
776            None
777        };
778        issues.push(dead_code_issue(
779            entry.finding_id.as_deref(),
780            entry.introduced,
781            &[],
782            CodeClimateIssueInput {
783                check_name: "fallow/circular-dependency",
784                description: &format!(
785                    "Circular dependency{}: {}",
786                    if cycle.is_cross_package {
787                        " (cross-package)"
788                    } else {
789                        ""
790                    },
791                    chain.join(" \u{2192} ")
792                ),
793                severity: level,
794                category: "Bug Risk",
795                path: &path,
796                begin_line: line,
797                fingerprint: &fp,
798            },
799        ));
800    }
801}
802
803fn push_re_export_cycle_issues(
804    issues: &mut Vec<CodeClimateIssue>,
805    cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
806    root: &Path,
807    severity: Severity,
808) {
809    if cycles.is_empty() {
810        return;
811    }
812    for entry in cycles {
813        let level = finding_codeclimate(entry, severity);
814        let cycle = &entry.cycle;
815        let Some(first) = cycle.files.first() else {
816            continue;
817        };
818        let path = cc_path(first, root);
819        let chain: Vec<String> = cycle.files.iter().map(|f| cc_path(f, root)).collect();
820        let chain_str = chain.join(":");
821        let kind_token = match cycle.kind {
822            fallow_types::results::ReExportCycleKind::SelfLoop => "self-loop",
823            fallow_types::results::ReExportCycleKind::MultiNode => "multi-node",
824        };
825        let kind_tag = match cycle.kind {
826            fallow_types::results::ReExportCycleKind::SelfLoop => " (self-loop)",
827            fallow_types::results::ReExportCycleKind::MultiNode => "",
828        };
829        let fp = codeclimate_fingerprint_hash(&["fallow/re-export-cycle", kind_token, &chain_str]);
830        issues.push(dead_code_issue(
831            entry.finding_id.as_deref(),
832            entry.introduced,
833            &[],
834            CodeClimateIssueInput {
835                check_name: "fallow/re-export-cycle",
836                description: &format!("Re-export cycle{}: {}", kind_tag, chain.join(" <-> ")),
837                severity: level,
838                category: "Bug Risk",
839                path: &path,
840                begin_line: None,
841                fingerprint: &fp,
842            },
843        ));
844    }
845}
846
847fn push_package_cycle_issues(
848    issues: &mut Vec<CodeClimateIssue>,
849    cycles: &[fallow_types::output_dead_code::PackageCycleFinding],
850    root: &Path,
851    severity: Severity,
852) {
853    for entry in cycles {
854        let level = finding_codeclimate(entry, severity);
855        let cycle = &entry.cycle;
856        let Some(anchor) = cycle.edges.first() else {
857            continue;
858        };
859        let path = cc_path(&anchor.path, root);
860        let packages = cycle.packages.join(":");
861        let fp = codeclimate_fingerprint_hash(&["fallow/package-cycle", &packages]);
862        let note = if cycle.group_truncated {
863            format!(
864                " ({})",
865                fallow_types::results::PackageCycle::GROUP_TRUNCATED_NOTE
866            )
867        } else {
868            String::new()
869        };
870        let mut issue = build_codeclimate_issue(CodeClimateIssueInput {
871            check_name: "fallow/package-cycle",
872            description: &format!("Package cycle: {}{note}", cycle.chain(" \u{2192} ")),
873            severity: level,
874            category: "Bug Risk",
875            path: &path,
876            begin_line: (anchor.line > 0).then_some(anchor.line),
877            fingerprint: &fp,
878        });
879        issue.audit = entry
880            .introduced
881            .map(|AuditIntroduced(introduced)| audit_review_context(introduced));
882        issues.push(issue);
883    }
884}
885
886fn push_boundary_violation_issues(
887    issues: &mut Vec<CodeClimateIssue>,
888    violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
889    root: &Path,
890    severity: Severity,
891) {
892    if violations.is_empty() {
893        return;
894    }
895    for entry in violations {
896        let level = finding_codeclimate(entry, severity);
897        let v = &entry.violation;
898        let path = cc_path(&v.from_path, root);
899        let to = cc_path(&v.to_path, root);
900        let fp = codeclimate_fingerprint_hash(&["fallow/boundary-violation", &path, &to]);
901        let line = if v.line > 0 { Some(v.line) } else { None };
902        let via = v
903            .via_path
904            .as_ref()
905            .map_or_else(String::new, |via| format!(", via {}", cc_path(via, root)));
906        issues.push(dead_code_issue(
907            entry.finding_id.as_deref(),
908            entry.introduced,
909            &[],
910            CodeClimateIssueInput {
911                check_name: "fallow/boundary-violation",
912                description: &format!(
913                    "Boundary violation: {} -> {} ({} -> {}{})",
914                    path, to, v.from_zone, v.to_zone, via
915                ),
916                severity: level,
917                category: "Bug Risk",
918                path: &path,
919                begin_line: line,
920                fingerprint: &fp,
921            },
922        ));
923    }
924}
925
926fn push_boundary_coverage_issues(
927    issues: &mut Vec<CodeClimateIssue>,
928    violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
929    root: &Path,
930    severity: Severity,
931) {
932    if violations.is_empty() {
933        return;
934    }
935    for entry in violations {
936        let level = finding_codeclimate(entry, severity);
937        let v = &entry.violation;
938        let path = cc_path(&v.path, root);
939        let fp = codeclimate_fingerprint_hash(&["fallow/boundary-coverage", &path]);
940        let line = if v.line > 0 { Some(v.line) } else { None };
941        issues.push(dead_code_issue(
942            entry.finding_id.as_deref(),
943            entry.introduced,
944            &[],
945            CodeClimateIssueInput {
946                check_name: "fallow/boundary-coverage",
947                description: &format!("Boundary coverage: {path} matches no configured zone"),
948                severity: level,
949                category: "Bug Risk",
950                path: &path,
951                begin_line: line,
952                fingerprint: &fp,
953            },
954        ));
955    }
956}
957
958fn push_boundary_call_issues(
959    issues: &mut Vec<CodeClimateIssue>,
960    violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
961    root: &Path,
962    severity: Severity,
963) {
964    if violations.is_empty() {
965        return;
966    }
967    for entry in violations {
968        let level = finding_codeclimate(entry, severity);
969        let v = &entry.violation;
970        let path = cc_path(&v.path, root);
971        let fp =
972            codeclimate_fingerprint_hash(&["fallow/boundary-call-violation", &path, &v.callee]);
973        let line = if v.line > 0 { Some(v.line) } else { None };
974        issues.push(dead_code_issue(
975            entry.finding_id.as_deref(),
976            entry.introduced,
977            &[],
978            CodeClimateIssueInput {
979                check_name: "fallow/boundary-call-violation",
980                description: &format!(
981                    "Boundary call: `{}` matches forbidden pattern `{}` in zone '{}'",
982                    v.callee, v.pattern, v.zone
983                ),
984                severity: level,
985                category: "Bug Risk",
986                path: &path,
987                begin_line: line,
988                fingerprint: &fp,
989            },
990        ));
991    }
992}
993
994fn push_policy_violation_issues(
995    issues: &mut Vec<CodeClimateIssue>,
996    violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
997    root: &Path,
998) {
999    use fallow_types::results::PolicyViolationSeverity;
1000
1001    for entry in violations {
1002        let v = &entry.violation;
1003        let path = cc_path(&v.path, root);
1004        let rule = format!("{}/{}", v.pack, v.rule_id);
1005        let fp =
1006            codeclimate_fingerprint_hash(&["fallow/policy-violation", &path, &rule, &v.matched]);
1007        let line = if v.line > 0 { Some(v.line) } else { None };
1008        // Severity comes from the EFFECTIVE per-finding value, not the
1009        // policy-violation master, so a severity: "error" rule under a warn
1010        // master maps to blocker-level just like the exit-code gate.
1011        let level = severity_to_codeclimate(match v.severity {
1012            PolicyViolationSeverity::Error => Severity::Error,
1013            PolicyViolationSeverity::Warn => Severity::Warn,
1014        });
1015        let message = match &v.message {
1016            Some(message) => format!(
1017                "Policy violation: `{}` is banned by `{rule}`. {message}",
1018                v.matched
1019            ),
1020            None => format!("Policy violation: `{}` is banned by `{rule}`", v.matched),
1021        };
1022        issues.push(dead_code_issue(
1023            entry.finding_id.as_deref(),
1024            entry.introduced,
1025            &[],
1026            CodeClimateIssueInput {
1027                check_name: "fallow/policy-violation",
1028                description: &message,
1029                severity: level,
1030                category: "Bug Risk",
1031                path: &path,
1032                begin_line: line,
1033                fingerprint: &fp,
1034            },
1035        ));
1036    }
1037}
1038
1039fn push_invalid_client_export_issues(
1040    issues: &mut Vec<CodeClimateIssue>,
1041    findings: &[fallow_types::output_dead_code::InvalidClientExportFinding],
1042    root: &Path,
1043    severity: Severity,
1044) {
1045    if findings.is_empty() {
1046        return;
1047    }
1048    for entry in findings {
1049        let level = finding_codeclimate(entry, severity);
1050        let e = &entry.export;
1051        let path = cc_path(&e.path, root);
1052        let fp =
1053            codeclimate_fingerprint_hash(&["fallow/invalid-client-export", &path, &e.export_name]);
1054        let line = if e.line > 0 { Some(e.line) } else { None };
1055        let message = format!(
1056            "Export `{}` is not allowed in a \"{}\" file (Next.js server-only / route-config name)",
1057            e.export_name, e.directive
1058        );
1059        issues.push(dead_code_issue(
1060            entry.finding_id.as_deref(),
1061            entry.introduced,
1062            &[],
1063            CodeClimateIssueInput {
1064                check_name: "fallow/invalid-client-export",
1065                description: &message,
1066                severity: level,
1067                category: "Bug Risk",
1068                path: &path,
1069                begin_line: line,
1070                fingerprint: &fp,
1071            },
1072        ));
1073    }
1074}
1075
1076fn push_mixed_client_server_barrel_issues(
1077    issues: &mut Vec<CodeClimateIssue>,
1078    findings: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
1079    root: &Path,
1080    severity: Severity,
1081) {
1082    if findings.is_empty() {
1083        return;
1084    }
1085    for entry in findings {
1086        let level = finding_codeclimate(entry, severity);
1087        let b = &entry.barrel;
1088        let path = cc_path(&b.path, root);
1089        let fp = codeclimate_fingerprint_hash(&[
1090            "fallow/mixed-client-server-barrel",
1091            &path,
1092            &b.client_origin,
1093            &b.server_origin,
1094        ]);
1095        let line = if b.line > 0 { Some(b.line) } else { None };
1096        let message = format!(
1097            "Barrel re-exports both a \"use client\" module (`{}`) and a server-only module (`{}`); one import drags the other's directive across the boundary",
1098            b.client_origin, b.server_origin
1099        );
1100        issues.push(dead_code_issue(
1101            entry.finding_id.as_deref(),
1102            entry.introduced,
1103            &[],
1104            CodeClimateIssueInput {
1105                check_name: "fallow/mixed-client-server-barrel",
1106                description: &message,
1107                severity: level,
1108                category: "Bug Risk",
1109                path: &path,
1110                begin_line: line,
1111                fingerprint: &fp,
1112            },
1113        ));
1114    }
1115}
1116
1117fn push_misplaced_directive_issues(
1118    issues: &mut Vec<CodeClimateIssue>,
1119    findings: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
1120    root: &Path,
1121    severity: Severity,
1122) {
1123    if findings.is_empty() {
1124        return;
1125    }
1126    for entry in findings {
1127        let level = finding_codeclimate(entry, severity);
1128        let d = &entry.directive_site;
1129        let path = cc_path(&d.path, root);
1130        let fp = codeclimate_fingerprint_hash(&[
1131            "fallow/misplaced-directive",
1132            &path,
1133            &d.line.to_string(),
1134            &d.directive,
1135        ]);
1136        let line = if d.line > 0 { Some(d.line) } else { None };
1137        let message = format!(
1138            "Directive `\"{}\"` is not in the leading position, so the RSC bundler ignores it; move it to the top of the file",
1139            d.directive
1140        );
1141        issues.push(dead_code_issue(
1142            entry.finding_id.as_deref(),
1143            entry.introduced,
1144            &[],
1145            CodeClimateIssueInput {
1146                check_name: "fallow/misplaced-directive",
1147                description: &message,
1148                severity: level,
1149                category: "Bug Risk",
1150                path: &path,
1151                begin_line: line,
1152                fingerprint: &fp,
1153            },
1154        ));
1155    }
1156}
1157
1158fn push_unprovided_inject_issues(
1159    issues: &mut Vec<CodeClimateIssue>,
1160    findings: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
1161    root: &Path,
1162    severity: Severity,
1163) {
1164    if findings.is_empty() {
1165        return;
1166    }
1167    for entry in findings {
1168        let level = finding_codeclimate(entry, severity);
1169        let i = &entry.inject;
1170        let path = cc_path(&i.path, root);
1171        let fp = codeclimate_fingerprint_hash(&[
1172            "fallow/unprovided-inject",
1173            &path,
1174            &i.line.to_string(),
1175            &i.key_name,
1176        ]);
1177        let line = if i.line > 0 { Some(i.line) } else { None };
1178        let message = format!(
1179            "inject(`{}`) has no matching provide(`{}`) in this project; at runtime it returns undefined (provide the key or remove this inject)",
1180            i.key_name, i.key_name
1181        );
1182        issues.push(dead_code_issue(
1183            entry.finding_id.as_deref(),
1184            entry.introduced,
1185            &[],
1186            CodeClimateIssueInput {
1187                check_name: "fallow/unprovided-inject",
1188                description: &message,
1189                severity: level,
1190                category: "Bug Risk",
1191                path: &path,
1192                begin_line: line,
1193                fingerprint: &fp,
1194            },
1195        ));
1196    }
1197}
1198
1199fn push_unrendered_component_issues(
1200    issues: &mut Vec<CodeClimateIssue>,
1201    findings: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
1202    root: &Path,
1203    severity: Severity,
1204) {
1205    if findings.is_empty() {
1206        return;
1207    }
1208    for entry in findings {
1209        let level = finding_codeclimate(entry, severity);
1210        let c = &entry.component;
1211        let path = cc_path(&c.path, root);
1212        let fp = codeclimate_fingerprint_hash(&[
1213            "fallow/unrendered-component",
1214            &path,
1215            &c.line.to_string(),
1216            &c.component_name,
1217        ]);
1218        let line = if c.line > 0 { Some(c.line) } else { None };
1219        let message = format!(
1220            "component `{}` is reachable but rendered nowhere in this project (render it somewhere or remove it)",
1221            c.component_name
1222        );
1223        issues.push(dead_code_issue(
1224            entry.finding_id.as_deref(),
1225            entry.introduced,
1226            &[],
1227            CodeClimateIssueInput {
1228                check_name: "fallow/unrendered-component",
1229                description: &message,
1230                severity: level,
1231                category: "Bug Risk",
1232                path: &path,
1233                begin_line: line,
1234                fingerprint: &fp,
1235            },
1236        ));
1237    }
1238}
1239
1240fn push_absent_component_prop_issues(
1241    issues: &mut Vec<CodeClimateIssue>,
1242    findings: &[fallow_types::output_dead_code::AbsentComponentPropFinding],
1243    root: &Path,
1244    severity: Severity,
1245) {
1246    for finding in findings {
1247        let prop = &finding.prop;
1248        let path = cc_path(&prop.path, root);
1249        let fingerprint = codeclimate_fingerprint_hash(&[
1250            "fallow/absent-component-prop",
1251            &path,
1252            &prop.component_name,
1253            &prop.prop_name,
1254        ]);
1255        let description = format!(
1256            "Optional prop '{}.{}' is absent from inspected callers. {}",
1257            prop.component_name, prop.prop_name, prop.explanation
1258        );
1259        issues.push(dead_code_issue(
1260            finding.finding_id.as_deref(),
1261            finding.introduced,
1262            &[],
1263            CodeClimateIssueInput {
1264                check_name: "fallow/absent-component-prop",
1265                description: &description,
1266                severity: finding_codeclimate(finding, severity),
1267                category: "Clarity",
1268                path: &path,
1269                begin_line: Some(prop.line),
1270                fingerprint: &fingerprint,
1271            },
1272        ));
1273    }
1274}
1275
1276fn push_unused_component_prop_issues(
1277    issues: &mut Vec<CodeClimateIssue>,
1278    findings: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
1279    root: &Path,
1280    severity: Severity,
1281) {
1282    if findings.is_empty() {
1283        return;
1284    }
1285    for entry in findings {
1286        let level = finding_codeclimate(entry, severity);
1287        let p = &entry.prop;
1288        let path = cc_path(&p.path, root);
1289        let fp = codeclimate_fingerprint_hash(&[
1290            "fallow/unused-component-prop",
1291            &path,
1292            &p.line.to_string(),
1293            &p.prop_name,
1294        ]);
1295        let line = if p.line > 0 { Some(p.line) } else { None };
1296        let message = format!(
1297            "prop `{}` is declared but referenced nowhere in component `{}` (remove it or use it)",
1298            p.prop_name, p.component_name
1299        );
1300        issues.push(dead_code_issue(
1301            entry.finding_id.as_deref(),
1302            entry.introduced,
1303            &[],
1304            CodeClimateIssueInput {
1305                check_name: "fallow/unused-component-prop",
1306                description: &message,
1307                severity: level,
1308                category: "Bug Risk",
1309                path: &path,
1310                begin_line: line,
1311                fingerprint: &fp,
1312            },
1313        ));
1314    }
1315}
1316
1317fn push_unused_component_emit_issues(
1318    issues: &mut Vec<CodeClimateIssue>,
1319    findings: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
1320    root: &Path,
1321    severity: Severity,
1322) {
1323    if findings.is_empty() {
1324        return;
1325    }
1326    for entry in findings {
1327        let level = finding_codeclimate(entry, severity);
1328        let e = &entry.emit;
1329        let path = cc_path(&e.path, root);
1330        let fp = codeclimate_fingerprint_hash(&[
1331            "fallow/unused-component-emit",
1332            &path,
1333            &e.line.to_string(),
1334            &e.emit_name,
1335        ]);
1336        let line = if e.line > 0 { Some(e.line) } else { None };
1337        let message = format!(
1338            "emit `{}` is declared but emitted nowhere in component `{}` (remove it or emit it)",
1339            e.emit_name, e.component_name
1340        );
1341        issues.push(dead_code_issue(
1342            entry.finding_id.as_deref(),
1343            entry.introduced,
1344            &[],
1345            CodeClimateIssueInput {
1346                check_name: "fallow/unused-component-emit",
1347                description: &message,
1348                severity: level,
1349                category: "Bug Risk",
1350                path: &path,
1351                begin_line: line,
1352                fingerprint: &fp,
1353            },
1354        ));
1355    }
1356}
1357
1358fn push_unused_effect_layer_issues(
1359    issues: &mut Vec<CodeClimateIssue>,
1360    findings: &[fallow_types::output_dead_code::UnusedEffectLayerFinding],
1361    root: &Path,
1362    severity: Severity,
1363) {
1364    for entry in findings {
1365        let level = finding_codeclimate(entry, severity);
1366        let f = &entry.layer;
1367        let path = cc_path(&f.path, root);
1368        let fp = codeclimate_fingerprint_hash(&[
1369            "fallow/unused-effect-layer",
1370            &path,
1371            &f.line.to_string(),
1372            &f.name,
1373        ]);
1374        let line = if f.line > 0 { Some(f.line) } else { None };
1375        let message = format!(
1376            "layer `{}` is composed only into layers that nothing uses ({}); compose it into a live layer or remove it",
1377            f.name,
1378            f.dead_consumers.join(", ")
1379        );
1380        issues.push(dead_code_issue(
1381            entry.finding_id.as_deref(),
1382            entry.introduced,
1383            &[],
1384            CodeClimateIssueInput {
1385                check_name: "fallow/unused-effect-layer",
1386                description: &message,
1387                severity: level,
1388                category: "Bug Risk",
1389                path: &path,
1390                begin_line: line,
1391                fingerprint: &fp,
1392            },
1393        ));
1394    }
1395}
1396
1397fn push_duplicate_export_alias_issues(
1398    issues: &mut Vec<CodeClimateIssue>,
1399    findings: &[fallow_types::output_dead_code::DuplicateExportAliasFinding],
1400    root: &Path,
1401    severity: Severity,
1402) {
1403    for entry in findings {
1404        let level = finding_codeclimate(entry, severity);
1405        let f = &entry.alias;
1406        let path = cc_path(&f.path, root);
1407        let names = f.export_names.join(",");
1408        let fp = codeclimate_fingerprint_hash(&[
1409            "fallow/duplicate-export-alias",
1410            &path,
1411            &f.local_name,
1412            &names,
1413        ]);
1414        let line = if f.line > 0 { Some(f.line) } else { None };
1415        let message = format!(
1416            "`{}` is exported under {} names ({}); keep one name or add the names to ignoreExports",
1417            f.local_name,
1418            f.export_names.len(),
1419            f.export_names.join(", ")
1420        );
1421        issues.push(dead_code_issue(
1422            entry.finding_id.as_deref(),
1423            entry.introduced,
1424            &[],
1425            CodeClimateIssueInput {
1426                check_name: "fallow/duplicate-export-alias",
1427                description: &message,
1428                severity: level,
1429                category: "Duplication",
1430                path: &path,
1431                begin_line: line,
1432                fingerprint: &fp,
1433            },
1434        ));
1435    }
1436}
1437
1438fn push_unused_tagged_error_issues(
1439    issues: &mut Vec<CodeClimateIssue>,
1440    findings: &[fallow_types::output_dead_code::UnusedTaggedErrorFinding],
1441    root: &Path,
1442    severity: Severity,
1443) {
1444    for entry in findings {
1445        let level = finding_codeclimate(entry, severity);
1446        let f = &entry.error;
1447        let path = cc_path(&f.path, root);
1448        let fp = codeclimate_fingerprint_hash(&[
1449            "fallow/unused-tagged-error",
1450            &path,
1451            &f.line.to_string(),
1452            &f.name,
1453        ]);
1454        let line = if f.line > 0 { Some(f.line) } else { None };
1455        let message = format!(
1456            "tagged error `{}` (tag `{}`) is never constructed or failed with; fail with it or remove it",
1457            f.name, f.tag
1458        );
1459        issues.push(dead_code_issue(
1460            entry.finding_id.as_deref(),
1461            entry.introduced,
1462            &[],
1463            CodeClimateIssueInput {
1464                check_name: "fallow/unused-tagged-error",
1465                description: &message,
1466                severity: level,
1467                category: "Bug Risk",
1468                path: &path,
1469                begin_line: line,
1470                fingerprint: &fp,
1471            },
1472        ));
1473    }
1474}
1475
1476fn push_unproduced_catch_tag_issues(
1477    issues: &mut Vec<CodeClimateIssue>,
1478    findings: &[fallow_types::output_dead_code::UnproducedCatchTagFinding],
1479    root: &Path,
1480    severity: Severity,
1481) {
1482    for entry in findings {
1483        let level = finding_codeclimate(entry, severity);
1484        let f = &entry.catch_tag;
1485        let path = cc_path(&f.path, root);
1486        let fp = codeclimate_fingerprint_hash(&[
1487            "fallow/unproduced-catch-tag",
1488            &path,
1489            &f.line.to_string(),
1490            &f.tag,
1491        ]);
1492        let line = if f.line > 0 { Some(f.line) } else { None };
1493        let message = format!(
1494            "catchTag handler for `{}` never runs: no code produces {}",
1495            f.tag,
1496            f.candidate_classes.join(", ")
1497        );
1498        issues.push(dead_code_issue(
1499            entry.finding_id.as_deref(),
1500            entry.introduced,
1501            &[],
1502            CodeClimateIssueInput {
1503                check_name: "fallow/unproduced-catch-tag",
1504                description: &message,
1505                severity: level,
1506                category: "Bug Risk",
1507                path: &path,
1508                begin_line: line,
1509                fingerprint: &fp,
1510            },
1511        ));
1512    }
1513}
1514
1515fn push_unused_server_action_issues(
1516    issues: &mut Vec<CodeClimateIssue>,
1517    findings: &[fallow_types::output_dead_code::UnusedServerActionFinding],
1518    root: &Path,
1519    severity: Severity,
1520) {
1521    if findings.is_empty() {
1522        return;
1523    }
1524    for entry in findings {
1525        let level = finding_codeclimate(entry, severity);
1526        let a = &entry.action;
1527        let path = cc_path(&a.path, root);
1528        let fp = codeclimate_fingerprint_hash(&[
1529            "fallow/unused-server-action",
1530            &path,
1531            &a.line.to_string(),
1532            &a.action_name,
1533        ]);
1534        let line = if a.line > 0 { Some(a.line) } else { None };
1535        let message = format!(
1536            "server action `{}` is exported from a \"use server\" file but no code in this project references it (wire it to a consumer or remove it)",
1537            a.action_name
1538        );
1539        issues.push(dead_code_issue(
1540            entry.finding_id.as_deref(),
1541            entry.introduced,
1542            &[],
1543            CodeClimateIssueInput {
1544                check_name: "fallow/unused-server-action",
1545                description: &message,
1546                severity: level,
1547                category: "Bug Risk",
1548                path: &path,
1549                begin_line: line,
1550                fingerprint: &fp,
1551            },
1552        ));
1553    }
1554}
1555
1556fn push_unused_load_data_key_issues(
1557    issues: &mut Vec<CodeClimateIssue>,
1558    findings: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
1559    root: &Path,
1560    severity: Severity,
1561) {
1562    if findings.is_empty() {
1563        return;
1564    }
1565    for entry in findings {
1566        let level = finding_codeclimate(entry, severity);
1567        let k = &entry.key;
1568        let path = cc_path(&k.path, root);
1569        let fp = codeclimate_fingerprint_hash(&[
1570            "fallow/unused-load-data-key",
1571            &path,
1572            &k.line.to_string(),
1573            &k.key_name,
1574        ]);
1575        let line = if k.line > 0 { Some(k.line) } else { None };
1576        let message = format!(
1577            "load() return key `{}` is read by no consumer (sibling +page.svelte data.<key> or project-wide page.data.<key>); delete the key or wire a consumer",
1578            k.key_name
1579        );
1580        issues.push(dead_code_issue(
1581            entry.finding_id.as_deref(),
1582            entry.introduced,
1583            &[],
1584            CodeClimateIssueInput {
1585                check_name: "fallow/unused-load-data-key",
1586                description: &message,
1587                severity: level,
1588                category: "Bug Risk",
1589                path: &path,
1590                begin_line: line,
1591                fingerprint: &fp,
1592            },
1593        ));
1594    }
1595}
1596
1597fn push_route_collision_issues(
1598    issues: &mut Vec<CodeClimateIssue>,
1599    findings: &[fallow_types::output_dead_code::RouteCollisionFinding],
1600    root: &Path,
1601    severity: Severity,
1602) {
1603    if findings.is_empty() {
1604        return;
1605    }
1606    for entry in findings {
1607        let level = finding_codeclimate(entry, severity);
1608        let c = &entry.collision;
1609        let path = cc_path(&c.path, root);
1610        let fp = codeclimate_fingerprint_hash(&["fallow/route-collision", &path, &c.url]);
1611        let line = if c.line > 0 { Some(c.line) } else { None };
1612        let message = format!(
1613            "Route file resolves to `{}`, also owned by {} other file(s); Next.js fails the build because a URL can have only one owner",
1614            c.url,
1615            c.conflicting_paths.len()
1616        );
1617        issues.push(dead_code_issue(
1618            entry.finding_id.as_deref(),
1619            entry.introduced,
1620            &[],
1621            CodeClimateIssueInput {
1622                check_name: "fallow/route-collision",
1623                description: &message,
1624                severity: level,
1625                category: "Bug Risk",
1626                path: &path,
1627                begin_line: line,
1628                fingerprint: &fp,
1629            },
1630        ));
1631    }
1632}
1633
1634fn push_dynamic_segment_name_conflict_issues(
1635    issues: &mut Vec<CodeClimateIssue>,
1636    findings: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
1637    root: &Path,
1638    severity: Severity,
1639) {
1640    if findings.is_empty() {
1641        return;
1642    }
1643    for entry in findings {
1644        let level = finding_codeclimate(entry, severity);
1645        let c = &entry.conflict;
1646        let path = cc_path(&c.path, root);
1647        let fp = codeclimate_fingerprint_hash(&[
1648            "fallow/dynamic-segment-name-conflict",
1649            &path,
1650            &c.position,
1651        ]);
1652        let line = if c.line > 0 { Some(c.line) } else { None };
1653        let message = format!(
1654            "Dynamic segments at `{}` use different slug names ({}); Next.js requires one consistent name per dynamic path",
1655            c.position,
1656            c.conflicting_segments.join(", ")
1657        );
1658        issues.push(dead_code_issue(
1659            entry.finding_id.as_deref(),
1660            entry.introduced,
1661            &[],
1662            CodeClimateIssueInput {
1663                check_name: "fallow/dynamic-segment-name-conflict",
1664                description: &message,
1665                severity: level,
1666                category: "Bug Risk",
1667                path: &path,
1668                begin_line: line,
1669                fingerprint: &fp,
1670            },
1671        ));
1672    }
1673}
1674
1675fn push_stale_suppression_issues(
1676    issues: &mut Vec<CodeClimateIssue>,
1677    suppressions: &[fallow_types::results::StaleSuppression],
1678    root: &Path,
1679    rules: &RulesConfig,
1680) {
1681    if suppressions.is_empty() {
1682        return;
1683    }
1684    for s in suppressions {
1685        let severity = if s.missing_reason {
1686            rules.require_suppression_reason
1687        } else {
1688            rules.stale_suppressions
1689        };
1690        let level = finding_codeclimate(s, severity);
1691        let path = cc_path(&s.path, root);
1692        let line_str = s.line.to_string();
1693        let check_name = if s.missing_reason {
1694            "fallow/missing-suppression-reason"
1695        } else {
1696            "fallow/stale-suppression"
1697        };
1698        let fp = codeclimate_fingerprint_hash(&[check_name, &path, &line_str]);
1699        issues.push(dead_code_issue(
1700            s.finding_id.as_deref(),
1701            // The audit sets this flag with `set_stale_suppression_audit_attribution`.
1702            None,
1703            &[],
1704            CodeClimateIssueInput {
1705                check_name,
1706                description: &s.display_message(),
1707                severity: level,
1708                category: "Bug Risk",
1709                path: &path,
1710                begin_line: Some(s.line),
1711                fingerprint: &fp,
1712            },
1713        ));
1714    }
1715}
1716
1717/// Build CodeClimate issues from dead-code analysis results.
1718///
1719/// Returns the typed [`CodeClimateIssue`] vec; callers that emit the wire
1720/// shape convert via [`fallow_output::codeclimate_issues_to_value`]. The schema
1721/// drift gate locks the per-issue shape against
1722/// [`fallow_output::CodeClimateOutput`].
1723#[must_use]
1724pub fn build_codeclimate(
1725    results: &AnalysisResults,
1726    root: &Path,
1727    rules: &RulesConfig,
1728) -> Vec<CodeClimateIssue> {
1729    CodeClimateBuilder {
1730        issues: Vec::new(),
1731        results,
1732        root,
1733        rules,
1734    }
1735    .build()
1736}
1737
1738struct CodeClimateBuilder<'a> {
1739    issues: Vec<CodeClimateIssue>,
1740    results: &'a AnalysisResults,
1741    root: &'a Path,
1742    rules: &'a RulesConfig,
1743}
1744
1745impl CodeClimateBuilder<'_> {
1746    fn build(mut self) -> Vec<CodeClimateIssue> {
1747        self.push_file_and_export_issues();
1748        self.push_private_type_leak_issues();
1749        push_deprecated_export_issues(
1750            &mut self.issues,
1751            &self.results.deprecated_exports_in_use,
1752            self.root,
1753            self.rules.deprecated_exports_in_use,
1754        );
1755        self.push_package_dependency_issues();
1756        self.push_type_test_dependency_issues();
1757        self.push_member_issues();
1758        self.push_import_and_duplicate_issues();
1759        self.push_graph_issues();
1760        self.push_boundary_issues();
1761        self.push_suppression_and_catalog_issues();
1762        self.push_override_issues();
1763        self.push_prop_drilling_issues();
1764        self.push_component_shape_issues();
1765        self.issues
1766    }
1767
1768    fn push_file_and_export_issues(&mut self) {
1769        push_unused_file_issues(
1770            &mut self.issues,
1771            &self.results.unused_files,
1772            self.root,
1773            self.rules.unused_files,
1774        );
1775        push_unused_export_issues(UnusedExportIssuesInput {
1776            issues: &mut self.issues,
1777            exports: self.results.unused_exports.iter().map(|e| {
1778                (
1779                    &e.export,
1780                    e.reachability_caveats.as_slice(),
1781                    e.effective_severity,
1782                    e.finding_id.as_deref(),
1783                    e.introduced,
1784                )
1785            }),
1786            root: self.root,
1787            rule_id: "fallow/unused-export",
1788            direct_label: "Export",
1789            re_export_label: "Re-export",
1790            severity: self.rules.unused_exports,
1791        });
1792        push_unused_export_issues(UnusedExportIssuesInput {
1793            issues: &mut self.issues,
1794            exports: self.results.unused_types.iter().map(|e| {
1795                (
1796                    &e.export,
1797                    e.reachability_caveats.as_slice(),
1798                    e.effective_severity,
1799                    e.finding_id.as_deref(),
1800                    e.introduced,
1801                )
1802            }),
1803            root: self.root,
1804            rule_id: "fallow/unused-type",
1805            direct_label: "Type export",
1806            re_export_label: "Type re-export",
1807            severity: self.rules.unused_types,
1808        });
1809    }
1810
1811    fn push_private_type_leak_issues(&mut self) {
1812        push_private_type_leak_issues(
1813            &mut self.issues,
1814            &self.results.private_type_leaks,
1815            self.root,
1816            self.rules.private_type_leaks,
1817        );
1818    }
1819
1820    fn push_package_dependency_issues(&mut self) {
1821        push_dep_cc_issues(
1822            &mut self.issues,
1823            self.results.unused_dependencies.iter().map(|f| {
1824                (
1825                    &f.dep,
1826                    f.reachability_caveats.as_slice(),
1827                    f.effective_severity,
1828                    f.finding_id.as_deref(),
1829                    f.introduced,
1830                )
1831            }),
1832            self.root,
1833            "fallow/unused-dependency",
1834            "dependencies",
1835            self.rules.unused_dependencies,
1836        );
1837        push_dep_cc_issues(
1838            &mut self.issues,
1839            self.results.unused_dev_dependencies.iter().map(|f| {
1840                (
1841                    &f.dep,
1842                    f.reachability_caveats.as_slice(),
1843                    f.effective_severity,
1844                    f.finding_id.as_deref(),
1845                    f.introduced,
1846                )
1847            }),
1848            self.root,
1849            "fallow/unused-dev-dependency",
1850            "devDependencies",
1851            self.rules.unused_dev_dependencies,
1852        );
1853        push_dep_cc_issues(
1854            &mut self.issues,
1855            self.results.unused_optional_dependencies.iter().map(|f| {
1856                (
1857                    &f.dep,
1858                    f.reachability_caveats.as_slice(),
1859                    f.effective_severity,
1860                    f.finding_id.as_deref(),
1861                    f.introduced,
1862                )
1863            }),
1864            self.root,
1865            "fallow/unused-optional-dependency",
1866            "optionalDependencies",
1867            self.rules.unused_optional_dependencies,
1868        );
1869    }
1870
1871    fn push_type_test_dependency_issues(&mut self) {
1872        push_type_only_dep_issues(
1873            &mut self.issues,
1874            &self.results.type_only_dependencies,
1875            self.root,
1876            self.rules.type_only_dependencies,
1877        );
1878        push_test_only_dep_issues(
1879            &mut self.issues,
1880            &self.results.test_only_dependencies,
1881            self.root,
1882            self.rules.test_only_dependencies,
1883        );
1884        push_dev_dep_in_prod_issues(
1885            &mut self.issues,
1886            &self.results.dev_dependencies_in_production,
1887            self.root,
1888            self.rules.dev_dependencies_in_production,
1889        );
1890    }
1891
1892    fn push_member_issues(&mut self) {
1893        push_unused_member_issues(
1894            &mut self.issues,
1895            self.results.unused_enum_members.iter().map(|m| {
1896                (
1897                    &m.member,
1898                    m.reachability_caveats.as_slice(),
1899                    m.effective_severity,
1900                    m.finding_id.as_deref(),
1901                    m.introduced,
1902                )
1903            }),
1904            self.root,
1905            "fallow/unused-enum-member",
1906            "Enum",
1907            self.rules.unused_enum_members,
1908        );
1909        push_unused_member_issues(
1910            &mut self.issues,
1911            self.results.unused_class_members.iter().map(|m| {
1912                (
1913                    &m.member,
1914                    m.reachability_caveats.as_slice(),
1915                    m.effective_severity,
1916                    m.finding_id.as_deref(),
1917                    m.introduced,
1918                )
1919            }),
1920            self.root,
1921            "fallow/unused-class-member",
1922            "Class",
1923            self.rules.unused_class_members,
1924        );
1925        push_unused_member_issues(
1926            &mut self.issues,
1927            self.results.unused_store_members.iter().map(|m| {
1928                (
1929                    &m.member,
1930                    m.reachability_caveats.as_slice(),
1931                    m.effective_severity,
1932                    m.finding_id.as_deref(),
1933                    m.introduced,
1934                )
1935            }),
1936            self.root,
1937            "fallow/unused-store-member",
1938            "Store",
1939            self.rules.unused_store_members,
1940        );
1941        push_unused_member_issues(
1942            &mut self.issues,
1943            self.results.unused_namespace_members.iter().map(|m| {
1944                (
1945                    &m.member,
1946                    m.reachability_caveats.as_slice(),
1947                    m.effective_severity,
1948                    m.finding_id.as_deref(),
1949                    m.introduced,
1950                )
1951            }),
1952            self.root,
1953            "fallow/unused-namespace-member",
1954            "Namespace",
1955            self.rules.unused_namespace_members,
1956        );
1957    }
1958
1959    fn push_import_and_duplicate_issues(&mut self) {
1960        push_unresolved_import_issues(
1961            &mut self.issues,
1962            &self.results.unresolved_imports,
1963            self.root,
1964            self.rules.unresolved_imports,
1965        );
1966        push_unlisted_dep_issues(
1967            &mut self.issues,
1968            &self.results.unlisted_dependencies,
1969            self.root,
1970            self.rules.unlisted_dependencies,
1971        );
1972        push_unlisted_binary_issues(
1973            &mut self.issues,
1974            &self.results.unlisted_binaries,
1975            self.root,
1976            self.rules.unlisted_binaries,
1977        );
1978        push_duplicate_export_issues(
1979            &mut self.issues,
1980            &self.results.duplicate_exports,
1981            self.root,
1982            self.rules.duplicate_exports,
1983        );
1984    }
1985
1986    fn push_graph_issues(&mut self) {
1987        push_circular_dep_issues(
1988            &mut self.issues,
1989            &self.results.circular_dependencies,
1990            self.root,
1991            self.rules.circular_dependencies,
1992        );
1993        push_re_export_cycle_issues(
1994            &mut self.issues,
1995            &self.results.re_export_cycles,
1996            self.root,
1997            self.rules.re_export_cycle,
1998        );
1999        push_package_cycle_issues(
2000            &mut self.issues,
2001            &self.results.package_cycles,
2002            self.root,
2003            self.rules.package_cycle,
2004        );
2005    }
2006
2007    fn push_boundary_issues(&mut self) {
2008        self.push_architecture_boundary_issues();
2009        self.push_client_server_boundary_issues();
2010        self.push_component_boundary_issues();
2011        self.push_framework_route_issues();
2012    }
2013
2014    fn push_architecture_boundary_issues(&mut self) {
2015        push_boundary_violation_issues(
2016            &mut self.issues,
2017            &self.results.boundary_violations,
2018            self.root,
2019            self.rules.boundary_violation,
2020        );
2021        push_boundary_coverage_issues(
2022            &mut self.issues,
2023            &self.results.boundary_coverage_violations,
2024            self.root,
2025            self.rules.boundary_violation,
2026        );
2027        push_boundary_call_issues(
2028            &mut self.issues,
2029            &self.results.boundary_call_violations,
2030            self.root,
2031            self.rules.boundary_violation,
2032        );
2033        push_policy_violation_issues(&mut self.issues, &self.results.policy_violations, self.root);
2034    }
2035
2036    fn push_client_server_boundary_issues(&mut self) {
2037        push_invalid_client_export_issues(
2038            &mut self.issues,
2039            &self.results.invalid_client_exports,
2040            self.root,
2041            self.rules.invalid_client_export,
2042        );
2043        push_mixed_client_server_barrel_issues(
2044            &mut self.issues,
2045            &self.results.mixed_client_server_barrels,
2046            self.root,
2047            self.rules.mixed_client_server_barrel,
2048        );
2049        push_misplaced_directive_issues(
2050            &mut self.issues,
2051            &self.results.misplaced_directives,
2052            self.root,
2053            self.rules.misplaced_directive,
2054        );
2055    }
2056
2057    fn push_component_boundary_issues(&mut self) {
2058        push_unprovided_inject_issues(
2059            &mut self.issues,
2060            &self.results.unprovided_injects,
2061            self.root,
2062            self.rules.unprovided_injects,
2063        );
2064        push_unrendered_component_issues(
2065            &mut self.issues,
2066            &self.results.unrendered_components,
2067            self.root,
2068            self.rules.unrendered_components,
2069        );
2070        push_absent_component_prop_issues(
2071            &mut self.issues,
2072            &self.results.absent_component_props,
2073            self.root,
2074            self.rules.absent_component_props,
2075        );
2076        push_unused_component_prop_issues(
2077            &mut self.issues,
2078            &self.results.unused_component_props,
2079            self.root,
2080            self.rules.unused_component_props,
2081        );
2082        push_unused_component_emit_issues(
2083            &mut self.issues,
2084            &self.results.unused_component_emits,
2085            self.root,
2086            self.rules.unused_component_emits,
2087        );
2088        push_unused_component_input_issues(
2089            &mut self.issues,
2090            &self.results.unused_component_inputs,
2091            self.root,
2092            self.rules.unused_component_inputs,
2093        );
2094        push_unused_component_output_issues(
2095            &mut self.issues,
2096            &self.results.unused_component_outputs,
2097            self.root,
2098            self.rules.unused_component_outputs,
2099        );
2100        push_unused_svelte_event_issues(
2101            &mut self.issues,
2102            &self.results.unused_svelte_events,
2103            self.root,
2104            self.rules.unused_svelte_events,
2105        );
2106        push_unused_effect_layer_issues(
2107            &mut self.issues,
2108            &self.results.unused_effect_layers,
2109            self.root,
2110            self.rules.unused_effect_layers,
2111        );
2112        push_duplicate_export_alias_issues(
2113            &mut self.issues,
2114            &self.results.duplicate_export_aliases,
2115            self.root,
2116            self.rules.duplicate_export_aliases,
2117        );
2118        push_unused_tagged_error_issues(
2119            &mut self.issues,
2120            &self.results.unused_tagged_errors,
2121            self.root,
2122            self.rules.unused_tagged_errors,
2123        );
2124        push_unproduced_catch_tag_issues(
2125            &mut self.issues,
2126            &self.results.unproduced_catch_tags,
2127            self.root,
2128            self.rules.unproduced_catch_tags,
2129        );
2130    }
2131
2132    fn push_framework_route_issues(&mut self) {
2133        push_unused_server_action_issues(
2134            &mut self.issues,
2135            &self.results.unused_server_actions,
2136            self.root,
2137            self.rules.unused_server_actions,
2138        );
2139        push_unused_load_data_key_issues(
2140            &mut self.issues,
2141            &self.results.unused_load_data_keys,
2142            self.root,
2143            self.rules.unused_load_data_keys,
2144        );
2145        push_route_collision_issues(
2146            &mut self.issues,
2147            &self.results.route_collisions,
2148            self.root,
2149            self.rules.route_collision,
2150        );
2151        push_dynamic_segment_name_conflict_issues(
2152            &mut self.issues,
2153            &self.results.dynamic_segment_name_conflicts,
2154            self.root,
2155            self.rules.dynamic_segment_name_conflict,
2156        );
2157    }
2158
2159    fn push_suppression_and_catalog_issues(&mut self) {
2160        push_stale_suppression_issues(
2161            &mut self.issues,
2162            &self.results.stale_suppressions,
2163            self.root,
2164            self.rules,
2165        );
2166        push_unused_catalog_entry_issues(
2167            &mut self.issues,
2168            &self.results.unused_catalog_entries,
2169            self.root,
2170            self.rules.unused_catalog_entries,
2171        );
2172        push_empty_catalog_group_issues(
2173            &mut self.issues,
2174            &self.results.empty_catalog_groups,
2175            self.root,
2176            self.rules.empty_catalog_groups,
2177        );
2178        push_unresolved_catalog_reference_issues(
2179            &mut self.issues,
2180            &self.results.unresolved_catalog_references,
2181            self.root,
2182            self.rules.unresolved_catalog_references,
2183        );
2184    }
2185
2186    fn push_override_issues(&mut self) {
2187        push_unused_dependency_override_issues(
2188            &mut self.issues,
2189            &self.results.unused_dependency_overrides,
2190            self.root,
2191            self.rules.unused_dependency_overrides,
2192        );
2193        push_misconfigured_dependency_override_issues(
2194            &mut self.issues,
2195            &self.results.misconfigured_dependency_overrides,
2196            self.root,
2197            self.rules.misconfigured_dependency_overrides,
2198        );
2199    }
2200}
2201
2202#[cfg(test)]
2203#[path = "dead_code_codeclimate_tests.rs"]
2204mod tests;