Skip to main content

fallow_cli/report/
sarif.rs

1use std::path::{Path, PathBuf};
2use std::process::ExitCode;
3
4use fallow_config::{RulesConfig, Severity};
5use fallow_core::duplicates::DuplicationReport;
6use fallow_core::results::{
7    AnalysisResults, BoundaryViolation, CircularDependency, DuplicateExportFinding,
8    EmptyCatalogGroupFinding, MisconfiguredDependencyOverrideFinding, PrivateTypeLeak,
9    StaleSuppression, TestOnlyDependency, TypeOnlyDependency, UnlistedDependencyFinding,
10    UnresolvedCatalogReferenceFinding, UnresolvedImport, UnusedCatalogEntryFinding,
11    UnusedDependency, UnusedDependencyOverrideFinding, UnusedExport, UnusedFile, UnusedMember,
12};
13use rustc_hash::FxHashMap;
14
15use super::ci::{fingerprint, severity};
16use super::grouping::{self, OwnershipResolver};
17use super::{emit_json, relative_uri};
18use crate::explain;
19
20/// Intermediate fields extracted from an issue for SARIF result construction.
21struct SarifFields {
22    rule_id: &'static str,
23    level: &'static str,
24    message: String,
25    uri: String,
26    region: Option<(u32, u32)>,
27    source_path: Option<PathBuf>,
28    properties: Option<serde_json::Value>,
29}
30
31#[derive(Default)]
32struct SourceSnippetCache {
33    files: FxHashMap<PathBuf, Vec<String>>,
34}
35
36impl SourceSnippetCache {
37    fn line(&mut self, path: &Path, line: u32) -> Option<String> {
38        if line == 0 {
39            return None;
40        }
41        if !self.files.contains_key(path) {
42            let lines = std::fs::read_to_string(path)
43                .ok()
44                .map(|source| source.lines().map(str::to_owned).collect())
45                .unwrap_or_default();
46            self.files.insert(path.to_path_buf(), lines);
47        }
48        self.files
49            .get(path)
50            .and_then(|lines| lines.get(line.saturating_sub(1) as usize))
51            .cloned()
52    }
53}
54
55fn severity_to_sarif_level(s: Severity) -> &'static str {
56    severity::sarif_level(s)
57}
58
59fn configured_sarif_level(s: Severity) -> &'static str {
60    match s {
61        Severity::Error | Severity::Warn => severity_to_sarif_level(s),
62        Severity::Off => "none",
63    }
64}
65
66/// Build a single SARIF result object.
67///
68/// When `region` is `Some((line, col))`, a `region` block with 1-based
69/// `startLine` and `startColumn` is included in the physical location.
70fn sarif_result(
71    rule_id: &str,
72    level: &str,
73    message: &str,
74    uri: &str,
75    region: Option<(u32, u32)>,
76) -> serde_json::Value {
77    sarif_result_with_snippet(rule_id, level, message, uri, region, None)
78}
79
80fn sarif_result_with_snippet(
81    rule_id: &str,
82    level: &str,
83    message: &str,
84    uri: &str,
85    region: Option<(u32, u32)>,
86    snippet: Option<&str>,
87) -> serde_json::Value {
88    let mut physical_location = serde_json::json!({
89        "artifactLocation": { "uri": uri }
90    });
91    if let Some((line, col)) = region {
92        physical_location["region"] = serde_json::json!({
93            "startLine": line,
94            "startColumn": col
95        });
96    }
97    let line = region.map_or_else(String::new, |(line, _)| line.to_string());
98    let col = region.map_or_else(String::new, |(_, col)| col.to_string());
99    let normalized_snippet = snippet
100        .map(fingerprint::normalize_snippet)
101        .filter(|snippet| !snippet.is_empty());
102    let partial_fingerprint = normalized_snippet.as_ref().map_or_else(
103        || fingerprint::fingerprint_hash(&[rule_id, uri, &line, &col]),
104        |snippet| fingerprint::finding_fingerprint(rule_id, uri, snippet),
105    );
106    let partial_fingerprint_ghas = partial_fingerprint.clone();
107    serde_json::json!({
108        "ruleId": rule_id,
109        "level": level,
110        "message": { "text": message },
111        "locations": [{ "physicalLocation": physical_location }],
112        "partialFingerprints": {
113            fingerprint::FINGERPRINT_KEY: partial_fingerprint,
114            fingerprint::GHAS_FINGERPRINT_KEY: partial_fingerprint_ghas
115        }
116    })
117}
118
119/// Append SARIF results for a slice of items using a closure to extract fields.
120fn push_sarif_results<T>(
121    sarif_results: &mut Vec<serde_json::Value>,
122    items: &[T],
123    snippets: &mut SourceSnippetCache,
124    mut extract: impl FnMut(&T) -> SarifFields,
125) {
126    for item in items {
127        let fields = extract(item);
128        let source_snippet = fields
129            .source_path
130            .as_deref()
131            .zip(fields.region)
132            .and_then(|(path, (line, _))| snippets.line(path, line));
133        let mut result = sarif_result_with_snippet(
134            fields.rule_id,
135            fields.level,
136            &fields.message,
137            &fields.uri,
138            fields.region,
139            source_snippet.as_deref(),
140        );
141        if let Some(props) = fields.properties {
142            result["properties"] = props;
143        }
144        sarif_results.push(result);
145    }
146}
147
148/// Build a SARIF rule definition with optional `fullDescription` and `helpUri`
149/// sourced from the centralized explain module.
150fn sarif_rule(id: &str, fallback_short: &str, level: &str) -> serde_json::Value {
151    explain::rule_by_id(id).map_or_else(
152        || {
153            serde_json::json!({
154                "id": id,
155                "shortDescription": { "text": fallback_short },
156                "defaultConfiguration": { "level": level }
157            })
158        },
159        |def| {
160            serde_json::json!({
161                "id": id,
162                "shortDescription": { "text": def.short },
163                "fullDescription": { "text": def.full },
164                "helpUri": explain::rule_docs_url(def),
165                "defaultConfiguration": { "level": level }
166            })
167        },
168    )
169}
170
171/// Extract SARIF fields for an unused export or type export.
172fn sarif_export_fields(
173    export: &UnusedExport,
174    root: &Path,
175    rule_id: &'static str,
176    level: &'static str,
177    kind: &str,
178    re_kind: &str,
179) -> SarifFields {
180    let label = if export.is_re_export { re_kind } else { kind };
181    SarifFields {
182        rule_id,
183        level,
184        message: format!(
185            "{} '{}' is never imported by other modules",
186            label, export.export_name
187        ),
188        uri: relative_uri(&export.path, root),
189        region: Some((export.line, export.col + 1)),
190        source_path: Some(export.path.clone()),
191        properties: if export.is_re_export {
192            Some(serde_json::json!({ "is_re_export": true }))
193        } else {
194            None
195        },
196    }
197}
198
199fn sarif_private_type_leak_fields(
200    leak: &PrivateTypeLeak,
201    root: &Path,
202    level: &'static str,
203) -> SarifFields {
204    SarifFields {
205        rule_id: "fallow/private-type-leak",
206        level,
207        message: format!(
208            "Export '{}' references private type '{}'",
209            leak.export_name, leak.type_name
210        ),
211        uri: relative_uri(&leak.path, root),
212        region: Some((leak.line, leak.col + 1)),
213        source_path: Some(leak.path.clone()),
214        properties: None,
215    }
216}
217
218/// Extract SARIF fields for an unused dependency.
219fn sarif_dep_fields(
220    dep: &UnusedDependency,
221    root: &Path,
222    rule_id: &'static str,
223    level: &'static str,
224    section: &str,
225) -> SarifFields {
226    let workspace_context = if dep.used_in_workspaces.is_empty() {
227        String::new()
228    } else {
229        let workspaces = dep
230            .used_in_workspaces
231            .iter()
232            .map(|path| relative_uri(path, root))
233            .collect::<Vec<_>>()
234            .join(", ");
235        format!("; imported in other workspaces: {workspaces}")
236    };
237    SarifFields {
238        rule_id,
239        level,
240        message: format!(
241            "Package '{}' is in {} but never imported{}",
242            dep.package_name, section, workspace_context
243        ),
244        uri: relative_uri(&dep.path, root),
245        region: if dep.line > 0 {
246            Some((dep.line, 1))
247        } else {
248            None
249        },
250        source_path: (dep.line > 0).then(|| dep.path.clone()),
251        properties: None,
252    }
253}
254
255/// Extract SARIF fields for an unused enum or class member.
256fn sarif_member_fields(
257    member: &UnusedMember,
258    root: &Path,
259    rule_id: &'static str,
260    level: &'static str,
261    kind: &str,
262) -> SarifFields {
263    SarifFields {
264        rule_id,
265        level,
266        message: format!(
267            "{} member '{}.{}' is never referenced",
268            kind, member.parent_name, member.member_name
269        ),
270        uri: relative_uri(&member.path, root),
271        region: Some((member.line, member.col + 1)),
272        source_path: Some(member.path.clone()),
273        properties: None,
274    }
275}
276
277fn sarif_unused_file_fields(file: &UnusedFile, root: &Path, level: &'static str) -> SarifFields {
278    SarifFields {
279        rule_id: "fallow/unused-file",
280        level,
281        message: "File is not reachable from any entry point".to_string(),
282        uri: relative_uri(&file.path, root),
283        region: None,
284        source_path: None,
285        properties: None,
286    }
287}
288
289fn sarif_type_only_dep_fields(
290    dep: &TypeOnlyDependency,
291    root: &Path,
292    level: &'static str,
293) -> SarifFields {
294    SarifFields {
295        rule_id: "fallow/type-only-dependency",
296        level,
297        message: format!(
298            "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
299            dep.package_name
300        ),
301        uri: relative_uri(&dep.path, root),
302        region: if dep.line > 0 {
303            Some((dep.line, 1))
304        } else {
305            None
306        },
307        source_path: (dep.line > 0).then(|| dep.path.clone()),
308        properties: None,
309    }
310}
311
312fn sarif_test_only_dep_fields(
313    dep: &TestOnlyDependency,
314    root: &Path,
315    level: &'static str,
316) -> SarifFields {
317    SarifFields {
318        rule_id: "fallow/test-only-dependency",
319        level,
320        message: format!(
321            "Package '{}' is only imported by test files (consider moving to devDependencies)",
322            dep.package_name
323        ),
324        uri: relative_uri(&dep.path, root),
325        region: if dep.line > 0 {
326            Some((dep.line, 1))
327        } else {
328            None
329        },
330        source_path: (dep.line > 0).then(|| dep.path.clone()),
331        properties: None,
332    }
333}
334
335fn sarif_unresolved_import_fields(
336    import: &UnresolvedImport,
337    root: &Path,
338    level: &'static str,
339) -> SarifFields {
340    SarifFields {
341        rule_id: "fallow/unresolved-import",
342        level,
343        message: format!("Import '{}' could not be resolved", import.specifier),
344        uri: relative_uri(&import.path, root),
345        region: Some((import.line, import.col + 1)),
346        source_path: Some(import.path.clone()),
347        properties: None,
348    }
349}
350
351fn sarif_circular_dep_fields(
352    cycle: &CircularDependency,
353    root: &Path,
354    level: &'static str,
355) -> SarifFields {
356    let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
357    let mut display_chain = chain.clone();
358    if let Some(first) = chain.first() {
359        display_chain.push(first.clone());
360    }
361    let first_uri = chain.first().map_or_else(String::new, Clone::clone);
362    let first_path = cycle.files.first().cloned();
363    SarifFields {
364        rule_id: "fallow/circular-dependency",
365        level,
366        message: format!(
367            "Circular dependency{}: {}",
368            if cycle.is_cross_package {
369                " (cross-package)"
370            } else {
371                ""
372            },
373            display_chain.join(" \u{2192} ")
374        ),
375        uri: first_uri,
376        region: if cycle.line > 0 {
377            Some((cycle.line, cycle.col + 1))
378        } else {
379            None
380        },
381        source_path: (cycle.line > 0).then_some(first_path).flatten(),
382        properties: None,
383    }
384}
385
386fn sarif_re_export_cycle_fields(
387    cycle: &fallow_core::results::ReExportCycle,
388    root: &Path,
389    level: &'static str,
390) -> SarifFields {
391    let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
392    let first_uri = chain.first().map_or_else(String::new, Clone::clone);
393    let first_path = cycle.files.first().cloned();
394    let kind_tag = match cycle.kind {
395        fallow_core::results::ReExportCycleKind::SelfLoop => " (self-loop)",
396        fallow_core::results::ReExportCycleKind::MultiNode => "",
397    };
398    SarifFields {
399        rule_id: "fallow/re-export-cycle",
400        level,
401        message: format!("Re-export cycle{}: {}", kind_tag, chain.join(" <-> ")),
402        uri: first_uri,
403        region: None,
404        source_path: first_path,
405        properties: None,
406    }
407}
408
409fn sarif_boundary_violation_fields(
410    violation: &BoundaryViolation,
411    root: &Path,
412    level: &'static str,
413) -> SarifFields {
414    let from_uri = relative_uri(&violation.from_path, root);
415    let to_uri = relative_uri(&violation.to_path, root);
416    SarifFields {
417        rule_id: "fallow/boundary-violation",
418        level,
419        message: format!(
420            "Import from zone '{}' to zone '{}' is not allowed ({})",
421            violation.from_zone, violation.to_zone, to_uri,
422        ),
423        uri: from_uri,
424        region: if violation.line > 0 {
425            Some((violation.line, violation.col + 1))
426        } else {
427            None
428        },
429        source_path: (violation.line > 0).then(|| violation.from_path.clone()),
430        properties: None,
431    }
432}
433
434fn sarif_stale_suppression_fields(
435    suppression: &StaleSuppression,
436    root: &Path,
437    level: &'static str,
438) -> SarifFields {
439    SarifFields {
440        rule_id: "fallow/stale-suppression",
441        level,
442        message: suppression.display_message(),
443        uri: relative_uri(&suppression.path, root),
444        region: Some((suppression.line, suppression.col + 1)),
445        source_path: Some(suppression.path.clone()),
446        properties: None,
447    }
448}
449
450fn sarif_unused_catalog_entry_fields(
451    entry: &UnusedCatalogEntryFinding,
452    root: &Path,
453    level: &'static str,
454) -> SarifFields {
455    let entry = &entry.entry;
456    let message = if entry.catalog_name == "default" {
457        format!(
458            "Catalog entry '{}' is not referenced by any workspace package",
459            entry.entry_name
460        )
461    } else {
462        format!(
463            "Catalog entry '{}' (catalog '{}') is not referenced by any workspace package",
464            entry.entry_name, entry.catalog_name
465        )
466    };
467    SarifFields {
468        rule_id: "fallow/unused-catalog-entry",
469        level,
470        message,
471        uri: relative_uri(&entry.path, root),
472        region: Some((entry.line, 1)),
473        source_path: Some(entry.path.clone()),
474        properties: None,
475    }
476}
477
478fn sarif_unused_dependency_override_fields(
479    finding: &UnusedDependencyOverrideFinding,
480    root: &Path,
481    level: &'static str,
482) -> SarifFields {
483    let finding = &finding.entry;
484    let mut message = format!(
485        "Override `{}` forces version `{}` but `{}` is not declared by any workspace package or resolved in pnpm-lock.yaml",
486        finding.raw_key, finding.version_range, finding.target_package,
487    );
488    if let Some(hint) = &finding.hint {
489        use std::fmt::Write as _;
490        let _ = write!(message, " ({hint})");
491    }
492    SarifFields {
493        rule_id: "fallow/unused-dependency-override",
494        level,
495        message,
496        uri: relative_uri(&finding.path, root),
497        region: Some((finding.line, 1)),
498        source_path: Some(finding.path.clone()),
499        properties: None,
500    }
501}
502
503fn sarif_misconfigured_dependency_override_fields(
504    finding: &MisconfiguredDependencyOverrideFinding,
505    root: &Path,
506    level: &'static str,
507) -> SarifFields {
508    let finding = &finding.entry;
509    let message = format!(
510        "Override `{}` -> `{}` is malformed: {}",
511        finding.raw_key,
512        finding.raw_value,
513        finding.reason.describe(),
514    );
515    SarifFields {
516        rule_id: "fallow/misconfigured-dependency-override",
517        level,
518        message,
519        uri: relative_uri(&finding.path, root),
520        region: Some((finding.line, 1)),
521        source_path: Some(finding.path.clone()),
522        properties: None,
523    }
524}
525
526fn sarif_unresolved_catalog_reference_fields(
527    finding: &UnresolvedCatalogReferenceFinding,
528    root: &Path,
529    level: &'static str,
530) -> SarifFields {
531    let finding = &finding.reference;
532    let catalog_phrase = if finding.catalog_name == "default" {
533        "the default catalog".to_string()
534    } else {
535        format!("catalog '{}'", finding.catalog_name)
536    };
537    let mut message = format!(
538        "Package '{}' is referenced via `catalog:{}` but {} does not declare it",
539        finding.entry_name,
540        if finding.catalog_name == "default" {
541            ""
542        } else {
543            finding.catalog_name.as_str()
544        },
545        catalog_phrase,
546    );
547    if !finding.available_in_catalogs.is_empty() {
548        use std::fmt::Write as _;
549        let _ = write!(
550            message,
551            " (available in: {})",
552            finding.available_in_catalogs.join(", ")
553        );
554    }
555    SarifFields {
556        rule_id: "fallow/unresolved-catalog-reference",
557        level,
558        message,
559        uri: relative_uri(&finding.path, root),
560        region: Some((finding.line, 1)),
561        source_path: Some(finding.path.clone()),
562        properties: None,
563    }
564}
565
566fn sarif_empty_catalog_group_fields(
567    group: &EmptyCatalogGroupFinding,
568    root: &Path,
569    level: &'static str,
570) -> SarifFields {
571    let group = &group.group;
572    SarifFields {
573        rule_id: "fallow/empty-catalog-group",
574        level,
575        message: format!("Catalog group '{}' has no entries", group.catalog_name),
576        uri: relative_uri(&group.path, root),
577        region: Some((group.line, 1)),
578        source_path: Some(group.path.clone()),
579        properties: None,
580    }
581}
582
583/// Unlisted deps fan out to one SARIF result per import site, so they do not
584/// fit `push_sarif_results`. Keep the nested-loop shape in its own helper.
585fn push_sarif_unlisted_deps(
586    sarif_results: &mut Vec<serde_json::Value>,
587    deps: &[UnlistedDependencyFinding],
588    root: &Path,
589    level: &'static str,
590    snippets: &mut SourceSnippetCache,
591) {
592    for entry in deps {
593        let dep = &entry.dep;
594        for site in &dep.imported_from {
595            let uri = relative_uri(&site.path, root);
596            let source_snippet = snippets.line(&site.path, site.line);
597            sarif_results.push(sarif_result_with_snippet(
598                "fallow/unlisted-dependency",
599                level,
600                &format!(
601                    "Package '{}' is imported but not listed in package.json",
602                    dep.package_name
603                ),
604                &uri,
605                Some((site.line, site.col + 1)),
606                source_snippet.as_deref(),
607            ));
608        }
609    }
610}
611
612/// Duplicate exports fan out to one SARIF result per location
613/// (SARIF 2.1.0 section 3.27.12), so they do not fit `push_sarif_results`.
614fn push_sarif_duplicate_exports(
615    sarif_results: &mut Vec<serde_json::Value>,
616    dups: &[DuplicateExportFinding],
617    root: &Path,
618    level: &'static str,
619    snippets: &mut SourceSnippetCache,
620) {
621    for dup in dups {
622        let dup = &dup.export;
623        for loc in &dup.locations {
624            let uri = relative_uri(&loc.path, root);
625            let source_snippet = snippets.line(&loc.path, loc.line);
626            sarif_results.push(sarif_result_with_snippet(
627                "fallow/duplicate-export",
628                level,
629                &format!("Export '{}' appears in multiple modules", dup.export_name),
630                &uri,
631                Some((loc.line, loc.col + 1)),
632                source_snippet.as_deref(),
633            ));
634        }
635    }
636}
637
638/// Build the SARIF rules list from the current rules configuration.
639fn build_sarif_rules(rules: &RulesConfig) -> Vec<serde_json::Value> {
640    [
641        (
642            "fallow/unused-file",
643            "File is not reachable from any entry point",
644            rules.unused_files,
645        ),
646        (
647            "fallow/unused-export",
648            "Export is never imported",
649            rules.unused_exports,
650        ),
651        (
652            "fallow/unused-type",
653            "Type export is never imported",
654            rules.unused_types,
655        ),
656        (
657            "fallow/private-type-leak",
658            "Exported signature references a same-file private type",
659            rules.private_type_leaks,
660        ),
661        (
662            "fallow/unused-dependency",
663            "Dependency listed but never imported",
664            rules.unused_dependencies,
665        ),
666        (
667            "fallow/unused-dev-dependency",
668            "Dev dependency listed but never imported",
669            rules.unused_dev_dependencies,
670        ),
671        (
672            "fallow/unused-optional-dependency",
673            "Optional dependency listed but never imported",
674            rules.unused_optional_dependencies,
675        ),
676        (
677            "fallow/type-only-dependency",
678            "Production dependency only used via type-only imports",
679            rules.type_only_dependencies,
680        ),
681        (
682            "fallow/test-only-dependency",
683            "Production dependency only imported by test files",
684            rules.test_only_dependencies,
685        ),
686        (
687            "fallow/unused-enum-member",
688            "Enum member is never referenced",
689            rules.unused_enum_members,
690        ),
691        (
692            "fallow/unused-class-member",
693            "Class member is never referenced",
694            rules.unused_class_members,
695        ),
696        (
697            "fallow/unresolved-import",
698            "Import could not be resolved",
699            rules.unresolved_imports,
700        ),
701        (
702            "fallow/unlisted-dependency",
703            "Dependency used but not in package.json",
704            rules.unlisted_dependencies,
705        ),
706        (
707            "fallow/duplicate-export",
708            "Export name appears in multiple modules",
709            rules.duplicate_exports,
710        ),
711        (
712            "fallow/circular-dependency",
713            "Circular dependency chain detected",
714            rules.circular_dependencies,
715        ),
716        (
717            "fallow/re-export-cycle",
718            "Two or more barrel files re-export from each other in a loop",
719            rules.re_export_cycle,
720        ),
721        (
722            "fallow/boundary-violation",
723            "Import crosses an architecture boundary",
724            rules.boundary_violation,
725        ),
726        (
727            "fallow/stale-suppression",
728            "Suppression comment or tag no longer matches any issue",
729            rules.stale_suppressions,
730        ),
731        (
732            "fallow/unused-catalog-entry",
733            "pnpm catalog entry not referenced by any workspace package",
734            rules.unused_catalog_entries,
735        ),
736        (
737            "fallow/empty-catalog-group",
738            "pnpm named catalog group has no entries",
739            rules.empty_catalog_groups,
740        ),
741        (
742            "fallow/unresolved-catalog-reference",
743            "package.json catalog reference points at a catalog that does not declare the package",
744            rules.unresolved_catalog_references,
745        ),
746        (
747            "fallow/unused-dependency-override",
748            "pnpm dependency override target is not declared or lockfile-resolved",
749            rules.unused_dependency_overrides,
750        ),
751        (
752            "fallow/misconfigured-dependency-override",
753            "pnpm dependency override key or value is malformed",
754            rules.misconfigured_dependency_overrides,
755        ),
756    ]
757    .into_iter()
758    .map(|(id, description, rule_severity)| {
759        sarif_rule(id, description, configured_sarif_level(rule_severity))
760    })
761    .collect()
762}
763
764#[must_use]
765#[expect(
766    clippy::too_many_lines,
767    reason = "SARIF builds one flat result list across every analysis family"
768)]
769pub fn build_sarif(
770    results: &AnalysisResults,
771    root: &Path,
772    rules: &RulesConfig,
773) -> serde_json::Value {
774    let mut sarif_results = Vec::new();
775    let mut snippets = SourceSnippetCache::default();
776
777    push_sarif_results(
778        &mut sarif_results,
779        &results.unused_files,
780        &mut snippets,
781        |f| sarif_unused_file_fields(&f.file, root, severity_to_sarif_level(rules.unused_files)),
782    );
783    push_sarif_results(
784        &mut sarif_results,
785        &results.unused_exports,
786        &mut snippets,
787        |e| {
788            sarif_export_fields(
789                &e.export,
790                root,
791                "fallow/unused-export",
792                severity_to_sarif_level(rules.unused_exports),
793                "Export",
794                "Re-export",
795            )
796        },
797    );
798    push_sarif_results(
799        &mut sarif_results,
800        &results.unused_types,
801        &mut snippets,
802        |e| {
803            sarif_export_fields(
804                &e.export,
805                root,
806                "fallow/unused-type",
807                severity_to_sarif_level(rules.unused_types),
808                "Type export",
809                "Type re-export",
810            )
811        },
812    );
813    push_sarif_results(
814        &mut sarif_results,
815        &results.private_type_leaks,
816        &mut snippets,
817        |e| {
818            sarif_private_type_leak_fields(
819                &e.leak,
820                root,
821                severity_to_sarif_level(rules.private_type_leaks),
822            )
823        },
824    );
825    push_sarif_results(
826        &mut sarif_results,
827        &results.unused_dependencies,
828        &mut snippets,
829        |d| {
830            sarif_dep_fields(
831                &d.dep,
832                root,
833                "fallow/unused-dependency",
834                severity_to_sarif_level(rules.unused_dependencies),
835                "dependencies",
836            )
837        },
838    );
839    push_sarif_results(
840        &mut sarif_results,
841        &results.unused_dev_dependencies,
842        &mut snippets,
843        |d| {
844            sarif_dep_fields(
845                &d.dep,
846                root,
847                "fallow/unused-dev-dependency",
848                severity_to_sarif_level(rules.unused_dev_dependencies),
849                "devDependencies",
850            )
851        },
852    );
853    push_sarif_results(
854        &mut sarif_results,
855        &results.unused_optional_dependencies,
856        &mut snippets,
857        |d| {
858            sarif_dep_fields(
859                &d.dep,
860                root,
861                "fallow/unused-optional-dependency",
862                severity_to_sarif_level(rules.unused_optional_dependencies),
863                "optionalDependencies",
864            )
865        },
866    );
867    push_sarif_results(
868        &mut sarif_results,
869        &results.type_only_dependencies,
870        &mut snippets,
871        |d| {
872            sarif_type_only_dep_fields(
873                &d.dep,
874                root,
875                severity_to_sarif_level(rules.type_only_dependencies),
876            )
877        },
878    );
879    push_sarif_results(
880        &mut sarif_results,
881        &results.test_only_dependencies,
882        &mut snippets,
883        |d| {
884            sarif_test_only_dep_fields(
885                &d.dep,
886                root,
887                severity_to_sarif_level(rules.test_only_dependencies),
888            )
889        },
890    );
891    push_sarif_results(
892        &mut sarif_results,
893        &results.unused_enum_members,
894        &mut snippets,
895        |m| {
896            sarif_member_fields(
897                &m.member,
898                root,
899                "fallow/unused-enum-member",
900                severity_to_sarif_level(rules.unused_enum_members),
901                "Enum",
902            )
903        },
904    );
905    push_sarif_results(
906        &mut sarif_results,
907        &results.unused_class_members,
908        &mut snippets,
909        |m| {
910            sarif_member_fields(
911                &m.member,
912                root,
913                "fallow/unused-class-member",
914                severity_to_sarif_level(rules.unused_class_members),
915                "Class",
916            )
917        },
918    );
919    push_sarif_results(
920        &mut sarif_results,
921        &results.unresolved_imports,
922        &mut snippets,
923        |i| {
924            sarif_unresolved_import_fields(
925                &i.import,
926                root,
927                severity_to_sarif_level(rules.unresolved_imports),
928            )
929        },
930    );
931    if !results.unlisted_dependencies.is_empty() {
932        push_sarif_unlisted_deps(
933            &mut sarif_results,
934            &results.unlisted_dependencies,
935            root,
936            severity_to_sarif_level(rules.unlisted_dependencies),
937            &mut snippets,
938        );
939    }
940    if !results.duplicate_exports.is_empty() {
941        push_sarif_duplicate_exports(
942            &mut sarif_results,
943            &results.duplicate_exports,
944            root,
945            severity_to_sarif_level(rules.duplicate_exports),
946            &mut snippets,
947        );
948    }
949    push_sarif_results(
950        &mut sarif_results,
951        &results.circular_dependencies,
952        &mut snippets,
953        |c| {
954            sarif_circular_dep_fields(
955                &c.cycle,
956                root,
957                severity_to_sarif_level(rules.circular_dependencies),
958            )
959        },
960    );
961    push_sarif_results(
962        &mut sarif_results,
963        &results.re_export_cycles,
964        &mut snippets,
965        |c| {
966            sarif_re_export_cycle_fields(
967                &c.cycle,
968                root,
969                severity_to_sarif_level(rules.re_export_cycle),
970            )
971        },
972    );
973    push_sarif_results(
974        &mut sarif_results,
975        &results.boundary_violations,
976        &mut snippets,
977        |v| {
978            sarif_boundary_violation_fields(
979                &v.violation,
980                root,
981                severity_to_sarif_level(rules.boundary_violation),
982            )
983        },
984    );
985    push_sarif_results(
986        &mut sarif_results,
987        &results.stale_suppressions,
988        &mut snippets,
989        |s| {
990            sarif_stale_suppression_fields(
991                s,
992                root,
993                severity_to_sarif_level(rules.stale_suppressions),
994            )
995        },
996    );
997    push_sarif_results(
998        &mut sarif_results,
999        &results.unused_catalog_entries,
1000        &mut snippets,
1001        |e| {
1002            sarif_unused_catalog_entry_fields(
1003                e,
1004                root,
1005                severity_to_sarif_level(rules.unused_catalog_entries),
1006            )
1007        },
1008    );
1009    push_sarif_results(
1010        &mut sarif_results,
1011        &results.empty_catalog_groups,
1012        &mut snippets,
1013        |g| {
1014            sarif_empty_catalog_group_fields(
1015                g,
1016                root,
1017                severity_to_sarif_level(rules.empty_catalog_groups),
1018            )
1019        },
1020    );
1021    push_sarif_results(
1022        &mut sarif_results,
1023        &results.unresolved_catalog_references,
1024        &mut snippets,
1025        |f| {
1026            sarif_unresolved_catalog_reference_fields(
1027                f,
1028                root,
1029                severity_to_sarif_level(rules.unresolved_catalog_references),
1030            )
1031        },
1032    );
1033    push_sarif_results(
1034        &mut sarif_results,
1035        &results.unused_dependency_overrides,
1036        &mut snippets,
1037        |f| {
1038            sarif_unused_dependency_override_fields(
1039                f,
1040                root,
1041                severity_to_sarif_level(rules.unused_dependency_overrides),
1042            )
1043        },
1044    );
1045    push_sarif_results(
1046        &mut sarif_results,
1047        &results.misconfigured_dependency_overrides,
1048        &mut snippets,
1049        |f| {
1050            sarif_misconfigured_dependency_override_fields(
1051                f,
1052                root,
1053                severity_to_sarif_level(rules.misconfigured_dependency_overrides),
1054            )
1055        },
1056    );
1057
1058    serde_json::json!({
1059        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1060        "version": "2.1.0",
1061        "runs": [{
1062            "tool": {
1063                "driver": {
1064                    "name": "fallow",
1065                    "version": env!("CARGO_PKG_VERSION"),
1066                    "informationUri": "https://github.com/fallow-rs/fallow",
1067                    "rules": build_sarif_rules(rules)
1068                }
1069            },
1070            "results": sarif_results
1071        }]
1072    })
1073}
1074
1075pub(super) fn print_sarif(results: &AnalysisResults, root: &Path, rules: &RulesConfig) -> ExitCode {
1076    let sarif = build_sarif(results, root, rules);
1077    emit_json(&sarif, "SARIF")
1078}
1079
1080/// Print SARIF output with owner properties added to each result.
1081///
1082/// Calls `build_sarif` to produce the standard SARIF JSON, then post-processes
1083/// each result to add `"properties": { "owner": "@team" }` by resolving the
1084/// artifact location URI through the `OwnershipResolver`.
1085pub(super) fn print_grouped_sarif(
1086    results: &AnalysisResults,
1087    root: &Path,
1088    rules: &RulesConfig,
1089    resolver: &OwnershipResolver,
1090) -> ExitCode {
1091    let mut sarif = build_sarif(results, root, rules);
1092
1093    // Post-process each result to inject the owner property.
1094    if let Some(runs) = sarif.get_mut("runs").and_then(|r| r.as_array_mut()) {
1095        for run in runs {
1096            if let Some(results) = run.get_mut("results").and_then(|r| r.as_array_mut()) {
1097                for result in results {
1098                    let uri = result
1099                        .pointer("/locations/0/physicalLocation/artifactLocation/uri")
1100                        .and_then(|v| v.as_str())
1101                        .unwrap_or("");
1102                    // Decode percent-encoded brackets before ownership lookup
1103                    // (SARIF URIs encode `[`/`]` as `%5B`/`%5D`)
1104                    let decoded = uri.replace("%5B", "[").replace("%5D", "]");
1105                    let owner =
1106                        grouping::resolve_owner(Path::new(&decoded), Path::new(""), resolver);
1107                    let props = result
1108                        .as_object_mut()
1109                        .expect("SARIF result should be an object")
1110                        .entry("properties")
1111                        .or_insert_with(|| serde_json::json!({}));
1112                    props
1113                        .as_object_mut()
1114                        .expect("properties should be an object")
1115                        .insert("owner".to_string(), serde_json::Value::String(owner));
1116                }
1117            }
1118        }
1119    }
1120
1121    emit_json(&sarif, "SARIF")
1122}
1123
1124#[expect(
1125    clippy::cast_possible_truncation,
1126    reason = "line/col numbers are bounded by source size"
1127)]
1128pub(super) fn print_duplication_sarif(report: &DuplicationReport, root: &Path) -> ExitCode {
1129    let mut sarif_results = Vec::new();
1130    let mut snippets = SourceSnippetCache::default();
1131
1132    for (i, group) in report.clone_groups.iter().enumerate() {
1133        for instance in &group.instances {
1134            let uri = relative_uri(&instance.file, root);
1135            let source_snippet = snippets.line(&instance.file, instance.start_line as u32);
1136            sarif_results.push(sarif_result_with_snippet(
1137                "fallow/code-duplication",
1138                "warning",
1139                &format!(
1140                    "Code clone group {} ({} lines, {} instances)",
1141                    i + 1,
1142                    group.line_count,
1143                    group.instances.len()
1144                ),
1145                &uri,
1146                Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
1147                source_snippet.as_deref(),
1148            ));
1149        }
1150    }
1151
1152    let sarif = serde_json::json!({
1153        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1154        "version": "2.1.0",
1155        "runs": [{
1156            "tool": {
1157                "driver": {
1158                    "name": "fallow",
1159                    "version": env!("CARGO_PKG_VERSION"),
1160                    "informationUri": "https://github.com/fallow-rs/fallow",
1161                    "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
1162                }
1163            },
1164            "results": sarif_results
1165        }]
1166    });
1167
1168    emit_json(&sarif, "SARIF")
1169}
1170
1171/// Print SARIF duplication output with a `properties.group` tag on every
1172/// result.
1173///
1174/// Each clone group is attributed to its largest owner (most instances; ties
1175/// broken alphabetically) via [`super::dupes_grouping::largest_owner`], and
1176/// every result emitted for that group's instances carries the same
1177/// `properties.group` value. This mirrors the health SARIF convention
1178/// (`print_grouped_health_sarif`) so consumers (GitHub Code Scanning, GitLab
1179/// Code Quality) can partition findings per team / package / directory
1180/// without re-resolving ownership.
1181#[expect(
1182    clippy::cast_possible_truncation,
1183    reason = "line/col numbers are bounded by source size"
1184)]
1185pub(super) fn print_grouped_duplication_sarif(
1186    report: &DuplicationReport,
1187    root: &Path,
1188    resolver: &OwnershipResolver,
1189) -> ExitCode {
1190    let mut sarif_results = Vec::new();
1191    let mut snippets = SourceSnippetCache::default();
1192
1193    for (i, group) in report.clone_groups.iter().enumerate() {
1194        // Compute the group's primary owner once. Every result emitted for
1195        // this group carries the same `properties.group` value (the GROUP'S
1196        // owner, not the per-instance owner).
1197        let primary_owner = super::dupes_grouping::largest_owner(group, root, resolver);
1198        for instance in &group.instances {
1199            let uri = relative_uri(&instance.file, root);
1200            let source_snippet = snippets.line(&instance.file, instance.start_line as u32);
1201            let mut result = sarif_result_with_snippet(
1202                "fallow/code-duplication",
1203                "warning",
1204                &format!(
1205                    "Code clone group {} ({} lines, {} instances)",
1206                    i + 1,
1207                    group.line_count,
1208                    group.instances.len()
1209                ),
1210                &uri,
1211                Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
1212                source_snippet.as_deref(),
1213            );
1214            let props = result
1215                .as_object_mut()
1216                .expect("SARIF result should be an object")
1217                .entry("properties")
1218                .or_insert_with(|| serde_json::json!({}));
1219            props
1220                .as_object_mut()
1221                .expect("properties should be an object")
1222                .insert(
1223                    "group".to_string(),
1224                    serde_json::Value::String(primary_owner.clone()),
1225                );
1226            sarif_results.push(result);
1227        }
1228    }
1229
1230    let sarif = serde_json::json!({
1231        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1232        "version": "2.1.0",
1233        "runs": [{
1234            "tool": {
1235                "driver": {
1236                    "name": "fallow",
1237                    "version": env!("CARGO_PKG_VERSION"),
1238                    "informationUri": "https://github.com/fallow-rs/fallow",
1239                    "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
1240                }
1241            },
1242            "results": sarif_results
1243        }]
1244    });
1245
1246    emit_json(&sarif, "SARIF")
1247}
1248
1249// ── Health SARIF output ────────────────────────────────────────────
1250// Note: file_scores are intentionally omitted from SARIF output.
1251// SARIF is designed for diagnostic results (issues/findings), not metric tables.
1252// File health scores are available in JSON, human, compact, and markdown formats.
1253
1254#[must_use]
1255#[expect(
1256    clippy::too_many_lines,
1257    reason = "flat rules + results table: adding runtime-coverage rules pushed past the 150 line threshold but each section is a straightforward sequence of sarif_rule / sarif_result calls"
1258)]
1259pub fn build_health_sarif(
1260    report: &crate::health_types::HealthReport,
1261    root: &Path,
1262) -> serde_json::Value {
1263    use crate::health_types::ExceededThreshold;
1264
1265    let mut sarif_results = Vec::new();
1266    let mut snippets = SourceSnippetCache::default();
1267
1268    for finding in &report.findings {
1269        let uri = relative_uri(&finding.path, root);
1270        // When CRAP contributes alongside complexity, use the CRAP rule as the
1271        // most actionable identifier (CRAP combines complexity and coverage)
1272        // and surface all exceeded dimensions in the message.
1273        let (rule_id, message) = match finding.exceeded {
1274            ExceededThreshold::Cyclomatic => (
1275                "fallow/high-cyclomatic-complexity",
1276                format!(
1277                    "'{}' has cyclomatic complexity {} (threshold: {})",
1278                    finding.name, finding.cyclomatic, report.summary.max_cyclomatic_threshold,
1279                ),
1280            ),
1281            ExceededThreshold::Cognitive => (
1282                "fallow/high-cognitive-complexity",
1283                format!(
1284                    "'{}' has cognitive complexity {} (threshold: {})",
1285                    finding.name, finding.cognitive, report.summary.max_cognitive_threshold,
1286                ),
1287            ),
1288            ExceededThreshold::Both => (
1289                "fallow/high-complexity",
1290                format!(
1291                    "'{}' has cyclomatic complexity {} (threshold: {}) and cognitive complexity {} (threshold: {})",
1292                    finding.name,
1293                    finding.cyclomatic,
1294                    report.summary.max_cyclomatic_threshold,
1295                    finding.cognitive,
1296                    report.summary.max_cognitive_threshold,
1297                ),
1298            ),
1299            ExceededThreshold::Crap
1300            | ExceededThreshold::CyclomaticCrap
1301            | ExceededThreshold::CognitiveCrap
1302            | ExceededThreshold::All => {
1303                let crap = finding.crap.unwrap_or(0.0);
1304                let coverage = finding
1305                    .coverage_pct
1306                    .map(|pct| format!(", coverage {pct:.0}%"))
1307                    .unwrap_or_default();
1308                (
1309                    "fallow/high-crap-score",
1310                    format!(
1311                        "'{}' has CRAP score {:.1} (threshold: {:.1}, cyclomatic {}{})",
1312                        finding.name,
1313                        crap,
1314                        report.summary.max_crap_threshold,
1315                        finding.cyclomatic,
1316                        coverage,
1317                    ),
1318                )
1319            }
1320        };
1321
1322        let level = match finding.severity {
1323            crate::health_types::FindingSeverity::Critical => "error",
1324            crate::health_types::FindingSeverity::High => "warning",
1325            crate::health_types::FindingSeverity::Moderate => "note",
1326        };
1327        let source_snippet = snippets.line(&finding.path, finding.line);
1328        sarif_results.push(sarif_result_with_snippet(
1329            rule_id,
1330            level,
1331            &message,
1332            &uri,
1333            Some((finding.line, finding.col + 1)),
1334            source_snippet.as_deref(),
1335        ));
1336    }
1337
1338    if let Some(ref production) = report.runtime_coverage {
1339        append_runtime_coverage_sarif_results(&mut sarif_results, production, root, &mut snippets);
1340    }
1341
1342    // Refactoring targets as SARIF results (warning level — advisory recommendations)
1343    for target in &report.targets {
1344        let uri = relative_uri(&target.path, root);
1345        let message = format!(
1346            "[{}] {} (priority: {:.1}, efficiency: {:.1}, effort: {}, confidence: {})",
1347            target.category.label(),
1348            target.recommendation,
1349            target.priority,
1350            target.efficiency,
1351            target.effort.label(),
1352            target.confidence.label(),
1353        );
1354        sarif_results.push(sarif_result(
1355            "fallow/refactoring-target",
1356            "warning",
1357            &message,
1358            &uri,
1359            None,
1360        ));
1361    }
1362
1363    if let Some(ref gaps) = report.coverage_gaps {
1364        for item in &gaps.files {
1365            let uri = relative_uri(&item.file.path, root);
1366            let message = format!(
1367                "File is runtime-reachable but has no test dependency path ({} value export{})",
1368                item.file.value_export_count,
1369                if item.file.value_export_count == 1 {
1370                    ""
1371                } else {
1372                    "s"
1373                },
1374            );
1375            sarif_results.push(sarif_result(
1376                "fallow/untested-file",
1377                "warning",
1378                &message,
1379                &uri,
1380                None,
1381            ));
1382        }
1383
1384        for item in &gaps.exports {
1385            let uri = relative_uri(&item.export.path, root);
1386            let message = format!(
1387                "Export '{}' is runtime-reachable but never referenced by test-reachable modules",
1388                item.export.export_name
1389            );
1390            let source_snippet = snippets.line(&item.export.path, item.export.line);
1391            sarif_results.push(sarif_result_with_snippet(
1392                "fallow/untested-export",
1393                "warning",
1394                &message,
1395                &uri,
1396                Some((item.export.line, item.export.col + 1)),
1397                source_snippet.as_deref(),
1398            ));
1399        }
1400    }
1401
1402    let health_rules = vec![
1403        sarif_rule(
1404            "fallow/high-cyclomatic-complexity",
1405            "Function has high cyclomatic complexity",
1406            "note",
1407        ),
1408        sarif_rule(
1409            "fallow/high-cognitive-complexity",
1410            "Function has high cognitive complexity",
1411            "note",
1412        ),
1413        sarif_rule(
1414            "fallow/high-complexity",
1415            "Function exceeds both complexity thresholds",
1416            "note",
1417        ),
1418        sarif_rule(
1419            "fallow/high-crap-score",
1420            "Function has a high CRAP score (high complexity combined with low coverage)",
1421            "warning",
1422        ),
1423        sarif_rule(
1424            "fallow/refactoring-target",
1425            "File identified as a high-priority refactoring candidate",
1426            "warning",
1427        ),
1428        sarif_rule(
1429            "fallow/untested-file",
1430            "Runtime-reachable file has no test dependency path",
1431            "warning",
1432        ),
1433        sarif_rule(
1434            "fallow/untested-export",
1435            "Runtime-reachable export has no test dependency path",
1436            "warning",
1437        ),
1438        sarif_rule(
1439            "fallow/runtime-safe-to-delete",
1440            "Function is statically unused and was never invoked in production",
1441            "warning",
1442        ),
1443        sarif_rule(
1444            "fallow/runtime-review-required",
1445            "Function is statically used but was never invoked in production",
1446            "warning",
1447        ),
1448        sarif_rule(
1449            "fallow/runtime-low-traffic",
1450            "Function was invoked below the low-traffic threshold relative to total trace count",
1451            "note",
1452        ),
1453        sarif_rule(
1454            "fallow/runtime-coverage-unavailable",
1455            "Runtime coverage could not be resolved for this function",
1456            "note",
1457        ),
1458        sarif_rule(
1459            "fallow/runtime-coverage",
1460            "Runtime coverage finding",
1461            "note",
1462        ),
1463    ];
1464
1465    serde_json::json!({
1466        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1467        "version": "2.1.0",
1468        "runs": [{
1469            "tool": {
1470                "driver": {
1471                    "name": "fallow",
1472                    "version": env!("CARGO_PKG_VERSION"),
1473                    "informationUri": "https://github.com/fallow-rs/fallow",
1474                    "rules": health_rules
1475                }
1476            },
1477            "results": sarif_results
1478        }]
1479    })
1480}
1481
1482// Note: `production.hot_paths`, `production.signals`, and per-hot-path
1483// `end_line` are intentionally omitted from SARIF output. SARIF is
1484// designed for diagnostic results (issues a reviewer should act on),
1485// not for state observations. `hot-path-touched` is informational
1486// (PR-context heads-up that a touched function is on the hot path),
1487// not a finding to fix; surfacing it as a SARIF result would clutter
1488// Code Scanning's UI with non-actionable entries. JSON consumers that
1489// want the full picture read `runtime_coverage.signals[]` and
1490// `runtime_coverage.hot_paths[]` directly.
1491fn append_runtime_coverage_sarif_results(
1492    sarif_results: &mut Vec<serde_json::Value>,
1493    production: &crate::health_types::RuntimeCoverageReport,
1494    root: &Path,
1495    snippets: &mut SourceSnippetCache,
1496) {
1497    for finding in &production.findings {
1498        let uri = relative_uri(&finding.path, root);
1499        let rule_id = match finding.verdict {
1500            crate::health_types::RuntimeCoverageVerdict::SafeToDelete => {
1501                "fallow/runtime-safe-to-delete"
1502            }
1503            crate::health_types::RuntimeCoverageVerdict::ReviewRequired => {
1504                "fallow/runtime-review-required"
1505            }
1506            crate::health_types::RuntimeCoverageVerdict::LowTraffic => "fallow/runtime-low-traffic",
1507            crate::health_types::RuntimeCoverageVerdict::CoverageUnavailable => {
1508                "fallow/runtime-coverage-unavailable"
1509            }
1510            crate::health_types::RuntimeCoverageVerdict::Active
1511            | crate::health_types::RuntimeCoverageVerdict::Unknown => "fallow/runtime-coverage",
1512        };
1513        let level = match finding.verdict {
1514            crate::health_types::RuntimeCoverageVerdict::SafeToDelete
1515            | crate::health_types::RuntimeCoverageVerdict::ReviewRequired => "warning",
1516            _ => "note",
1517        };
1518        let invocations_hint = finding.invocations.map_or_else(
1519            || "untracked".to_owned(),
1520            |hits| format!("{hits} invocations"),
1521        );
1522        let message = format!(
1523            "'{}' runtime coverage verdict: {} ({})",
1524            finding.function,
1525            finding.verdict.human_label(),
1526            invocations_hint,
1527        );
1528        let source_snippet = snippets.line(&finding.path, finding.line);
1529        sarif_results.push(sarif_result_with_snippet(
1530            rule_id,
1531            level,
1532            &message,
1533            &uri,
1534            Some((finding.line, 1)),
1535            source_snippet.as_deref(),
1536        ));
1537    }
1538}
1539
1540pub(super) fn print_health_sarif(
1541    report: &crate::health_types::HealthReport,
1542    root: &Path,
1543) -> ExitCode {
1544    let sarif = build_health_sarif(report, root);
1545    emit_json(&sarif, "SARIF")
1546}
1547
1548/// Print health SARIF with a per-result `properties.group` tag.
1549///
1550/// Mirrors the dead-code grouped SARIF pattern (`print_grouped_sarif`):
1551/// build the standard SARIF first, then post-process each result to inject
1552/// the resolver-derived group key on `properties.group`. Consumers that read
1553/// SARIF (GitHub Code Scanning, GitLab Code Quality) can then partition
1554/// findings per team / package / directory without dropping out of the
1555/// SARIF pipeline. Each finding's URI is decoded (`%5B` -> `[`, `%5D` -> `]`)
1556/// before resolution, matching the dead-code behaviour for paths containing
1557/// brackets like Next.js dynamic routes.
1558pub(super) fn print_grouped_health_sarif(
1559    report: &crate::health_types::HealthReport,
1560    root: &Path,
1561    resolver: &OwnershipResolver,
1562) -> ExitCode {
1563    let mut sarif = build_health_sarif(report, root);
1564
1565    if let Some(runs) = sarif.get_mut("runs").and_then(|r| r.as_array_mut()) {
1566        for run in runs {
1567            if let Some(results) = run.get_mut("results").and_then(|r| r.as_array_mut()) {
1568                for result in results {
1569                    let uri = result
1570                        .pointer("/locations/0/physicalLocation/artifactLocation/uri")
1571                        .and_then(|v| v.as_str())
1572                        .unwrap_or("");
1573                    let decoded = uri.replace("%5B", "[").replace("%5D", "]");
1574                    let group =
1575                        grouping::resolve_owner(Path::new(&decoded), Path::new(""), resolver);
1576                    let props = result
1577                        .as_object_mut()
1578                        .expect("SARIF result should be an object")
1579                        .entry("properties")
1580                        .or_insert_with(|| serde_json::json!({}));
1581                    props
1582                        .as_object_mut()
1583                        .expect("properties should be an object")
1584                        .insert("group".to_string(), serde_json::Value::String(group));
1585                }
1586            }
1587        }
1588    }
1589
1590    emit_json(&sarif, "SARIF")
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595    use super::*;
1596    use crate::report::test_helpers::sample_results;
1597    use fallow_core::results::*;
1598    use std::path::PathBuf;
1599
1600    #[test]
1601    fn sarif_has_required_top_level_fields() {
1602        let root = PathBuf::from("/project");
1603        let results = AnalysisResults::default();
1604        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1605
1606        assert_eq!(
1607            sarif["$schema"],
1608            "https://json.schemastore.org/sarif-2.1.0.json"
1609        );
1610        assert_eq!(sarif["version"], "2.1.0");
1611        assert!(sarif["runs"].is_array());
1612    }
1613
1614    #[test]
1615    fn sarif_has_tool_driver_info() {
1616        let root = PathBuf::from("/project");
1617        let results = AnalysisResults::default();
1618        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1619
1620        let driver = &sarif["runs"][0]["tool"]["driver"];
1621        assert_eq!(driver["name"], "fallow");
1622        assert!(driver["version"].is_string());
1623        assert_eq!(
1624            driver["informationUri"],
1625            "https://github.com/fallow-rs/fallow"
1626        );
1627    }
1628
1629    #[test]
1630    fn sarif_declares_all_rules() {
1631        let root = PathBuf::from("/project");
1632        let results = AnalysisResults::default();
1633        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1634
1635        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1636            .as_array()
1637            .expect("rules should be an array");
1638        assert_eq!(rules.len(), 23);
1639
1640        let rule_ids: Vec<&str> = rules.iter().map(|r| r["id"].as_str().unwrap()).collect();
1641        assert!(rule_ids.contains(&"fallow/unused-file"));
1642        assert!(rule_ids.contains(&"fallow/unused-export"));
1643        assert!(rule_ids.contains(&"fallow/unused-type"));
1644        assert!(rule_ids.contains(&"fallow/private-type-leak"));
1645        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1646        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1647        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1648        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1649        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1650        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1651        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1652        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1653        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1654        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1655        assert!(rule_ids.contains(&"fallow/circular-dependency"));
1656        assert!(rule_ids.contains(&"fallow/re-export-cycle"));
1657        assert!(rule_ids.contains(&"fallow/boundary-violation"));
1658        assert!(rule_ids.contains(&"fallow/unused-catalog-entry"));
1659        assert!(rule_ids.contains(&"fallow/empty-catalog-group"));
1660        assert!(rule_ids.contains(&"fallow/unresolved-catalog-reference"));
1661        assert!(rule_ids.contains(&"fallow/unused-dependency-override"));
1662        assert!(rule_ids.contains(&"fallow/misconfigured-dependency-override"));
1663    }
1664
1665    #[test]
1666    fn sarif_empty_results_no_results_entries() {
1667        let root = PathBuf::from("/project");
1668        let results = AnalysisResults::default();
1669        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1670
1671        let sarif_results = sarif["runs"][0]["results"]
1672            .as_array()
1673            .expect("results should be an array");
1674        assert!(sarif_results.is_empty());
1675    }
1676
1677    #[test]
1678    fn sarif_unused_file_result() {
1679        let root = PathBuf::from("/project");
1680        let mut results = AnalysisResults::default();
1681        results
1682            .unused_files
1683            .push(UnusedFileFinding::with_actions(UnusedFile {
1684                path: root.join("src/dead.ts"),
1685            }));
1686
1687        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1688        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1689        assert_eq!(entries.len(), 1);
1690
1691        let entry = &entries[0];
1692        assert_eq!(entry["ruleId"], "fallow/unused-file");
1693        // Default severity is "error" per RulesConfig::default()
1694        assert_eq!(entry["level"], "error");
1695        assert_eq!(
1696            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1697            "src/dead.ts"
1698        );
1699    }
1700
1701    #[test]
1702    fn sarif_unused_export_includes_region() {
1703        let root = PathBuf::from("/project");
1704        let mut results = AnalysisResults::default();
1705        results
1706            .unused_exports
1707            .push(UnusedExportFinding::with_actions(UnusedExport {
1708                path: root.join("src/utils.ts"),
1709                export_name: "helperFn".to_string(),
1710                is_type_only: false,
1711                line: 10,
1712                col: 4,
1713                span_start: 120,
1714                is_re_export: false,
1715            }));
1716
1717        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1718        let entry = &sarif["runs"][0]["results"][0];
1719        assert_eq!(entry["ruleId"], "fallow/unused-export");
1720
1721        let region = &entry["locations"][0]["physicalLocation"]["region"];
1722        assert_eq!(region["startLine"], 10);
1723        // SARIF columns are 1-based, code adds +1 to the 0-based col
1724        assert_eq!(region["startColumn"], 5);
1725    }
1726
1727    #[test]
1728    fn sarif_unresolved_import_is_error_level() {
1729        let root = PathBuf::from("/project");
1730        let mut results = AnalysisResults::default();
1731        results
1732            .unresolved_imports
1733            .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
1734                path: root.join("src/app.ts"),
1735                specifier: "./missing".to_string(),
1736                line: 1,
1737                col: 0,
1738                specifier_col: 0,
1739            }));
1740
1741        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1742        let entry = &sarif["runs"][0]["results"][0];
1743        assert_eq!(entry["ruleId"], "fallow/unresolved-import");
1744        assert_eq!(entry["level"], "error");
1745    }
1746
1747    #[test]
1748    fn sarif_unlisted_dependency_points_to_import_site() {
1749        let root = PathBuf::from("/project");
1750        let mut results = AnalysisResults::default();
1751        results
1752            .unlisted_dependencies
1753            .push(UnlistedDependencyFinding::with_actions(
1754                UnlistedDependency {
1755                    package_name: "chalk".to_string(),
1756                    imported_from: vec![ImportSite {
1757                        path: root.join("src/cli.ts"),
1758                        line: 3,
1759                        col: 0,
1760                    }],
1761                },
1762            ));
1763
1764        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1765        let entry = &sarif["runs"][0]["results"][0];
1766        assert_eq!(entry["ruleId"], "fallow/unlisted-dependency");
1767        assert_eq!(entry["level"], "error");
1768        assert_eq!(
1769            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1770            "src/cli.ts"
1771        );
1772        let region = &entry["locations"][0]["physicalLocation"]["region"];
1773        assert_eq!(region["startLine"], 3);
1774        assert_eq!(region["startColumn"], 1);
1775    }
1776
1777    #[test]
1778    fn sarif_dependency_issues_point_to_package_json() {
1779        let root = PathBuf::from("/project");
1780        let mut results = AnalysisResults::default();
1781        results
1782            .unused_dependencies
1783            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1784                package_name: "lodash".to_string(),
1785                location: DependencyLocation::Dependencies,
1786                path: root.join("package.json"),
1787                line: 5,
1788                used_in_workspaces: Vec::new(),
1789            }));
1790        results
1791            .unused_dev_dependencies
1792            .push(UnusedDevDependencyFinding::with_actions(UnusedDependency {
1793                package_name: "jest".to_string(),
1794                location: DependencyLocation::DevDependencies,
1795                path: root.join("package.json"),
1796                line: 5,
1797                used_in_workspaces: Vec::new(),
1798            }));
1799
1800        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1801        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1802        for entry in entries {
1803            assert_eq!(
1804                entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1805                "package.json"
1806            );
1807        }
1808    }
1809
1810    #[test]
1811    fn sarif_duplicate_export_emits_one_result_per_location() {
1812        let root = PathBuf::from("/project");
1813        let mut results = AnalysisResults::default();
1814        results
1815            .duplicate_exports
1816            .push(DuplicateExportFinding::with_actions(DuplicateExport {
1817                export_name: "Config".to_string(),
1818                locations: vec![
1819                    DuplicateLocation {
1820                        path: root.join("src/a.ts"),
1821                        line: 15,
1822                        col: 0,
1823                    },
1824                    DuplicateLocation {
1825                        path: root.join("src/b.ts"),
1826                        line: 30,
1827                        col: 0,
1828                    },
1829                ],
1830            }));
1831
1832        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1833        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1834        // One SARIF result per location, not one per DuplicateExport
1835        assert_eq!(entries.len(), 2);
1836        assert_eq!(entries[0]["ruleId"], "fallow/duplicate-export");
1837        assert_eq!(entries[1]["ruleId"], "fallow/duplicate-export");
1838        assert_eq!(
1839            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1840            "src/a.ts"
1841        );
1842        assert_eq!(
1843            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1844            "src/b.ts"
1845        );
1846    }
1847
1848    #[test]
1849    fn sarif_all_issue_types_produce_results() {
1850        let root = PathBuf::from("/project");
1851        let results = sample_results(&root);
1852        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1853
1854        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1855        // All issue types with one entry each; duplicate_exports has 2 locations => one extra SARIF result
1856        assert_eq!(entries.len(), results.total_issues() + 1);
1857
1858        let rule_ids: Vec<&str> = entries
1859            .iter()
1860            .map(|e| e["ruleId"].as_str().unwrap())
1861            .collect();
1862        assert!(rule_ids.contains(&"fallow/unused-file"));
1863        assert!(rule_ids.contains(&"fallow/unused-export"));
1864        assert!(rule_ids.contains(&"fallow/unused-type"));
1865        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1866        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1867        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1868        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1869        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1870        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1871        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1872        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1873        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1874        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1875    }
1876
1877    #[test]
1878    fn sarif_serializes_to_valid_json() {
1879        let root = PathBuf::from("/project");
1880        let results = sample_results(&root);
1881        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1882
1883        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1884        let reparsed: serde_json::Value =
1885            serde_json::from_str(&json_str).expect("SARIF output should be valid JSON");
1886        assert_eq!(reparsed, sarif);
1887    }
1888
1889    #[test]
1890    fn sarif_file_write_produces_valid_sarif() {
1891        let root = PathBuf::from("/project");
1892        let results = sample_results(&root);
1893        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1894        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1895
1896        let dir = std::env::temp_dir().join("fallow-test-sarif-file");
1897        let _ = std::fs::create_dir_all(&dir);
1898        let sarif_path = dir.join("results.sarif");
1899        std::fs::write(&sarif_path, &json_str).expect("should write SARIF file");
1900
1901        let contents = std::fs::read_to_string(&sarif_path).expect("should read SARIF file");
1902        let parsed: serde_json::Value =
1903            serde_json::from_str(&contents).expect("file should contain valid JSON");
1904
1905        assert_eq!(parsed["version"], "2.1.0");
1906        assert_eq!(
1907            parsed["$schema"],
1908            "https://json.schemastore.org/sarif-2.1.0.json"
1909        );
1910        let sarif_results = parsed["runs"][0]["results"]
1911            .as_array()
1912            .expect("results should be an array");
1913        assert!(!sarif_results.is_empty());
1914
1915        // Clean up
1916        let _ = std::fs::remove_file(&sarif_path);
1917        let _ = std::fs::remove_dir(&dir);
1918    }
1919
1920    // ── Health SARIF ──
1921
1922    #[test]
1923    fn health_sarif_empty_no_results() {
1924        let root = PathBuf::from("/project");
1925        let report = crate::health_types::HealthReport {
1926            summary: crate::health_types::HealthSummary {
1927                files_analyzed: 10,
1928                functions_analyzed: 50,
1929                ..Default::default()
1930            },
1931            ..Default::default()
1932        };
1933        let sarif = build_health_sarif(&report, &root);
1934        assert_eq!(sarif["version"], "2.1.0");
1935        let results = sarif["runs"][0]["results"].as_array().unwrap();
1936        assert!(results.is_empty());
1937        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1938            .as_array()
1939            .unwrap();
1940        assert_eq!(rules.len(), 12);
1941    }
1942
1943    #[test]
1944    fn health_sarif_cyclomatic_only() {
1945        let root = PathBuf::from("/project");
1946        let report = crate::health_types::HealthReport {
1947            findings: vec![
1948                crate::health_types::ComplexityViolation {
1949                    path: root.join("src/utils.ts"),
1950                    name: "parseExpression".to_string(),
1951                    line: 42,
1952                    col: 0,
1953                    cyclomatic: 25,
1954                    cognitive: 10,
1955                    line_count: 80,
1956                    param_count: 0,
1957                    exceeded: crate::health_types::ExceededThreshold::Cyclomatic,
1958                    severity: crate::health_types::FindingSeverity::High,
1959                    crap: None,
1960                    coverage_pct: None,
1961                    coverage_tier: None,
1962                    coverage_source: None,
1963                    inherited_from: None,
1964                    component_rollup: None,
1965                }
1966                .into(),
1967            ],
1968            summary: crate::health_types::HealthSummary {
1969                files_analyzed: 5,
1970                functions_analyzed: 20,
1971                functions_above_threshold: 1,
1972                ..Default::default()
1973            },
1974            ..Default::default()
1975        };
1976        let sarif = build_health_sarif(&report, &root);
1977        let entry = &sarif["runs"][0]["results"][0];
1978        assert_eq!(entry["ruleId"], "fallow/high-cyclomatic-complexity");
1979        assert_eq!(entry["level"], "warning");
1980        assert!(
1981            entry["message"]["text"]
1982                .as_str()
1983                .unwrap()
1984                .contains("cyclomatic complexity 25")
1985        );
1986        assert_eq!(
1987            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1988            "src/utils.ts"
1989        );
1990        let region = &entry["locations"][0]["physicalLocation"]["region"];
1991        assert_eq!(region["startLine"], 42);
1992        assert_eq!(region["startColumn"], 1);
1993    }
1994
1995    #[test]
1996    fn health_sarif_cognitive_only() {
1997        let root = PathBuf::from("/project");
1998        let report = crate::health_types::HealthReport {
1999            findings: vec![
2000                crate::health_types::ComplexityViolation {
2001                    path: root.join("src/api.ts"),
2002                    name: "handleRequest".to_string(),
2003                    line: 10,
2004                    col: 4,
2005                    cyclomatic: 8,
2006                    cognitive: 20,
2007                    line_count: 40,
2008                    param_count: 0,
2009                    exceeded: crate::health_types::ExceededThreshold::Cognitive,
2010                    severity: crate::health_types::FindingSeverity::High,
2011                    crap: None,
2012                    coverage_pct: None,
2013                    coverage_tier: None,
2014                    coverage_source: None,
2015                    inherited_from: None,
2016                    component_rollup: None,
2017                }
2018                .into(),
2019            ],
2020            summary: crate::health_types::HealthSummary {
2021                files_analyzed: 3,
2022                functions_analyzed: 10,
2023                functions_above_threshold: 1,
2024                ..Default::default()
2025            },
2026            ..Default::default()
2027        };
2028        let sarif = build_health_sarif(&report, &root);
2029        let entry = &sarif["runs"][0]["results"][0];
2030        assert_eq!(entry["ruleId"], "fallow/high-cognitive-complexity");
2031        assert!(
2032            entry["message"]["text"]
2033                .as_str()
2034                .unwrap()
2035                .contains("cognitive complexity 20")
2036        );
2037        let region = &entry["locations"][0]["physicalLocation"]["region"];
2038        assert_eq!(region["startColumn"], 5); // col 4 + 1
2039    }
2040
2041    #[test]
2042    fn health_sarif_both_thresholds() {
2043        let root = PathBuf::from("/project");
2044        let report = crate::health_types::HealthReport {
2045            findings: vec![
2046                crate::health_types::ComplexityViolation {
2047                    path: root.join("src/complex.ts"),
2048                    name: "doEverything".to_string(),
2049                    line: 1,
2050                    col: 0,
2051                    cyclomatic: 30,
2052                    cognitive: 45,
2053                    line_count: 100,
2054                    param_count: 0,
2055                    exceeded: crate::health_types::ExceededThreshold::Both,
2056                    severity: crate::health_types::FindingSeverity::High,
2057                    crap: None,
2058                    coverage_pct: None,
2059                    coverage_tier: None,
2060                    coverage_source: None,
2061                    inherited_from: None,
2062                    component_rollup: None,
2063                }
2064                .into(),
2065            ],
2066            summary: crate::health_types::HealthSummary {
2067                files_analyzed: 1,
2068                functions_analyzed: 1,
2069                functions_above_threshold: 1,
2070                ..Default::default()
2071            },
2072            ..Default::default()
2073        };
2074        let sarif = build_health_sarif(&report, &root);
2075        let entry = &sarif["runs"][0]["results"][0];
2076        assert_eq!(entry["ruleId"], "fallow/high-complexity");
2077        let msg = entry["message"]["text"].as_str().unwrap();
2078        assert!(msg.contains("cyclomatic complexity 30"));
2079        assert!(msg.contains("cognitive complexity 45"));
2080    }
2081
2082    #[test]
2083    fn health_sarif_crap_only_emits_crap_rule() {
2084        // CRAP-only: cyclomatic + cognitive below their thresholds, CRAP at or
2085        // above the CRAP threshold. Rule must be `fallow/high-crap-score`.
2086        let root = PathBuf::from("/project");
2087        let report = crate::health_types::HealthReport {
2088            findings: vec![
2089                crate::health_types::ComplexityViolation {
2090                    path: root.join("src/untested.ts"),
2091                    name: "risky".to_string(),
2092                    line: 8,
2093                    col: 0,
2094                    cyclomatic: 10,
2095                    cognitive: 10,
2096                    line_count: 20,
2097                    param_count: 1,
2098                    exceeded: crate::health_types::ExceededThreshold::Crap,
2099                    severity: crate::health_types::FindingSeverity::High,
2100                    crap: Some(82.2),
2101                    coverage_pct: Some(12.0),
2102                    coverage_tier: None,
2103                    coverage_source: None,
2104                    inherited_from: None,
2105                    component_rollup: None,
2106                }
2107                .into(),
2108            ],
2109            summary: crate::health_types::HealthSummary {
2110                files_analyzed: 1,
2111                functions_analyzed: 1,
2112                functions_above_threshold: 1,
2113                ..Default::default()
2114            },
2115            ..Default::default()
2116        };
2117        let sarif = build_health_sarif(&report, &root);
2118        let entry = &sarif["runs"][0]["results"][0];
2119        assert_eq!(entry["ruleId"], "fallow/high-crap-score");
2120        let msg = entry["message"]["text"].as_str().unwrap();
2121        assert!(msg.contains("CRAP score 82.2"), "msg: {msg}");
2122        assert!(msg.contains("coverage 12%"), "msg: {msg}");
2123    }
2124
2125    #[test]
2126    fn health_sarif_cyclomatic_crap_uses_crap_rule() {
2127        // Cyclomatic + CRAP both exceeded. The CRAP-centric rule subsumes
2128        // the cyclomatic breach; only one SARIF result is emitted.
2129        let root = PathBuf::from("/project");
2130        let report = crate::health_types::HealthReport {
2131            findings: vec![
2132                crate::health_types::ComplexityViolation {
2133                    path: root.join("src/hot.ts"),
2134                    name: "branchy".to_string(),
2135                    line: 1,
2136                    col: 0,
2137                    cyclomatic: 67,
2138                    cognitive: 12,
2139                    line_count: 80,
2140                    param_count: 1,
2141                    exceeded: crate::health_types::ExceededThreshold::CyclomaticCrap,
2142                    severity: crate::health_types::FindingSeverity::Critical,
2143                    crap: Some(182.0),
2144                    coverage_pct: None,
2145                    coverage_tier: None,
2146                    coverage_source: None,
2147                    inherited_from: None,
2148                    component_rollup: None,
2149                }
2150                .into(),
2151            ],
2152            summary: crate::health_types::HealthSummary {
2153                files_analyzed: 1,
2154                functions_analyzed: 1,
2155                functions_above_threshold: 1,
2156                ..Default::default()
2157            },
2158            ..Default::default()
2159        };
2160        let sarif = build_health_sarif(&report, &root);
2161        let results = sarif["runs"][0]["results"].as_array().unwrap();
2162        assert_eq!(
2163            results.len(),
2164            1,
2165            "CyclomaticCrap should emit a single SARIF result under the CRAP rule"
2166        );
2167        assert_eq!(results[0]["ruleId"], "fallow/high-crap-score");
2168        let msg = results[0]["message"]["text"].as_str().unwrap();
2169        assert!(msg.contains("CRAP score 182"), "msg: {msg}");
2170        // coverage_pct absent => no coverage suffix
2171        assert!(!msg.contains("coverage"), "msg: {msg}");
2172    }
2173
2174    // ── Severity mapping ──
2175
2176    #[test]
2177    fn severity_to_sarif_level_error() {
2178        assert_eq!(severity_to_sarif_level(Severity::Error), "error");
2179    }
2180
2181    #[test]
2182    fn severity_to_sarif_level_warn() {
2183        assert_eq!(severity_to_sarif_level(Severity::Warn), "warning");
2184    }
2185
2186    #[test]
2187    #[should_panic(expected = "internal error: entered unreachable code")]
2188    fn severity_to_sarif_level_off() {
2189        let _ = severity_to_sarif_level(Severity::Off);
2190    }
2191
2192    // ── Re-export properties ──
2193
2194    #[test]
2195    fn sarif_re_export_has_properties() {
2196        let root = PathBuf::from("/project");
2197        let mut results = AnalysisResults::default();
2198        results
2199            .unused_exports
2200            .push(UnusedExportFinding::with_actions(UnusedExport {
2201                path: root.join("src/index.ts"),
2202                export_name: "reExported".to_string(),
2203                is_type_only: false,
2204                line: 1,
2205                col: 0,
2206                span_start: 0,
2207                is_re_export: true,
2208            }));
2209
2210        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2211        let entry = &sarif["runs"][0]["results"][0];
2212        assert_eq!(entry["properties"]["is_re_export"], true);
2213        let msg = entry["message"]["text"].as_str().unwrap();
2214        assert!(msg.starts_with("Re-export"));
2215    }
2216
2217    #[test]
2218    fn sarif_non_re_export_has_no_properties() {
2219        let root = PathBuf::from("/project");
2220        let mut results = AnalysisResults::default();
2221        results
2222            .unused_exports
2223            .push(UnusedExportFinding::with_actions(UnusedExport {
2224                path: root.join("src/utils.ts"),
2225                export_name: "foo".to_string(),
2226                is_type_only: false,
2227                line: 5,
2228                col: 0,
2229                span_start: 0,
2230                is_re_export: false,
2231            }));
2232
2233        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2234        let entry = &sarif["runs"][0]["results"][0];
2235        assert!(entry.get("properties").is_none());
2236        let msg = entry["message"]["text"].as_str().unwrap();
2237        assert!(msg.starts_with("Export"));
2238    }
2239
2240    // ── Type re-export ──
2241
2242    #[test]
2243    fn sarif_type_re_export_message() {
2244        let root = PathBuf::from("/project");
2245        let mut results = AnalysisResults::default();
2246        results
2247            .unused_types
2248            .push(UnusedTypeFinding::with_actions(UnusedExport {
2249                path: root.join("src/index.ts"),
2250                export_name: "MyType".to_string(),
2251                is_type_only: true,
2252                line: 1,
2253                col: 0,
2254                span_start: 0,
2255                is_re_export: true,
2256            }));
2257
2258        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2259        let entry = &sarif["runs"][0]["results"][0];
2260        assert_eq!(entry["ruleId"], "fallow/unused-type");
2261        let msg = entry["message"]["text"].as_str().unwrap();
2262        assert!(msg.starts_with("Type re-export"));
2263        assert_eq!(entry["properties"]["is_re_export"], true);
2264    }
2265
2266    // ── Dependency line == 0 skips region ──
2267
2268    #[test]
2269    fn sarif_dependency_line_zero_skips_region() {
2270        let root = PathBuf::from("/project");
2271        let mut results = AnalysisResults::default();
2272        results
2273            .unused_dependencies
2274            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
2275                package_name: "lodash".to_string(),
2276                location: DependencyLocation::Dependencies,
2277                path: root.join("package.json"),
2278                line: 0,
2279                used_in_workspaces: Vec::new(),
2280            }));
2281
2282        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2283        let entry = &sarif["runs"][0]["results"][0];
2284        let phys = &entry["locations"][0]["physicalLocation"];
2285        assert!(phys.get("region").is_none());
2286    }
2287
2288    #[test]
2289    fn sarif_dependency_line_nonzero_has_region() {
2290        let root = PathBuf::from("/project");
2291        let mut results = AnalysisResults::default();
2292        results
2293            .unused_dependencies
2294            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
2295                package_name: "lodash".to_string(),
2296                location: DependencyLocation::Dependencies,
2297                path: root.join("package.json"),
2298                line: 7,
2299                used_in_workspaces: Vec::new(),
2300            }));
2301
2302        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2303        let entry = &sarif["runs"][0]["results"][0];
2304        let region = &entry["locations"][0]["physicalLocation"]["region"];
2305        assert_eq!(region["startLine"], 7);
2306        assert_eq!(region["startColumn"], 1);
2307    }
2308
2309    // ── Type-only dependency line == 0 skips region ──
2310
2311    #[test]
2312    fn sarif_type_only_dep_line_zero_skips_region() {
2313        let root = PathBuf::from("/project");
2314        let mut results = AnalysisResults::default();
2315        results
2316            .type_only_dependencies
2317            .push(TypeOnlyDependencyFinding::with_actions(
2318                TypeOnlyDependency {
2319                    package_name: "zod".to_string(),
2320                    path: root.join("package.json"),
2321                    line: 0,
2322                },
2323            ));
2324
2325        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2326        let entry = &sarif["runs"][0]["results"][0];
2327        let phys = &entry["locations"][0]["physicalLocation"];
2328        assert!(phys.get("region").is_none());
2329    }
2330
2331    // ── Circular dependency line == 0 skips region ──
2332
2333    #[test]
2334    fn sarif_circular_dep_line_zero_skips_region() {
2335        let root = PathBuf::from("/project");
2336        let mut results = AnalysisResults::default();
2337        results
2338            .circular_dependencies
2339            .push(CircularDependencyFinding::with_actions(
2340                CircularDependency {
2341                    files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
2342                    length: 2,
2343                    line: 0,
2344                    col: 0,
2345                    is_cross_package: false,
2346                },
2347            ));
2348
2349        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2350        let entry = &sarif["runs"][0]["results"][0];
2351        let phys = &entry["locations"][0]["physicalLocation"];
2352        assert!(phys.get("region").is_none());
2353    }
2354
2355    #[test]
2356    fn sarif_circular_dep_line_nonzero_has_region() {
2357        let root = PathBuf::from("/project");
2358        let mut results = AnalysisResults::default();
2359        results
2360            .circular_dependencies
2361            .push(CircularDependencyFinding::with_actions(
2362                CircularDependency {
2363                    files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
2364                    length: 2,
2365                    line: 5,
2366                    col: 2,
2367                    is_cross_package: false,
2368                },
2369            ));
2370
2371        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2372        let entry = &sarif["runs"][0]["results"][0];
2373        let region = &entry["locations"][0]["physicalLocation"]["region"];
2374        assert_eq!(region["startLine"], 5);
2375        assert_eq!(region["startColumn"], 3);
2376    }
2377
2378    // ── Unused optional dependency ──
2379
2380    #[test]
2381    fn sarif_unused_optional_dependency_result() {
2382        let root = PathBuf::from("/project");
2383        let mut results = AnalysisResults::default();
2384        results
2385            .unused_optional_dependencies
2386            .push(UnusedOptionalDependencyFinding::with_actions(
2387                UnusedDependency {
2388                    package_name: "fsevents".to_string(),
2389                    location: DependencyLocation::OptionalDependencies,
2390                    path: root.join("package.json"),
2391                    line: 12,
2392                    used_in_workspaces: Vec::new(),
2393                },
2394            ));
2395
2396        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2397        let entry = &sarif["runs"][0]["results"][0];
2398        assert_eq!(entry["ruleId"], "fallow/unused-optional-dependency");
2399        let msg = entry["message"]["text"].as_str().unwrap();
2400        assert!(msg.contains("optionalDependencies"));
2401    }
2402
2403    // ── Enum and class member SARIF messages ──
2404
2405    #[test]
2406    fn sarif_enum_member_message_format() {
2407        let root = PathBuf::from("/project");
2408        let mut results = AnalysisResults::default();
2409        results.unused_enum_members.push(
2410            fallow_core::results::UnusedEnumMemberFinding::with_actions(UnusedMember {
2411                path: root.join("src/enums.ts"),
2412                parent_name: "Color".to_string(),
2413                member_name: "Purple".to_string(),
2414                kind: fallow_core::extract::MemberKind::EnumMember,
2415                line: 5,
2416                col: 2,
2417            }),
2418        );
2419
2420        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2421        let entry = &sarif["runs"][0]["results"][0];
2422        assert_eq!(entry["ruleId"], "fallow/unused-enum-member");
2423        let msg = entry["message"]["text"].as_str().unwrap();
2424        assert!(msg.contains("Enum member 'Color.Purple'"));
2425        let region = &entry["locations"][0]["physicalLocation"]["region"];
2426        assert_eq!(region["startColumn"], 3); // col 2 + 1
2427    }
2428
2429    #[test]
2430    fn sarif_class_member_message_format() {
2431        let root = PathBuf::from("/project");
2432        let mut results = AnalysisResults::default();
2433        results.unused_class_members.push(
2434            fallow_core::results::UnusedClassMemberFinding::with_actions(UnusedMember {
2435                path: root.join("src/service.ts"),
2436                parent_name: "API".to_string(),
2437                member_name: "fetch".to_string(),
2438                kind: fallow_core::extract::MemberKind::ClassMethod,
2439                line: 10,
2440                col: 4,
2441            }),
2442        );
2443
2444        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2445        let entry = &sarif["runs"][0]["results"][0];
2446        assert_eq!(entry["ruleId"], "fallow/unused-class-member");
2447        let msg = entry["message"]["text"].as_str().unwrap();
2448        assert!(msg.contains("Class member 'API.fetch'"));
2449    }
2450
2451    // ── Duplication SARIF ──
2452
2453    #[test]
2454    #[expect(
2455        clippy::cast_possible_truncation,
2456        reason = "test line/col values are trivially small"
2457    )]
2458    fn duplication_sarif_structure() {
2459        use fallow_core::duplicates::*;
2460
2461        let root = PathBuf::from("/project");
2462        let report = DuplicationReport {
2463            clone_groups: vec![CloneGroup {
2464                instances: vec![
2465                    CloneInstance {
2466                        file: root.join("src/a.ts"),
2467                        start_line: 1,
2468                        end_line: 10,
2469                        start_col: 0,
2470                        end_col: 0,
2471                        fragment: String::new(),
2472                    },
2473                    CloneInstance {
2474                        file: root.join("src/b.ts"),
2475                        start_line: 5,
2476                        end_line: 14,
2477                        start_col: 2,
2478                        end_col: 0,
2479                        fragment: String::new(),
2480                    },
2481                ],
2482                token_count: 50,
2483                line_count: 10,
2484            }],
2485            clone_families: vec![],
2486            mirrored_directories: vec![],
2487            stats: DuplicationStats::default(),
2488        };
2489
2490        let sarif = serde_json::json!({
2491            "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2492            "version": "2.1.0",
2493            "runs": [{
2494                "tool": {
2495                    "driver": {
2496                        "name": "fallow",
2497                        "version": env!("CARGO_PKG_VERSION"),
2498                        "informationUri": "https://github.com/fallow-rs/fallow",
2499                        "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
2500                    }
2501                },
2502                "results": []
2503            }]
2504        });
2505        // Just verify the function doesn't panic and produces expected structure
2506        let _ = sarif;
2507
2508        // Test the actual build path through print_duplication_sarif internals
2509        let mut sarif_results = Vec::new();
2510        for (i, group) in report.clone_groups.iter().enumerate() {
2511            for instance in &group.instances {
2512                sarif_results.push(sarif_result(
2513                    "fallow/code-duplication",
2514                    "warning",
2515                    &format!(
2516                        "Code clone group {} ({} lines, {} instances)",
2517                        i + 1,
2518                        group.line_count,
2519                        group.instances.len()
2520                    ),
2521                    &super::super::relative_uri(&instance.file, &root),
2522                    Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
2523                ));
2524            }
2525        }
2526        assert_eq!(sarif_results.len(), 2);
2527        assert_eq!(sarif_results[0]["ruleId"], "fallow/code-duplication");
2528        assert!(
2529            sarif_results[0]["message"]["text"]
2530                .as_str()
2531                .unwrap()
2532                .contains("10 lines")
2533        );
2534        let region0 = &sarif_results[0]["locations"][0]["physicalLocation"]["region"];
2535        assert_eq!(region0["startLine"], 1);
2536        assert_eq!(region0["startColumn"], 1); // start_col 0 + 1
2537        let region1 = &sarif_results[1]["locations"][0]["physicalLocation"]["region"];
2538        assert_eq!(region1["startLine"], 5);
2539        assert_eq!(region1["startColumn"], 3); // start_col 2 + 1
2540    }
2541
2542    // ── sarif_rule fallback (unknown rule ID) ──
2543
2544    #[test]
2545    fn sarif_rule_known_id_has_full_description() {
2546        let rule = sarif_rule("fallow/unused-file", "fallback text", "error");
2547        assert!(rule.get("fullDescription").is_some());
2548        assert!(rule.get("helpUri").is_some());
2549    }
2550
2551    #[test]
2552    fn sarif_rule_unknown_id_uses_fallback() {
2553        let rule = sarif_rule("fallow/nonexistent", "fallback text", "warning");
2554        assert_eq!(rule["shortDescription"]["text"], "fallback text");
2555        assert!(rule.get("fullDescription").is_none());
2556        assert!(rule.get("helpUri").is_none());
2557        assert_eq!(rule["defaultConfiguration"]["level"], "warning");
2558    }
2559
2560    // ── sarif_result without region ──
2561
2562    #[test]
2563    fn sarif_result_no_region_omits_region_key() {
2564        let result = sarif_result("rule/test", "error", "test msg", "src/file.ts", None);
2565        let phys = &result["locations"][0]["physicalLocation"];
2566        assert!(phys.get("region").is_none());
2567        assert_eq!(phys["artifactLocation"]["uri"], "src/file.ts");
2568    }
2569
2570    #[test]
2571    fn sarif_result_with_region_includes_region() {
2572        let result = sarif_result(
2573            "rule/test",
2574            "error",
2575            "test msg",
2576            "src/file.ts",
2577            Some((10, 5)),
2578        );
2579        let region = &result["locations"][0]["physicalLocation"]["region"];
2580        assert_eq!(region["startLine"], 10);
2581        assert_eq!(region["startColumn"], 5);
2582    }
2583
2584    #[test]
2585    fn sarif_partial_fingerprint_ignores_rendered_message() {
2586        let a = sarif_result(
2587            "rule/test",
2588            "error",
2589            "first message",
2590            "src/file.ts",
2591            Some((10, 5)),
2592        );
2593        let b = sarif_result(
2594            "rule/test",
2595            "error",
2596            "rewritten message",
2597            "src/file.ts",
2598            Some((10, 5)),
2599        );
2600        assert_eq!(
2601            a["partialFingerprints"][fingerprint::FINGERPRINT_KEY],
2602            b["partialFingerprints"][fingerprint::FINGERPRINT_KEY]
2603        );
2604    }
2605
2606    // ── Health SARIF refactoring targets ──
2607
2608    #[test]
2609    fn health_sarif_includes_refactoring_targets() {
2610        use crate::health_types::*;
2611
2612        let root = PathBuf::from("/project");
2613        let report = HealthReport {
2614            summary: HealthSummary {
2615                files_analyzed: 10,
2616                functions_analyzed: 50,
2617                ..Default::default()
2618            },
2619            targets: vec![
2620                RefactoringTarget {
2621                    path: root.join("src/complex.ts"),
2622                    priority: 85.0,
2623                    efficiency: 42.5,
2624                    recommendation: "Split high-impact file".into(),
2625                    category: RecommendationCategory::SplitHighImpact,
2626                    effort: EffortEstimate::Medium,
2627                    confidence: Confidence::High,
2628                    factors: vec![],
2629                    evidence: None,
2630                }
2631                .into(),
2632            ],
2633            ..Default::default()
2634        };
2635
2636        let sarif = build_health_sarif(&report, &root);
2637        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2638        assert_eq!(entries.len(), 1);
2639        assert_eq!(entries[0]["ruleId"], "fallow/refactoring-target");
2640        assert_eq!(entries[0]["level"], "warning");
2641        let msg = entries[0]["message"]["text"].as_str().unwrap();
2642        assert!(msg.contains("high impact"));
2643        assert!(msg.contains("Split high-impact file"));
2644        assert!(msg.contains("42.5"));
2645    }
2646
2647    #[test]
2648    fn health_sarif_includes_coverage_gaps() {
2649        use crate::health_types::*;
2650
2651        let root = PathBuf::from("/project");
2652        let report = HealthReport {
2653            summary: HealthSummary {
2654                files_analyzed: 10,
2655                functions_analyzed: 50,
2656                ..Default::default()
2657            },
2658            coverage_gaps: Some(CoverageGaps {
2659                summary: CoverageGapSummary {
2660                    runtime_files: 2,
2661                    covered_files: 0,
2662                    file_coverage_pct: 0.0,
2663                    untested_files: 1,
2664                    untested_exports: 1,
2665                },
2666                files: vec![UntestedFileFinding::with_actions(
2667                    UntestedFile {
2668                        path: root.join("src/app.ts"),
2669                        value_export_count: 2,
2670                    },
2671                    &root,
2672                )],
2673                exports: vec![UntestedExportFinding::with_actions(
2674                    UntestedExport {
2675                        path: root.join("src/app.ts"),
2676                        export_name: "loader".into(),
2677                        line: 12,
2678                        col: 4,
2679                    },
2680                    &root,
2681                )],
2682            }),
2683            ..Default::default()
2684        };
2685
2686        let sarif = build_health_sarif(&report, &root);
2687        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2688        assert_eq!(entries.len(), 2);
2689        assert_eq!(entries[0]["ruleId"], "fallow/untested-file");
2690        assert_eq!(
2691            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2692            "src/app.ts"
2693        );
2694        assert!(
2695            entries[0]["message"]["text"]
2696                .as_str()
2697                .unwrap()
2698                .contains("2 value exports")
2699        );
2700        assert_eq!(entries[1]["ruleId"], "fallow/untested-export");
2701        assert_eq!(
2702            entries[1]["locations"][0]["physicalLocation"]["region"]["startLine"],
2703            12
2704        );
2705        assert_eq!(
2706            entries[1]["locations"][0]["physicalLocation"]["region"]["startColumn"],
2707            5
2708        );
2709    }
2710
2711    // ── Health SARIF rules include fullDescription from explain module ──
2712
2713    #[test]
2714    fn health_sarif_rules_have_full_descriptions() {
2715        let root = PathBuf::from("/project");
2716        let report = crate::health_types::HealthReport::default();
2717        let sarif = build_health_sarif(&report, &root);
2718        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
2719            .as_array()
2720            .unwrap();
2721        for rule in rules {
2722            let id = rule["id"].as_str().unwrap();
2723            assert!(
2724                rule.get("fullDescription").is_some(),
2725                "health rule {id} should have fullDescription"
2726            );
2727            assert!(
2728                rule.get("helpUri").is_some(),
2729                "health rule {id} should have helpUri"
2730            );
2731        }
2732    }
2733
2734    // ── Warn severity propagates correctly ──
2735
2736    #[test]
2737    fn sarif_warn_severity_produces_warning_level() {
2738        let root = PathBuf::from("/project");
2739        let mut results = AnalysisResults::default();
2740        results
2741            .unused_files
2742            .push(UnusedFileFinding::with_actions(UnusedFile {
2743                path: root.join("src/dead.ts"),
2744            }));
2745
2746        let rules = RulesConfig {
2747            unused_files: Severity::Warn,
2748            ..RulesConfig::default()
2749        };
2750
2751        let sarif = build_sarif(&results, &root, &rules);
2752        let entry = &sarif["runs"][0]["results"][0];
2753        assert_eq!(entry["level"], "warning");
2754    }
2755
2756    // ── Unused file has no region ──
2757
2758    #[test]
2759    fn sarif_unused_file_has_no_region() {
2760        let root = PathBuf::from("/project");
2761        let mut results = AnalysisResults::default();
2762        results
2763            .unused_files
2764            .push(UnusedFileFinding::with_actions(UnusedFile {
2765                path: root.join("src/dead.ts"),
2766            }));
2767
2768        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2769        let entry = &sarif["runs"][0]["results"][0];
2770        let phys = &entry["locations"][0]["physicalLocation"];
2771        assert!(phys.get("region").is_none());
2772    }
2773
2774    // ── Multiple unlisted deps with multiple import sites ──
2775
2776    #[test]
2777    fn sarif_unlisted_dep_multiple_import_sites() {
2778        let root = PathBuf::from("/project");
2779        let mut results = AnalysisResults::default();
2780        results
2781            .unlisted_dependencies
2782            .push(UnlistedDependencyFinding::with_actions(
2783                UnlistedDependency {
2784                    package_name: "dotenv".to_string(),
2785                    imported_from: vec![
2786                        ImportSite {
2787                            path: root.join("src/a.ts"),
2788                            line: 1,
2789                            col: 0,
2790                        },
2791                        ImportSite {
2792                            path: root.join("src/b.ts"),
2793                            line: 5,
2794                            col: 0,
2795                        },
2796                    ],
2797                },
2798            ));
2799
2800        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2801        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2802        // One SARIF result per import site
2803        assert_eq!(entries.len(), 2);
2804        assert_eq!(
2805            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2806            "src/a.ts"
2807        );
2808        assert_eq!(
2809            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2810            "src/b.ts"
2811        );
2812    }
2813
2814    // ── Empty unlisted dep (no import sites) produces zero results ──
2815
2816    #[test]
2817    fn sarif_unlisted_dep_no_import_sites() {
2818        let root = PathBuf::from("/project");
2819        let mut results = AnalysisResults::default();
2820        results
2821            .unlisted_dependencies
2822            .push(UnlistedDependencyFinding::with_actions(
2823                UnlistedDependency {
2824                    package_name: "phantom".to_string(),
2825                    imported_from: vec![],
2826                },
2827            ));
2828
2829        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2830        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2831        // No import sites => no SARIF results for this unlisted dep
2832        assert!(entries.is_empty());
2833    }
2834}