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