Skip to main content

fallow_cli/report/
sarif.rs

1use std::path::Path;
2use std::process::ExitCode;
3
4use fallow_config::{RulesConfig, Severity};
5use fallow_core::duplicates::DuplicationReport;
6use fallow_core::results::{
7    AnalysisResults, BoundaryViolation, CircularDependency, DuplicateExport, StaleSuppression,
8    TestOnlyDependency, TypeOnlyDependency, UnlistedDependency, UnresolvedImport, UnusedDependency,
9    UnusedExport, UnusedFile, UnusedMember,
10};
11
12use super::grouping::{self, OwnershipResolver};
13use super::{emit_json, relative_uri};
14use crate::explain;
15
16/// Intermediate fields extracted from an issue for SARIF result construction.
17struct SarifFields {
18    rule_id: &'static str,
19    level: &'static str,
20    message: String,
21    uri: String,
22    region: Option<(u32, u32)>,
23    properties: Option<serde_json::Value>,
24}
25
26const fn severity_to_sarif_level(s: Severity) -> &'static str {
27    match s {
28        Severity::Error => "error",
29        Severity::Warn | Severity::Off => "warning",
30    }
31}
32
33/// Build a single SARIF result object.
34///
35/// When `region` is `Some((line, col))`, a `region` block with 1-based
36/// `startLine` and `startColumn` is included in the physical location.
37fn sarif_result(
38    rule_id: &str,
39    level: &str,
40    message: &str,
41    uri: &str,
42    region: Option<(u32, u32)>,
43) -> serde_json::Value {
44    let mut physical_location = serde_json::json!({
45        "artifactLocation": { "uri": uri }
46    });
47    if let Some((line, col)) = region {
48        physical_location["region"] = serde_json::json!({
49            "startLine": line,
50            "startColumn": col
51        });
52    }
53    serde_json::json!({
54        "ruleId": rule_id,
55        "level": level,
56        "message": { "text": message },
57        "locations": [{ "physicalLocation": physical_location }]
58    })
59}
60
61/// Append SARIF results for a slice of items using a closure to extract fields.
62fn push_sarif_results<T>(
63    sarif_results: &mut Vec<serde_json::Value>,
64    items: &[T],
65    extract: impl Fn(&T) -> SarifFields,
66) {
67    for item in items {
68        let fields = extract(item);
69        let mut result = sarif_result(
70            fields.rule_id,
71            fields.level,
72            &fields.message,
73            &fields.uri,
74            fields.region,
75        );
76        if let Some(props) = fields.properties {
77            result["properties"] = props;
78        }
79        sarif_results.push(result);
80    }
81}
82
83/// Build a SARIF rule definition with optional `fullDescription` and `helpUri`
84/// sourced from the centralized explain module.
85fn sarif_rule(id: &str, fallback_short: &str, level: &str) -> serde_json::Value {
86    explain::rule_by_id(id).map_or_else(
87        || {
88            serde_json::json!({
89                "id": id,
90                "shortDescription": { "text": fallback_short },
91                "defaultConfiguration": { "level": level }
92            })
93        },
94        |def| {
95            serde_json::json!({
96                "id": id,
97                "shortDescription": { "text": def.short },
98                "fullDescription": { "text": def.full },
99                "helpUri": explain::rule_docs_url(def),
100                "defaultConfiguration": { "level": level }
101            })
102        },
103    )
104}
105
106/// Extract SARIF fields for an unused export or type export.
107fn sarif_export_fields(
108    export: &UnusedExport,
109    root: &Path,
110    rule_id: &'static str,
111    level: &'static str,
112    kind: &str,
113    re_kind: &str,
114) -> SarifFields {
115    let label = if export.is_re_export { re_kind } else { kind };
116    SarifFields {
117        rule_id,
118        level,
119        message: format!(
120            "{} '{}' is never imported by other modules",
121            label, export.export_name
122        ),
123        uri: relative_uri(&export.path, root),
124        region: Some((export.line, export.col + 1)),
125        properties: if export.is_re_export {
126            Some(serde_json::json!({ "is_re_export": true }))
127        } else {
128            None
129        },
130    }
131}
132
133/// Extract SARIF fields for an unused dependency.
134fn sarif_dep_fields(
135    dep: &UnusedDependency,
136    root: &Path,
137    rule_id: &'static str,
138    level: &'static str,
139    section: &str,
140) -> SarifFields {
141    SarifFields {
142        rule_id,
143        level,
144        message: format!(
145            "Package '{}' is in {} but never imported",
146            dep.package_name, section
147        ),
148        uri: relative_uri(&dep.path, root),
149        region: if dep.line > 0 {
150            Some((dep.line, 1))
151        } else {
152            None
153        },
154        properties: None,
155    }
156}
157
158/// Extract SARIF fields for an unused enum or class member.
159fn sarif_member_fields(
160    member: &UnusedMember,
161    root: &Path,
162    rule_id: &'static str,
163    level: &'static str,
164    kind: &str,
165) -> SarifFields {
166    SarifFields {
167        rule_id,
168        level,
169        message: format!(
170            "{} member '{}.{}' is never referenced",
171            kind, member.parent_name, member.member_name
172        ),
173        uri: relative_uri(&member.path, root),
174        region: Some((member.line, member.col + 1)),
175        properties: None,
176    }
177}
178
179fn sarif_unused_file_fields(file: &UnusedFile, root: &Path, level: &'static str) -> SarifFields {
180    SarifFields {
181        rule_id: "fallow/unused-file",
182        level,
183        message: "File is not reachable from any entry point".to_string(),
184        uri: relative_uri(&file.path, root),
185        region: None,
186        properties: None,
187    }
188}
189
190fn sarif_type_only_dep_fields(
191    dep: &TypeOnlyDependency,
192    root: &Path,
193    level: &'static str,
194) -> SarifFields {
195    SarifFields {
196        rule_id: "fallow/type-only-dependency",
197        level,
198        message: format!(
199            "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
200            dep.package_name
201        ),
202        uri: relative_uri(&dep.path, root),
203        region: if dep.line > 0 {
204            Some((dep.line, 1))
205        } else {
206            None
207        },
208        properties: None,
209    }
210}
211
212fn sarif_test_only_dep_fields(
213    dep: &TestOnlyDependency,
214    root: &Path,
215    level: &'static str,
216) -> SarifFields {
217    SarifFields {
218        rule_id: "fallow/test-only-dependency",
219        level,
220        message: format!(
221            "Package '{}' is only imported by test files (consider moving to devDependencies)",
222            dep.package_name
223        ),
224        uri: relative_uri(&dep.path, root),
225        region: if dep.line > 0 {
226            Some((dep.line, 1))
227        } else {
228            None
229        },
230        properties: None,
231    }
232}
233
234fn sarif_unresolved_import_fields(
235    import: &UnresolvedImport,
236    root: &Path,
237    level: &'static str,
238) -> SarifFields {
239    SarifFields {
240        rule_id: "fallow/unresolved-import",
241        level,
242        message: format!("Import '{}' could not be resolved", import.specifier),
243        uri: relative_uri(&import.path, root),
244        region: Some((import.line, import.col + 1)),
245        properties: None,
246    }
247}
248
249fn sarif_circular_dep_fields(
250    cycle: &CircularDependency,
251    root: &Path,
252    level: &'static str,
253) -> SarifFields {
254    let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
255    let mut display_chain = chain.clone();
256    if let Some(first) = chain.first() {
257        display_chain.push(first.clone());
258    }
259    let first_uri = chain.first().map_or_else(String::new, Clone::clone);
260    SarifFields {
261        rule_id: "fallow/circular-dependency",
262        level,
263        message: format!(
264            "Circular dependency{}: {}",
265            if cycle.is_cross_package {
266                " (cross-package)"
267            } else {
268                ""
269            },
270            display_chain.join(" \u{2192} ")
271        ),
272        uri: first_uri,
273        region: if cycle.line > 0 {
274            Some((cycle.line, cycle.col + 1))
275        } else {
276            None
277        },
278        properties: None,
279    }
280}
281
282fn sarif_boundary_violation_fields(
283    violation: &BoundaryViolation,
284    root: &Path,
285    level: &'static str,
286) -> SarifFields {
287    let from_uri = relative_uri(&violation.from_path, root);
288    let to_uri = relative_uri(&violation.to_path, root);
289    SarifFields {
290        rule_id: "fallow/boundary-violation",
291        level,
292        message: format!(
293            "Import from zone '{}' to zone '{}' is not allowed ({})",
294            violation.from_zone, violation.to_zone, to_uri,
295        ),
296        uri: from_uri,
297        region: if violation.line > 0 {
298            Some((violation.line, violation.col + 1))
299        } else {
300            None
301        },
302        properties: None,
303    }
304}
305
306fn sarif_stale_suppression_fields(
307    suppression: &StaleSuppression,
308    root: &Path,
309    level: &'static str,
310) -> SarifFields {
311    SarifFields {
312        rule_id: "fallow/stale-suppression",
313        level,
314        message: suppression.description(),
315        uri: relative_uri(&suppression.path, root),
316        region: Some((suppression.line, suppression.col + 1)),
317        properties: None,
318    }
319}
320
321/// Unlisted deps fan out to one SARIF result per import site, so they do not
322/// fit `push_sarif_results`. Keep the nested-loop shape in its own helper.
323fn push_sarif_unlisted_deps(
324    sarif_results: &mut Vec<serde_json::Value>,
325    deps: &[UnlistedDependency],
326    root: &Path,
327    level: &'static str,
328) {
329    for dep in deps {
330        for site in &dep.imported_from {
331            sarif_results.push(sarif_result(
332                "fallow/unlisted-dependency",
333                level,
334                &format!(
335                    "Package '{}' is imported but not listed in package.json",
336                    dep.package_name
337                ),
338                &relative_uri(&site.path, root),
339                Some((site.line, site.col + 1)),
340            ));
341        }
342    }
343}
344
345/// Duplicate exports fan out to one SARIF result per location
346/// (SARIF 2.1.0 section 3.27.12), so they do not fit `push_sarif_results`.
347fn push_sarif_duplicate_exports(
348    sarif_results: &mut Vec<serde_json::Value>,
349    dups: &[DuplicateExport],
350    root: &Path,
351    level: &'static str,
352) {
353    for dup in dups {
354        for loc in &dup.locations {
355            sarif_results.push(sarif_result(
356                "fallow/duplicate-export",
357                level,
358                &format!("Export '{}' appears in multiple modules", dup.export_name),
359                &relative_uri(&loc.path, root),
360                Some((loc.line, loc.col + 1)),
361            ));
362        }
363    }
364}
365
366/// Build the SARIF rules list from the current rules configuration.
367fn build_sarif_rules(rules: &RulesConfig) -> Vec<serde_json::Value> {
368    vec![
369        sarif_rule(
370            "fallow/unused-file",
371            "File is not reachable from any entry point",
372            severity_to_sarif_level(rules.unused_files),
373        ),
374        sarif_rule(
375            "fallow/unused-export",
376            "Export is never imported",
377            severity_to_sarif_level(rules.unused_exports),
378        ),
379        sarif_rule(
380            "fallow/unused-type",
381            "Type export is never imported",
382            severity_to_sarif_level(rules.unused_types),
383        ),
384        sarif_rule(
385            "fallow/unused-dependency",
386            "Dependency listed but never imported",
387            severity_to_sarif_level(rules.unused_dependencies),
388        ),
389        sarif_rule(
390            "fallow/unused-dev-dependency",
391            "Dev dependency listed but never imported",
392            severity_to_sarif_level(rules.unused_dev_dependencies),
393        ),
394        sarif_rule(
395            "fallow/unused-optional-dependency",
396            "Optional dependency listed but never imported",
397            severity_to_sarif_level(rules.unused_optional_dependencies),
398        ),
399        sarif_rule(
400            "fallow/type-only-dependency",
401            "Production dependency only used via type-only imports",
402            severity_to_sarif_level(rules.type_only_dependencies),
403        ),
404        sarif_rule(
405            "fallow/test-only-dependency",
406            "Production dependency only imported by test files",
407            severity_to_sarif_level(rules.test_only_dependencies),
408        ),
409        sarif_rule(
410            "fallow/unused-enum-member",
411            "Enum member is never referenced",
412            severity_to_sarif_level(rules.unused_enum_members),
413        ),
414        sarif_rule(
415            "fallow/unused-class-member",
416            "Class member is never referenced",
417            severity_to_sarif_level(rules.unused_class_members),
418        ),
419        sarif_rule(
420            "fallow/unresolved-import",
421            "Import could not be resolved",
422            severity_to_sarif_level(rules.unresolved_imports),
423        ),
424        sarif_rule(
425            "fallow/unlisted-dependency",
426            "Dependency used but not in package.json",
427            severity_to_sarif_level(rules.unlisted_dependencies),
428        ),
429        sarif_rule(
430            "fallow/duplicate-export",
431            "Export name appears in multiple modules",
432            severity_to_sarif_level(rules.duplicate_exports),
433        ),
434        sarif_rule(
435            "fallow/circular-dependency",
436            "Circular dependency chain detected",
437            severity_to_sarif_level(rules.circular_dependencies),
438        ),
439        sarif_rule(
440            "fallow/boundary-violation",
441            "Import crosses an architecture boundary",
442            severity_to_sarif_level(rules.boundary_violation),
443        ),
444        sarif_rule(
445            "fallow/stale-suppression",
446            "Suppression comment or tag no longer matches any issue",
447            severity_to_sarif_level(rules.stale_suppressions),
448        ),
449    ]
450}
451
452#[must_use]
453pub fn build_sarif(
454    results: &AnalysisResults,
455    root: &Path,
456    rules: &RulesConfig,
457) -> serde_json::Value {
458    let mut sarif_results = Vec::new();
459    let lvl_files = severity_to_sarif_level(rules.unused_files);
460    let lvl_exports = severity_to_sarif_level(rules.unused_exports);
461    let lvl_types = severity_to_sarif_level(rules.unused_types);
462    let lvl_deps = severity_to_sarif_level(rules.unused_dependencies);
463    let lvl_dev_deps = severity_to_sarif_level(rules.unused_dev_dependencies);
464    let lvl_opt_deps = severity_to_sarif_level(rules.unused_optional_dependencies);
465    let lvl_type_only = severity_to_sarif_level(rules.type_only_dependencies);
466    let lvl_test_only = severity_to_sarif_level(rules.test_only_dependencies);
467    let lvl_enum_members = severity_to_sarif_level(rules.unused_enum_members);
468    let lvl_class_members = severity_to_sarif_level(rules.unused_class_members);
469    let lvl_unresolved = severity_to_sarif_level(rules.unresolved_imports);
470    let lvl_unlisted = severity_to_sarif_level(rules.unlisted_dependencies);
471    let lvl_duplicate = severity_to_sarif_level(rules.duplicate_exports);
472    let lvl_circular = severity_to_sarif_level(rules.circular_dependencies);
473    let lvl_boundary = severity_to_sarif_level(rules.boundary_violation);
474    let lvl_stale = severity_to_sarif_level(rules.stale_suppressions);
475
476    push_sarif_results(&mut sarif_results, &results.unused_files, |f| {
477        sarif_unused_file_fields(f, root, lvl_files)
478    });
479    push_sarif_results(&mut sarif_results, &results.unused_exports, |e| {
480        sarif_export_fields(
481            e,
482            root,
483            "fallow/unused-export",
484            lvl_exports,
485            "Export",
486            "Re-export",
487        )
488    });
489    push_sarif_results(&mut sarif_results, &results.unused_types, |e| {
490        sarif_export_fields(
491            e,
492            root,
493            "fallow/unused-type",
494            lvl_types,
495            "Type export",
496            "Type re-export",
497        )
498    });
499    push_sarif_results(&mut sarif_results, &results.unused_dependencies, |d| {
500        sarif_dep_fields(
501            d,
502            root,
503            "fallow/unused-dependency",
504            lvl_deps,
505            "dependencies",
506        )
507    });
508    push_sarif_results(&mut sarif_results, &results.unused_dev_dependencies, |d| {
509        sarif_dep_fields(
510            d,
511            root,
512            "fallow/unused-dev-dependency",
513            lvl_dev_deps,
514            "devDependencies",
515        )
516    });
517    push_sarif_results(
518        &mut sarif_results,
519        &results.unused_optional_dependencies,
520        |d| {
521            sarif_dep_fields(
522                d,
523                root,
524                "fallow/unused-optional-dependency",
525                lvl_opt_deps,
526                "optionalDependencies",
527            )
528        },
529    );
530    push_sarif_results(&mut sarif_results, &results.type_only_dependencies, |d| {
531        sarif_type_only_dep_fields(d, root, lvl_type_only)
532    });
533    push_sarif_results(&mut sarif_results, &results.test_only_dependencies, |d| {
534        sarif_test_only_dep_fields(d, root, lvl_test_only)
535    });
536    push_sarif_results(&mut sarif_results, &results.unused_enum_members, |m| {
537        sarif_member_fields(
538            m,
539            root,
540            "fallow/unused-enum-member",
541            lvl_enum_members,
542            "Enum",
543        )
544    });
545    push_sarif_results(&mut sarif_results, &results.unused_class_members, |m| {
546        sarif_member_fields(
547            m,
548            root,
549            "fallow/unused-class-member",
550            lvl_class_members,
551            "Class",
552        )
553    });
554    push_sarif_results(&mut sarif_results, &results.unresolved_imports, |i| {
555        sarif_unresolved_import_fields(i, root, lvl_unresolved)
556    });
557    push_sarif_unlisted_deps(
558        &mut sarif_results,
559        &results.unlisted_dependencies,
560        root,
561        lvl_unlisted,
562    );
563    push_sarif_duplicate_exports(
564        &mut sarif_results,
565        &results.duplicate_exports,
566        root,
567        lvl_duplicate,
568    );
569    push_sarif_results(&mut sarif_results, &results.circular_dependencies, |c| {
570        sarif_circular_dep_fields(c, root, lvl_circular)
571    });
572    push_sarif_results(&mut sarif_results, &results.boundary_violations, |v| {
573        sarif_boundary_violation_fields(v, root, lvl_boundary)
574    });
575    push_sarif_results(&mut sarif_results, &results.stale_suppressions, |s| {
576        sarif_stale_suppression_fields(s, root, lvl_stale)
577    });
578
579    serde_json::json!({
580        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
581        "version": "2.1.0",
582        "runs": [{
583            "tool": {
584                "driver": {
585                    "name": "fallow",
586                    "version": env!("CARGO_PKG_VERSION"),
587                    "informationUri": "https://github.com/fallow-rs/fallow",
588                    "rules": build_sarif_rules(rules)
589                }
590            },
591            "results": sarif_results
592        }]
593    })
594}
595
596pub(super) fn print_sarif(results: &AnalysisResults, root: &Path, rules: &RulesConfig) -> ExitCode {
597    let sarif = build_sarif(results, root, rules);
598    emit_json(&sarif, "SARIF")
599}
600
601/// Print SARIF output with owner properties added to each result.
602///
603/// Calls `build_sarif` to produce the standard SARIF JSON, then post-processes
604/// each result to add `"properties": { "owner": "@team" }` by resolving the
605/// artifact location URI through the `OwnershipResolver`.
606pub(super) fn print_grouped_sarif(
607    results: &AnalysisResults,
608    root: &Path,
609    rules: &RulesConfig,
610    resolver: &OwnershipResolver,
611) -> ExitCode {
612    let mut sarif = build_sarif(results, root, rules);
613
614    // Post-process each result to inject the owner property.
615    if let Some(runs) = sarif.get_mut("runs").and_then(|r| r.as_array_mut()) {
616        for run in runs {
617            if let Some(results) = run.get_mut("results").and_then(|r| r.as_array_mut()) {
618                for result in results {
619                    let uri = result
620                        .pointer("/locations/0/physicalLocation/artifactLocation/uri")
621                        .and_then(|v| v.as_str())
622                        .unwrap_or("");
623                    // Decode percent-encoded brackets before ownership lookup
624                    // (SARIF URIs encode `[`/`]` as `%5B`/`%5D`)
625                    let decoded = uri.replace("%5B", "[").replace("%5D", "]");
626                    let owner =
627                        grouping::resolve_owner(Path::new(&decoded), Path::new(""), resolver);
628                    let props = result
629                        .as_object_mut()
630                        .expect("SARIF result should be an object")
631                        .entry("properties")
632                        .or_insert_with(|| serde_json::json!({}));
633                    props
634                        .as_object_mut()
635                        .expect("properties should be an object")
636                        .insert("owner".to_string(), serde_json::Value::String(owner));
637                }
638            }
639        }
640    }
641
642    emit_json(&sarif, "SARIF")
643}
644
645#[expect(
646    clippy::cast_possible_truncation,
647    reason = "line/col numbers are bounded by source size"
648)]
649pub(super) fn print_duplication_sarif(report: &DuplicationReport, root: &Path) -> ExitCode {
650    let mut sarif_results = Vec::new();
651
652    for (i, group) in report.clone_groups.iter().enumerate() {
653        for instance in &group.instances {
654            sarif_results.push(sarif_result(
655                "fallow/code-duplication",
656                "warning",
657                &format!(
658                    "Code clone group {} ({} lines, {} instances)",
659                    i + 1,
660                    group.line_count,
661                    group.instances.len()
662                ),
663                &relative_uri(&instance.file, root),
664                Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
665            ));
666        }
667    }
668
669    let sarif = serde_json::json!({
670        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
671        "version": "2.1.0",
672        "runs": [{
673            "tool": {
674                "driver": {
675                    "name": "fallow",
676                    "version": env!("CARGO_PKG_VERSION"),
677                    "informationUri": "https://github.com/fallow-rs/fallow",
678                    "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
679                }
680            },
681            "results": sarif_results
682        }]
683    });
684
685    emit_json(&sarif, "SARIF")
686}
687
688// ── Health SARIF output ────────────────────────────────────────────
689// Note: file_scores are intentionally omitted from SARIF output.
690// SARIF is designed for diagnostic results (issues/findings), not metric tables.
691// File health scores are available in JSON, human, compact, and markdown formats.
692
693#[must_use]
694#[expect(
695    clippy::too_many_lines,
696    reason = "flat rules + results table: adding production-coverage rules pushed past the 150 line threshold but each section is a straightforward sequence of sarif_rule / sarif_result calls"
697)]
698pub fn build_health_sarif(
699    report: &crate::health_types::HealthReport,
700    root: &Path,
701) -> serde_json::Value {
702    use crate::health_types::ExceededThreshold;
703
704    let mut sarif_results = Vec::new();
705
706    for finding in &report.findings {
707        let uri = relative_uri(&finding.path, root);
708        // When CRAP contributes alongside complexity, use the CRAP rule as the
709        // most actionable identifier (CRAP combines complexity and coverage)
710        // and surface all exceeded dimensions in the message.
711        let (rule_id, message) = match finding.exceeded {
712            ExceededThreshold::Cyclomatic => (
713                "fallow/high-cyclomatic-complexity",
714                format!(
715                    "'{}' has cyclomatic complexity {} (threshold: {})",
716                    finding.name, finding.cyclomatic, report.summary.max_cyclomatic_threshold,
717                ),
718            ),
719            ExceededThreshold::Cognitive => (
720                "fallow/high-cognitive-complexity",
721                format!(
722                    "'{}' has cognitive complexity {} (threshold: {})",
723                    finding.name, finding.cognitive, report.summary.max_cognitive_threshold,
724                ),
725            ),
726            ExceededThreshold::Both => (
727                "fallow/high-complexity",
728                format!(
729                    "'{}' has cyclomatic complexity {} (threshold: {}) and cognitive complexity {} (threshold: {})",
730                    finding.name,
731                    finding.cyclomatic,
732                    report.summary.max_cyclomatic_threshold,
733                    finding.cognitive,
734                    report.summary.max_cognitive_threshold,
735                ),
736            ),
737            ExceededThreshold::Crap
738            | ExceededThreshold::CyclomaticCrap
739            | ExceededThreshold::CognitiveCrap
740            | ExceededThreshold::All => {
741                let crap = finding.crap.unwrap_or(0.0);
742                let coverage = finding
743                    .coverage_pct
744                    .map(|pct| format!(", coverage {pct:.0}%"))
745                    .unwrap_or_default();
746                (
747                    "fallow/high-crap-score",
748                    format!(
749                        "'{}' has CRAP score {:.1} (threshold: {:.1}, cyclomatic {}{})",
750                        finding.name,
751                        crap,
752                        report.summary.max_crap_threshold,
753                        finding.cyclomatic,
754                        coverage,
755                    ),
756                )
757            }
758        };
759
760        let level = match finding.severity {
761            crate::health_types::FindingSeverity::Critical => "error",
762            crate::health_types::FindingSeverity::High => "warning",
763            crate::health_types::FindingSeverity::Moderate => "note",
764        };
765        sarif_results.push(sarif_result(
766            rule_id,
767            level,
768            &message,
769            &uri,
770            Some((finding.line, finding.col + 1)),
771        ));
772    }
773
774    if let Some(ref production) = report.production_coverage {
775        append_production_coverage_sarif_results(&mut sarif_results, production, root);
776    }
777
778    // Refactoring targets as SARIF results (warning level — advisory recommendations)
779    for target in &report.targets {
780        let uri = relative_uri(&target.path, root);
781        let message = format!(
782            "[{}] {} (priority: {:.1}, efficiency: {:.1}, effort: {}, confidence: {})",
783            target.category.label(),
784            target.recommendation,
785            target.priority,
786            target.efficiency,
787            target.effort.label(),
788            target.confidence.label(),
789        );
790        sarif_results.push(sarif_result(
791            "fallow/refactoring-target",
792            "warning",
793            &message,
794            &uri,
795            None,
796        ));
797    }
798
799    if let Some(ref gaps) = report.coverage_gaps {
800        for item in &gaps.files {
801            let uri = relative_uri(&item.path, root);
802            let message = format!(
803                "File is runtime-reachable but has no test dependency path ({} value export{})",
804                item.value_export_count,
805                if item.value_export_count == 1 {
806                    ""
807                } else {
808                    "s"
809                },
810            );
811            sarif_results.push(sarif_result(
812                "fallow/untested-file",
813                "warning",
814                &message,
815                &uri,
816                None,
817            ));
818        }
819
820        for item in &gaps.exports {
821            let uri = relative_uri(&item.path, root);
822            let message = format!(
823                "Export '{}' is runtime-reachable but never referenced by test-reachable modules",
824                item.export_name
825            );
826            sarif_results.push(sarif_result(
827                "fallow/untested-export",
828                "warning",
829                &message,
830                &uri,
831                Some((item.line, item.col + 1)),
832            ));
833        }
834    }
835
836    let health_rules = vec![
837        sarif_rule(
838            "fallow/high-cyclomatic-complexity",
839            "Function has high cyclomatic complexity",
840            "note",
841        ),
842        sarif_rule(
843            "fallow/high-cognitive-complexity",
844            "Function has high cognitive complexity",
845            "note",
846        ),
847        sarif_rule(
848            "fallow/high-complexity",
849            "Function exceeds both complexity thresholds",
850            "note",
851        ),
852        sarif_rule(
853            "fallow/high-crap-score",
854            "Function has a high CRAP score (high complexity combined with low coverage)",
855            "warning",
856        ),
857        sarif_rule(
858            "fallow/refactoring-target",
859            "File identified as a high-priority refactoring candidate",
860            "warning",
861        ),
862        sarif_rule(
863            "fallow/untested-file",
864            "Runtime-reachable file has no test dependency path",
865            "warning",
866        ),
867        sarif_rule(
868            "fallow/untested-export",
869            "Runtime-reachable export has no test dependency path",
870            "warning",
871        ),
872        sarif_rule(
873            "fallow/production-safe-to-delete",
874            "Function is statically unused and was never invoked in production",
875            "warning",
876        ),
877        sarif_rule(
878            "fallow/production-review-required",
879            "Function is statically used but was never invoked in production",
880            "warning",
881        ),
882        sarif_rule(
883            "fallow/production-low-traffic",
884            "Function was invoked below the low-traffic threshold relative to total trace count",
885            "note",
886        ),
887        sarif_rule(
888            "fallow/production-coverage-unavailable",
889            "Production coverage could not be resolved for this function",
890            "note",
891        ),
892        sarif_rule(
893            "fallow/production-coverage",
894            "Production coverage finding",
895            "note",
896        ),
897    ];
898
899    serde_json::json!({
900        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
901        "version": "2.1.0",
902        "runs": [{
903            "tool": {
904                "driver": {
905                    "name": "fallow",
906                    "version": env!("CARGO_PKG_VERSION"),
907                    "informationUri": "https://github.com/fallow-rs/fallow",
908                    "rules": health_rules
909                }
910            },
911            "results": sarif_results
912        }]
913    })
914}
915
916fn append_production_coverage_sarif_results(
917    sarif_results: &mut Vec<serde_json::Value>,
918    production: &crate::health_types::ProductionCoverageReport,
919    root: &Path,
920) {
921    for finding in &production.findings {
922        let uri = relative_uri(&finding.path, root);
923        let rule_id = match finding.verdict {
924            crate::health_types::ProductionCoverageVerdict::SafeToDelete => {
925                "fallow/production-safe-to-delete"
926            }
927            crate::health_types::ProductionCoverageVerdict::ReviewRequired => {
928                "fallow/production-review-required"
929            }
930            crate::health_types::ProductionCoverageVerdict::LowTraffic => {
931                "fallow/production-low-traffic"
932            }
933            crate::health_types::ProductionCoverageVerdict::CoverageUnavailable => {
934                "fallow/production-coverage-unavailable"
935            }
936            crate::health_types::ProductionCoverageVerdict::Active
937            | crate::health_types::ProductionCoverageVerdict::Unknown => {
938                "fallow/production-coverage"
939            }
940        };
941        let level = match finding.verdict {
942            crate::health_types::ProductionCoverageVerdict::SafeToDelete
943            | crate::health_types::ProductionCoverageVerdict::ReviewRequired => "warning",
944            _ => "note",
945        };
946        let invocations_hint = finding.invocations.map_or_else(
947            || "untracked".to_owned(),
948            |hits| format!("{hits} invocations"),
949        );
950        let message = format!(
951            "'{}' production coverage verdict: {} ({})",
952            finding.function,
953            finding.verdict.human_label(),
954            invocations_hint,
955        );
956        sarif_results.push(sarif_result(
957            rule_id,
958            level,
959            &message,
960            &uri,
961            Some((finding.line, 1)),
962        ));
963    }
964}
965
966pub(super) fn print_health_sarif(
967    report: &crate::health_types::HealthReport,
968    root: &Path,
969) -> ExitCode {
970    let sarif = build_health_sarif(report, root);
971    emit_json(&sarif, "SARIF")
972}
973
974/// Print health SARIF with a per-result `properties.group` tag.
975///
976/// Mirrors the dead-code grouped SARIF pattern (`print_grouped_sarif`):
977/// build the standard SARIF first, then post-process each result to inject
978/// the resolver-derived group key on `properties.group`. Consumers that read
979/// SARIF (GitHub Code Scanning, GitLab Code Quality) can then partition
980/// findings per team / package / directory without dropping out of the
981/// SARIF pipeline. Each finding's URI is decoded (`%5B` -> `[`, `%5D` -> `]`)
982/// before resolution, matching the dead-code behaviour for paths containing
983/// brackets like Next.js dynamic routes.
984pub(super) fn print_grouped_health_sarif(
985    report: &crate::health_types::HealthReport,
986    root: &Path,
987    resolver: &OwnershipResolver,
988) -> ExitCode {
989    let mut sarif = build_health_sarif(report, root);
990
991    if let Some(runs) = sarif.get_mut("runs").and_then(|r| r.as_array_mut()) {
992        for run in runs {
993            if let Some(results) = run.get_mut("results").and_then(|r| r.as_array_mut()) {
994                for result in results {
995                    let uri = result
996                        .pointer("/locations/0/physicalLocation/artifactLocation/uri")
997                        .and_then(|v| v.as_str())
998                        .unwrap_or("");
999                    let decoded = uri.replace("%5B", "[").replace("%5D", "]");
1000                    let group =
1001                        grouping::resolve_owner(Path::new(&decoded), Path::new(""), resolver);
1002                    let props = result
1003                        .as_object_mut()
1004                        .expect("SARIF result should be an object")
1005                        .entry("properties")
1006                        .or_insert_with(|| serde_json::json!({}));
1007                    props
1008                        .as_object_mut()
1009                        .expect("properties should be an object")
1010                        .insert("group".to_string(), serde_json::Value::String(group));
1011                }
1012            }
1013        }
1014    }
1015
1016    emit_json(&sarif, "SARIF")
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use super::*;
1022    use crate::report::test_helpers::sample_results;
1023    use fallow_core::results::*;
1024    use std::path::PathBuf;
1025
1026    #[test]
1027    fn sarif_has_required_top_level_fields() {
1028        let root = PathBuf::from("/project");
1029        let results = AnalysisResults::default();
1030        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1031
1032        assert_eq!(
1033            sarif["$schema"],
1034            "https://json.schemastore.org/sarif-2.1.0.json"
1035        );
1036        assert_eq!(sarif["version"], "2.1.0");
1037        assert!(sarif["runs"].is_array());
1038    }
1039
1040    #[test]
1041    fn sarif_has_tool_driver_info() {
1042        let root = PathBuf::from("/project");
1043        let results = AnalysisResults::default();
1044        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1045
1046        let driver = &sarif["runs"][0]["tool"]["driver"];
1047        assert_eq!(driver["name"], "fallow");
1048        assert!(driver["version"].is_string());
1049        assert_eq!(
1050            driver["informationUri"],
1051            "https://github.com/fallow-rs/fallow"
1052        );
1053    }
1054
1055    #[test]
1056    fn sarif_declares_all_rules() {
1057        let root = PathBuf::from("/project");
1058        let results = AnalysisResults::default();
1059        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1060
1061        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1062            .as_array()
1063            .expect("rules should be an array");
1064        assert_eq!(rules.len(), 16);
1065
1066        let rule_ids: Vec<&str> = rules.iter().map(|r| r["id"].as_str().unwrap()).collect();
1067        assert!(rule_ids.contains(&"fallow/unused-file"));
1068        assert!(rule_ids.contains(&"fallow/unused-export"));
1069        assert!(rule_ids.contains(&"fallow/unused-type"));
1070        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1071        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1072        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1073        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1074        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1075        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1076        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1077        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1078        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1079        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1080        assert!(rule_ids.contains(&"fallow/circular-dependency"));
1081        assert!(rule_ids.contains(&"fallow/boundary-violation"));
1082    }
1083
1084    #[test]
1085    fn sarif_empty_results_no_results_entries() {
1086        let root = PathBuf::from("/project");
1087        let results = AnalysisResults::default();
1088        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1089
1090        let sarif_results = sarif["runs"][0]["results"]
1091            .as_array()
1092            .expect("results should be an array");
1093        assert!(sarif_results.is_empty());
1094    }
1095
1096    #[test]
1097    fn sarif_unused_file_result() {
1098        let root = PathBuf::from("/project");
1099        let mut results = AnalysisResults::default();
1100        results.unused_files.push(UnusedFile {
1101            path: root.join("src/dead.ts"),
1102        });
1103
1104        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1105        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1106        assert_eq!(entries.len(), 1);
1107
1108        let entry = &entries[0];
1109        assert_eq!(entry["ruleId"], "fallow/unused-file");
1110        // Default severity is "error" per RulesConfig::default()
1111        assert_eq!(entry["level"], "error");
1112        assert_eq!(
1113            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1114            "src/dead.ts"
1115        );
1116    }
1117
1118    #[test]
1119    fn sarif_unused_export_includes_region() {
1120        let root = PathBuf::from("/project");
1121        let mut results = AnalysisResults::default();
1122        results.unused_exports.push(UnusedExport {
1123            path: root.join("src/utils.ts"),
1124            export_name: "helperFn".to_string(),
1125            is_type_only: false,
1126            line: 10,
1127            col: 4,
1128            span_start: 120,
1129            is_re_export: false,
1130        });
1131
1132        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1133        let entry = &sarif["runs"][0]["results"][0];
1134        assert_eq!(entry["ruleId"], "fallow/unused-export");
1135
1136        let region = &entry["locations"][0]["physicalLocation"]["region"];
1137        assert_eq!(region["startLine"], 10);
1138        // SARIF columns are 1-based, code adds +1 to the 0-based col
1139        assert_eq!(region["startColumn"], 5);
1140    }
1141
1142    #[test]
1143    fn sarif_unresolved_import_is_error_level() {
1144        let root = PathBuf::from("/project");
1145        let mut results = AnalysisResults::default();
1146        results.unresolved_imports.push(UnresolvedImport {
1147            path: root.join("src/app.ts"),
1148            specifier: "./missing".to_string(),
1149            line: 1,
1150            col: 0,
1151            specifier_col: 0,
1152        });
1153
1154        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1155        let entry = &sarif["runs"][0]["results"][0];
1156        assert_eq!(entry["ruleId"], "fallow/unresolved-import");
1157        assert_eq!(entry["level"], "error");
1158    }
1159
1160    #[test]
1161    fn sarif_unlisted_dependency_points_to_import_site() {
1162        let root = PathBuf::from("/project");
1163        let mut results = AnalysisResults::default();
1164        results.unlisted_dependencies.push(UnlistedDependency {
1165            package_name: "chalk".to_string(),
1166            imported_from: vec![ImportSite {
1167                path: root.join("src/cli.ts"),
1168                line: 3,
1169                col: 0,
1170            }],
1171        });
1172
1173        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1174        let entry = &sarif["runs"][0]["results"][0];
1175        assert_eq!(entry["ruleId"], "fallow/unlisted-dependency");
1176        assert_eq!(entry["level"], "error");
1177        assert_eq!(
1178            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1179            "src/cli.ts"
1180        );
1181        let region = &entry["locations"][0]["physicalLocation"]["region"];
1182        assert_eq!(region["startLine"], 3);
1183        assert_eq!(region["startColumn"], 1);
1184    }
1185
1186    #[test]
1187    fn sarif_dependency_issues_point_to_package_json() {
1188        let root = PathBuf::from("/project");
1189        let mut results = AnalysisResults::default();
1190        results.unused_dependencies.push(UnusedDependency {
1191            package_name: "lodash".to_string(),
1192            location: DependencyLocation::Dependencies,
1193            path: root.join("package.json"),
1194            line: 5,
1195        });
1196        results.unused_dev_dependencies.push(UnusedDependency {
1197            package_name: "jest".to_string(),
1198            location: DependencyLocation::DevDependencies,
1199            path: root.join("package.json"),
1200            line: 5,
1201        });
1202
1203        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1204        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1205        for entry in entries {
1206            assert_eq!(
1207                entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1208                "package.json"
1209            );
1210        }
1211    }
1212
1213    #[test]
1214    fn sarif_duplicate_export_emits_one_result_per_location() {
1215        let root = PathBuf::from("/project");
1216        let mut results = AnalysisResults::default();
1217        results.duplicate_exports.push(DuplicateExport {
1218            export_name: "Config".to_string(),
1219            locations: vec![
1220                DuplicateLocation {
1221                    path: root.join("src/a.ts"),
1222                    line: 15,
1223                    col: 0,
1224                },
1225                DuplicateLocation {
1226                    path: root.join("src/b.ts"),
1227                    line: 30,
1228                    col: 0,
1229                },
1230            ],
1231        });
1232
1233        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1234        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1235        // One SARIF result per location, not one per DuplicateExport
1236        assert_eq!(entries.len(), 2);
1237        assert_eq!(entries[0]["ruleId"], "fallow/duplicate-export");
1238        assert_eq!(entries[1]["ruleId"], "fallow/duplicate-export");
1239        assert_eq!(
1240            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1241            "src/a.ts"
1242        );
1243        assert_eq!(
1244            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1245            "src/b.ts"
1246        );
1247    }
1248
1249    #[test]
1250    fn sarif_all_issue_types_produce_results() {
1251        let root = PathBuf::from("/project");
1252        let results = sample_results(&root);
1253        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1254
1255        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1256        // All issue types with one entry each; duplicate_exports has 2 locations => one extra SARIF result
1257        assert_eq!(entries.len(), results.total_issues() + 1);
1258
1259        let rule_ids: Vec<&str> = entries
1260            .iter()
1261            .map(|e| e["ruleId"].as_str().unwrap())
1262            .collect();
1263        assert!(rule_ids.contains(&"fallow/unused-file"));
1264        assert!(rule_ids.contains(&"fallow/unused-export"));
1265        assert!(rule_ids.contains(&"fallow/unused-type"));
1266        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1267        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1268        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1269        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1270        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1271        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1272        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1273        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1274        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1275        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1276    }
1277
1278    #[test]
1279    fn sarif_serializes_to_valid_json() {
1280        let root = PathBuf::from("/project");
1281        let results = sample_results(&root);
1282        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1283
1284        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1285        let reparsed: serde_json::Value =
1286            serde_json::from_str(&json_str).expect("SARIF output should be valid JSON");
1287        assert_eq!(reparsed, sarif);
1288    }
1289
1290    #[test]
1291    fn sarif_file_write_produces_valid_sarif() {
1292        let root = PathBuf::from("/project");
1293        let results = sample_results(&root);
1294        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1295        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1296
1297        let dir = std::env::temp_dir().join("fallow-test-sarif-file");
1298        let _ = std::fs::create_dir_all(&dir);
1299        let sarif_path = dir.join("results.sarif");
1300        std::fs::write(&sarif_path, &json_str).expect("should write SARIF file");
1301
1302        let contents = std::fs::read_to_string(&sarif_path).expect("should read SARIF file");
1303        let parsed: serde_json::Value =
1304            serde_json::from_str(&contents).expect("file should contain valid JSON");
1305
1306        assert_eq!(parsed["version"], "2.1.0");
1307        assert_eq!(
1308            parsed["$schema"],
1309            "https://json.schemastore.org/sarif-2.1.0.json"
1310        );
1311        let sarif_results = parsed["runs"][0]["results"]
1312            .as_array()
1313            .expect("results should be an array");
1314        assert!(!sarif_results.is_empty());
1315
1316        // Clean up
1317        let _ = std::fs::remove_file(&sarif_path);
1318        let _ = std::fs::remove_dir(&dir);
1319    }
1320
1321    // ── Health SARIF ──
1322
1323    #[test]
1324    fn health_sarif_empty_no_results() {
1325        let root = PathBuf::from("/project");
1326        let report = crate::health_types::HealthReport {
1327            summary: crate::health_types::HealthSummary {
1328                files_analyzed: 10,
1329                functions_analyzed: 50,
1330                ..Default::default()
1331            },
1332            ..Default::default()
1333        };
1334        let sarif = build_health_sarif(&report, &root);
1335        assert_eq!(sarif["version"], "2.1.0");
1336        let results = sarif["runs"][0]["results"].as_array().unwrap();
1337        assert!(results.is_empty());
1338        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1339            .as_array()
1340            .unwrap();
1341        assert_eq!(rules.len(), 12);
1342    }
1343
1344    #[test]
1345    fn health_sarif_cyclomatic_only() {
1346        let root = PathBuf::from("/project");
1347        let report = crate::health_types::HealthReport {
1348            findings: vec![crate::health_types::HealthFinding {
1349                path: root.join("src/utils.ts"),
1350                name: "parseExpression".to_string(),
1351                line: 42,
1352                col: 0,
1353                cyclomatic: 25,
1354                cognitive: 10,
1355                line_count: 80,
1356                param_count: 0,
1357                exceeded: crate::health_types::ExceededThreshold::Cyclomatic,
1358                severity: crate::health_types::FindingSeverity::High,
1359                crap: None,
1360                coverage_pct: None,
1361            }],
1362            summary: crate::health_types::HealthSummary {
1363                files_analyzed: 5,
1364                functions_analyzed: 20,
1365                functions_above_threshold: 1,
1366                ..Default::default()
1367            },
1368            ..Default::default()
1369        };
1370        let sarif = build_health_sarif(&report, &root);
1371        let entry = &sarif["runs"][0]["results"][0];
1372        assert_eq!(entry["ruleId"], "fallow/high-cyclomatic-complexity");
1373        assert_eq!(entry["level"], "warning");
1374        assert!(
1375            entry["message"]["text"]
1376                .as_str()
1377                .unwrap()
1378                .contains("cyclomatic complexity 25")
1379        );
1380        assert_eq!(
1381            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1382            "src/utils.ts"
1383        );
1384        let region = &entry["locations"][0]["physicalLocation"]["region"];
1385        assert_eq!(region["startLine"], 42);
1386        assert_eq!(region["startColumn"], 1);
1387    }
1388
1389    #[test]
1390    fn health_sarif_cognitive_only() {
1391        let root = PathBuf::from("/project");
1392        let report = crate::health_types::HealthReport {
1393            findings: vec![crate::health_types::HealthFinding {
1394                path: root.join("src/api.ts"),
1395                name: "handleRequest".to_string(),
1396                line: 10,
1397                col: 4,
1398                cyclomatic: 8,
1399                cognitive: 20,
1400                line_count: 40,
1401                param_count: 0,
1402                exceeded: crate::health_types::ExceededThreshold::Cognitive,
1403                severity: crate::health_types::FindingSeverity::High,
1404                crap: None,
1405                coverage_pct: None,
1406            }],
1407            summary: crate::health_types::HealthSummary {
1408                files_analyzed: 3,
1409                functions_analyzed: 10,
1410                functions_above_threshold: 1,
1411                ..Default::default()
1412            },
1413            ..Default::default()
1414        };
1415        let sarif = build_health_sarif(&report, &root);
1416        let entry = &sarif["runs"][0]["results"][0];
1417        assert_eq!(entry["ruleId"], "fallow/high-cognitive-complexity");
1418        assert!(
1419            entry["message"]["text"]
1420                .as_str()
1421                .unwrap()
1422                .contains("cognitive complexity 20")
1423        );
1424        let region = &entry["locations"][0]["physicalLocation"]["region"];
1425        assert_eq!(region["startColumn"], 5); // col 4 + 1
1426    }
1427
1428    #[test]
1429    fn health_sarif_both_thresholds() {
1430        let root = PathBuf::from("/project");
1431        let report = crate::health_types::HealthReport {
1432            findings: vec![crate::health_types::HealthFinding {
1433                path: root.join("src/complex.ts"),
1434                name: "doEverything".to_string(),
1435                line: 1,
1436                col: 0,
1437                cyclomatic: 30,
1438                cognitive: 45,
1439                line_count: 100,
1440                param_count: 0,
1441                exceeded: crate::health_types::ExceededThreshold::Both,
1442                severity: crate::health_types::FindingSeverity::High,
1443                crap: None,
1444                coverage_pct: None,
1445            }],
1446            summary: crate::health_types::HealthSummary {
1447                files_analyzed: 1,
1448                functions_analyzed: 1,
1449                functions_above_threshold: 1,
1450                ..Default::default()
1451            },
1452            ..Default::default()
1453        };
1454        let sarif = build_health_sarif(&report, &root);
1455        let entry = &sarif["runs"][0]["results"][0];
1456        assert_eq!(entry["ruleId"], "fallow/high-complexity");
1457        let msg = entry["message"]["text"].as_str().unwrap();
1458        assert!(msg.contains("cyclomatic complexity 30"));
1459        assert!(msg.contains("cognitive complexity 45"));
1460    }
1461
1462    #[test]
1463    fn health_sarif_crap_only_emits_crap_rule() {
1464        // CRAP-only: cyclomatic + cognitive below their thresholds, CRAP at or
1465        // above the CRAP threshold. Rule must be `fallow/high-crap-score`.
1466        let root = PathBuf::from("/project");
1467        let report = crate::health_types::HealthReport {
1468            findings: vec![crate::health_types::HealthFinding {
1469                path: root.join("src/untested.ts"),
1470                name: "risky".to_string(),
1471                line: 8,
1472                col: 0,
1473                cyclomatic: 10,
1474                cognitive: 10,
1475                line_count: 20,
1476                param_count: 1,
1477                exceeded: crate::health_types::ExceededThreshold::Crap,
1478                severity: crate::health_types::FindingSeverity::High,
1479                crap: Some(82.2),
1480                coverage_pct: Some(12.0),
1481            }],
1482            summary: crate::health_types::HealthSummary {
1483                files_analyzed: 1,
1484                functions_analyzed: 1,
1485                functions_above_threshold: 1,
1486                ..Default::default()
1487            },
1488            ..Default::default()
1489        };
1490        let sarif = build_health_sarif(&report, &root);
1491        let entry = &sarif["runs"][0]["results"][0];
1492        assert_eq!(entry["ruleId"], "fallow/high-crap-score");
1493        let msg = entry["message"]["text"].as_str().unwrap();
1494        assert!(msg.contains("CRAP score 82.2"), "msg: {msg}");
1495        assert!(msg.contains("coverage 12%"), "msg: {msg}");
1496    }
1497
1498    #[test]
1499    fn health_sarif_cyclomatic_crap_uses_crap_rule() {
1500        // Cyclomatic + CRAP both exceeded. The CRAP-centric rule subsumes
1501        // the cyclomatic breach; only one SARIF result is emitted.
1502        let root = PathBuf::from("/project");
1503        let report = crate::health_types::HealthReport {
1504            findings: vec![crate::health_types::HealthFinding {
1505                path: root.join("src/hot.ts"),
1506                name: "branchy".to_string(),
1507                line: 1,
1508                col: 0,
1509                cyclomatic: 67,
1510                cognitive: 12,
1511                line_count: 80,
1512                param_count: 1,
1513                exceeded: crate::health_types::ExceededThreshold::CyclomaticCrap,
1514                severity: crate::health_types::FindingSeverity::Critical,
1515                crap: Some(182.0),
1516                coverage_pct: None,
1517            }],
1518            summary: crate::health_types::HealthSummary {
1519                files_analyzed: 1,
1520                functions_analyzed: 1,
1521                functions_above_threshold: 1,
1522                ..Default::default()
1523            },
1524            ..Default::default()
1525        };
1526        let sarif = build_health_sarif(&report, &root);
1527        let results = sarif["runs"][0]["results"].as_array().unwrap();
1528        assert_eq!(
1529            results.len(),
1530            1,
1531            "CyclomaticCrap should emit a single SARIF result under the CRAP rule"
1532        );
1533        assert_eq!(results[0]["ruleId"], "fallow/high-crap-score");
1534        let msg = results[0]["message"]["text"].as_str().unwrap();
1535        assert!(msg.contains("CRAP score 182"), "msg: {msg}");
1536        // coverage_pct absent => no coverage suffix
1537        assert!(!msg.contains("coverage"), "msg: {msg}");
1538    }
1539
1540    // ── Severity mapping ──
1541
1542    #[test]
1543    fn severity_to_sarif_level_error() {
1544        assert_eq!(severity_to_sarif_level(Severity::Error), "error");
1545    }
1546
1547    #[test]
1548    fn severity_to_sarif_level_warn() {
1549        assert_eq!(severity_to_sarif_level(Severity::Warn), "warning");
1550    }
1551
1552    #[test]
1553    fn severity_to_sarif_level_off() {
1554        assert_eq!(severity_to_sarif_level(Severity::Off), "warning");
1555    }
1556
1557    // ── Re-export properties ──
1558
1559    #[test]
1560    fn sarif_re_export_has_properties() {
1561        let root = PathBuf::from("/project");
1562        let mut results = AnalysisResults::default();
1563        results.unused_exports.push(UnusedExport {
1564            path: root.join("src/index.ts"),
1565            export_name: "reExported".to_string(),
1566            is_type_only: false,
1567            line: 1,
1568            col: 0,
1569            span_start: 0,
1570            is_re_export: true,
1571        });
1572
1573        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1574        let entry = &sarif["runs"][0]["results"][0];
1575        assert_eq!(entry["properties"]["is_re_export"], true);
1576        let msg = entry["message"]["text"].as_str().unwrap();
1577        assert!(msg.starts_with("Re-export"));
1578    }
1579
1580    #[test]
1581    fn sarif_non_re_export_has_no_properties() {
1582        let root = PathBuf::from("/project");
1583        let mut results = AnalysisResults::default();
1584        results.unused_exports.push(UnusedExport {
1585            path: root.join("src/utils.ts"),
1586            export_name: "foo".to_string(),
1587            is_type_only: false,
1588            line: 5,
1589            col: 0,
1590            span_start: 0,
1591            is_re_export: false,
1592        });
1593
1594        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1595        let entry = &sarif["runs"][0]["results"][0];
1596        assert!(entry.get("properties").is_none());
1597        let msg = entry["message"]["text"].as_str().unwrap();
1598        assert!(msg.starts_with("Export"));
1599    }
1600
1601    // ── Type re-export ──
1602
1603    #[test]
1604    fn sarif_type_re_export_message() {
1605        let root = PathBuf::from("/project");
1606        let mut results = AnalysisResults::default();
1607        results.unused_types.push(UnusedExport {
1608            path: root.join("src/index.ts"),
1609            export_name: "MyType".to_string(),
1610            is_type_only: true,
1611            line: 1,
1612            col: 0,
1613            span_start: 0,
1614            is_re_export: true,
1615        });
1616
1617        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1618        let entry = &sarif["runs"][0]["results"][0];
1619        assert_eq!(entry["ruleId"], "fallow/unused-type");
1620        let msg = entry["message"]["text"].as_str().unwrap();
1621        assert!(msg.starts_with("Type re-export"));
1622        assert_eq!(entry["properties"]["is_re_export"], true);
1623    }
1624
1625    // ── Dependency line == 0 skips region ──
1626
1627    #[test]
1628    fn sarif_dependency_line_zero_skips_region() {
1629        let root = PathBuf::from("/project");
1630        let mut results = AnalysisResults::default();
1631        results.unused_dependencies.push(UnusedDependency {
1632            package_name: "lodash".to_string(),
1633            location: DependencyLocation::Dependencies,
1634            path: root.join("package.json"),
1635            line: 0,
1636        });
1637
1638        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1639        let entry = &sarif["runs"][0]["results"][0];
1640        let phys = &entry["locations"][0]["physicalLocation"];
1641        assert!(phys.get("region").is_none());
1642    }
1643
1644    #[test]
1645    fn sarif_dependency_line_nonzero_has_region() {
1646        let root = PathBuf::from("/project");
1647        let mut results = AnalysisResults::default();
1648        results.unused_dependencies.push(UnusedDependency {
1649            package_name: "lodash".to_string(),
1650            location: DependencyLocation::Dependencies,
1651            path: root.join("package.json"),
1652            line: 7,
1653        });
1654
1655        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1656        let entry = &sarif["runs"][0]["results"][0];
1657        let region = &entry["locations"][0]["physicalLocation"]["region"];
1658        assert_eq!(region["startLine"], 7);
1659        assert_eq!(region["startColumn"], 1);
1660    }
1661
1662    // ── Type-only dependency line == 0 skips region ──
1663
1664    #[test]
1665    fn sarif_type_only_dep_line_zero_skips_region() {
1666        let root = PathBuf::from("/project");
1667        let mut results = AnalysisResults::default();
1668        results.type_only_dependencies.push(TypeOnlyDependency {
1669            package_name: "zod".to_string(),
1670            path: root.join("package.json"),
1671            line: 0,
1672        });
1673
1674        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1675        let entry = &sarif["runs"][0]["results"][0];
1676        let phys = &entry["locations"][0]["physicalLocation"];
1677        assert!(phys.get("region").is_none());
1678    }
1679
1680    // ── Circular dependency line == 0 skips region ──
1681
1682    #[test]
1683    fn sarif_circular_dep_line_zero_skips_region() {
1684        let root = PathBuf::from("/project");
1685        let mut results = AnalysisResults::default();
1686        results.circular_dependencies.push(CircularDependency {
1687            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1688            length: 2,
1689            line: 0,
1690            col: 0,
1691            is_cross_package: false,
1692        });
1693
1694        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1695        let entry = &sarif["runs"][0]["results"][0];
1696        let phys = &entry["locations"][0]["physicalLocation"];
1697        assert!(phys.get("region").is_none());
1698    }
1699
1700    #[test]
1701    fn sarif_circular_dep_line_nonzero_has_region() {
1702        let root = PathBuf::from("/project");
1703        let mut results = AnalysisResults::default();
1704        results.circular_dependencies.push(CircularDependency {
1705            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1706            length: 2,
1707            line: 5,
1708            col: 2,
1709            is_cross_package: false,
1710        });
1711
1712        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1713        let entry = &sarif["runs"][0]["results"][0];
1714        let region = &entry["locations"][0]["physicalLocation"]["region"];
1715        assert_eq!(region["startLine"], 5);
1716        assert_eq!(region["startColumn"], 3);
1717    }
1718
1719    // ── Unused optional dependency ──
1720
1721    #[test]
1722    fn sarif_unused_optional_dependency_result() {
1723        let root = PathBuf::from("/project");
1724        let mut results = AnalysisResults::default();
1725        results.unused_optional_dependencies.push(UnusedDependency {
1726            package_name: "fsevents".to_string(),
1727            location: DependencyLocation::OptionalDependencies,
1728            path: root.join("package.json"),
1729            line: 12,
1730        });
1731
1732        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1733        let entry = &sarif["runs"][0]["results"][0];
1734        assert_eq!(entry["ruleId"], "fallow/unused-optional-dependency");
1735        let msg = entry["message"]["text"].as_str().unwrap();
1736        assert!(msg.contains("optionalDependencies"));
1737    }
1738
1739    // ── Enum and class member SARIF messages ──
1740
1741    #[test]
1742    fn sarif_enum_member_message_format() {
1743        let root = PathBuf::from("/project");
1744        let mut results = AnalysisResults::default();
1745        results
1746            .unused_enum_members
1747            .push(fallow_core::results::UnusedMember {
1748                path: root.join("src/enums.ts"),
1749                parent_name: "Color".to_string(),
1750                member_name: "Purple".to_string(),
1751                kind: fallow_core::extract::MemberKind::EnumMember,
1752                line: 5,
1753                col: 2,
1754            });
1755
1756        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1757        let entry = &sarif["runs"][0]["results"][0];
1758        assert_eq!(entry["ruleId"], "fallow/unused-enum-member");
1759        let msg = entry["message"]["text"].as_str().unwrap();
1760        assert!(msg.contains("Enum member 'Color.Purple'"));
1761        let region = &entry["locations"][0]["physicalLocation"]["region"];
1762        assert_eq!(region["startColumn"], 3); // col 2 + 1
1763    }
1764
1765    #[test]
1766    fn sarif_class_member_message_format() {
1767        let root = PathBuf::from("/project");
1768        let mut results = AnalysisResults::default();
1769        results
1770            .unused_class_members
1771            .push(fallow_core::results::UnusedMember {
1772                path: root.join("src/service.ts"),
1773                parent_name: "API".to_string(),
1774                member_name: "fetch".to_string(),
1775                kind: fallow_core::extract::MemberKind::ClassMethod,
1776                line: 10,
1777                col: 4,
1778            });
1779
1780        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1781        let entry = &sarif["runs"][0]["results"][0];
1782        assert_eq!(entry["ruleId"], "fallow/unused-class-member");
1783        let msg = entry["message"]["text"].as_str().unwrap();
1784        assert!(msg.contains("Class member 'API.fetch'"));
1785    }
1786
1787    // ── Duplication SARIF ──
1788
1789    #[test]
1790    #[expect(
1791        clippy::cast_possible_truncation,
1792        reason = "test line/col values are trivially small"
1793    )]
1794    fn duplication_sarif_structure() {
1795        use fallow_core::duplicates::*;
1796
1797        let root = PathBuf::from("/project");
1798        let report = DuplicationReport {
1799            clone_groups: vec![CloneGroup {
1800                instances: vec![
1801                    CloneInstance {
1802                        file: root.join("src/a.ts"),
1803                        start_line: 1,
1804                        end_line: 10,
1805                        start_col: 0,
1806                        end_col: 0,
1807                        fragment: String::new(),
1808                    },
1809                    CloneInstance {
1810                        file: root.join("src/b.ts"),
1811                        start_line: 5,
1812                        end_line: 14,
1813                        start_col: 2,
1814                        end_col: 0,
1815                        fragment: String::new(),
1816                    },
1817                ],
1818                token_count: 50,
1819                line_count: 10,
1820            }],
1821            clone_families: vec![],
1822            mirrored_directories: vec![],
1823            stats: DuplicationStats::default(),
1824        };
1825
1826        let sarif = serde_json::json!({
1827            "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1828            "version": "2.1.0",
1829            "runs": [{
1830                "tool": {
1831                    "driver": {
1832                        "name": "fallow",
1833                        "version": env!("CARGO_PKG_VERSION"),
1834                        "informationUri": "https://github.com/fallow-rs/fallow",
1835                        "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
1836                    }
1837                },
1838                "results": []
1839            }]
1840        });
1841        // Just verify the function doesn't panic and produces expected structure
1842        let _ = sarif;
1843
1844        // Test the actual build path through print_duplication_sarif internals
1845        let mut sarif_results = Vec::new();
1846        for (i, group) in report.clone_groups.iter().enumerate() {
1847            for instance in &group.instances {
1848                sarif_results.push(sarif_result(
1849                    "fallow/code-duplication",
1850                    "warning",
1851                    &format!(
1852                        "Code clone group {} ({} lines, {} instances)",
1853                        i + 1,
1854                        group.line_count,
1855                        group.instances.len()
1856                    ),
1857                    &super::super::relative_uri(&instance.file, &root),
1858                    Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
1859                ));
1860            }
1861        }
1862        assert_eq!(sarif_results.len(), 2);
1863        assert_eq!(sarif_results[0]["ruleId"], "fallow/code-duplication");
1864        assert!(
1865            sarif_results[0]["message"]["text"]
1866                .as_str()
1867                .unwrap()
1868                .contains("10 lines")
1869        );
1870        let region0 = &sarif_results[0]["locations"][0]["physicalLocation"]["region"];
1871        assert_eq!(region0["startLine"], 1);
1872        assert_eq!(region0["startColumn"], 1); // start_col 0 + 1
1873        let region1 = &sarif_results[1]["locations"][0]["physicalLocation"]["region"];
1874        assert_eq!(region1["startLine"], 5);
1875        assert_eq!(region1["startColumn"], 3); // start_col 2 + 1
1876    }
1877
1878    // ── sarif_rule fallback (unknown rule ID) ──
1879
1880    #[test]
1881    fn sarif_rule_known_id_has_full_description() {
1882        let rule = sarif_rule("fallow/unused-file", "fallback text", "error");
1883        assert!(rule.get("fullDescription").is_some());
1884        assert!(rule.get("helpUri").is_some());
1885    }
1886
1887    #[test]
1888    fn sarif_rule_unknown_id_uses_fallback() {
1889        let rule = sarif_rule("fallow/nonexistent", "fallback text", "warning");
1890        assert_eq!(rule["shortDescription"]["text"], "fallback text");
1891        assert!(rule.get("fullDescription").is_none());
1892        assert!(rule.get("helpUri").is_none());
1893        assert_eq!(rule["defaultConfiguration"]["level"], "warning");
1894    }
1895
1896    // ── sarif_result without region ──
1897
1898    #[test]
1899    fn sarif_result_no_region_omits_region_key() {
1900        let result = sarif_result("rule/test", "error", "test msg", "src/file.ts", None);
1901        let phys = &result["locations"][0]["physicalLocation"];
1902        assert!(phys.get("region").is_none());
1903        assert_eq!(phys["artifactLocation"]["uri"], "src/file.ts");
1904    }
1905
1906    #[test]
1907    fn sarif_result_with_region_includes_region() {
1908        let result = sarif_result(
1909            "rule/test",
1910            "error",
1911            "test msg",
1912            "src/file.ts",
1913            Some((10, 5)),
1914        );
1915        let region = &result["locations"][0]["physicalLocation"]["region"];
1916        assert_eq!(region["startLine"], 10);
1917        assert_eq!(region["startColumn"], 5);
1918    }
1919
1920    // ── Health SARIF refactoring targets ──
1921
1922    #[test]
1923    fn health_sarif_includes_refactoring_targets() {
1924        use crate::health_types::*;
1925
1926        let root = PathBuf::from("/project");
1927        let report = HealthReport {
1928            summary: HealthSummary {
1929                files_analyzed: 10,
1930                functions_analyzed: 50,
1931                ..Default::default()
1932            },
1933            targets: vec![RefactoringTarget {
1934                path: root.join("src/complex.ts"),
1935                priority: 85.0,
1936                efficiency: 42.5,
1937                recommendation: "Split high-impact file".into(),
1938                category: RecommendationCategory::SplitHighImpact,
1939                effort: EffortEstimate::Medium,
1940                confidence: Confidence::High,
1941                factors: vec![],
1942                evidence: None,
1943            }],
1944            ..Default::default()
1945        };
1946
1947        let sarif = build_health_sarif(&report, &root);
1948        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1949        assert_eq!(entries.len(), 1);
1950        assert_eq!(entries[0]["ruleId"], "fallow/refactoring-target");
1951        assert_eq!(entries[0]["level"], "warning");
1952        let msg = entries[0]["message"]["text"].as_str().unwrap();
1953        assert!(msg.contains("high impact"));
1954        assert!(msg.contains("Split high-impact file"));
1955        assert!(msg.contains("42.5"));
1956    }
1957
1958    #[test]
1959    fn health_sarif_includes_coverage_gaps() {
1960        use crate::health_types::*;
1961
1962        let root = PathBuf::from("/project");
1963        let report = HealthReport {
1964            summary: HealthSummary {
1965                files_analyzed: 10,
1966                functions_analyzed: 50,
1967                ..Default::default()
1968            },
1969            coverage_gaps: Some(CoverageGaps {
1970                summary: CoverageGapSummary {
1971                    runtime_files: 2,
1972                    covered_files: 0,
1973                    file_coverage_pct: 0.0,
1974                    untested_files: 1,
1975                    untested_exports: 1,
1976                },
1977                files: vec![UntestedFile {
1978                    path: root.join("src/app.ts"),
1979                    value_export_count: 2,
1980                }],
1981                exports: vec![UntestedExport {
1982                    path: root.join("src/app.ts"),
1983                    export_name: "loader".into(),
1984                    line: 12,
1985                    col: 4,
1986                }],
1987            }),
1988            ..Default::default()
1989        };
1990
1991        let sarif = build_health_sarif(&report, &root);
1992        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1993        assert_eq!(entries.len(), 2);
1994        assert_eq!(entries[0]["ruleId"], "fallow/untested-file");
1995        assert_eq!(
1996            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1997            "src/app.ts"
1998        );
1999        assert!(
2000            entries[0]["message"]["text"]
2001                .as_str()
2002                .unwrap()
2003                .contains("2 value exports")
2004        );
2005        assert_eq!(entries[1]["ruleId"], "fallow/untested-export");
2006        assert_eq!(
2007            entries[1]["locations"][0]["physicalLocation"]["region"]["startLine"],
2008            12
2009        );
2010        assert_eq!(
2011            entries[1]["locations"][0]["physicalLocation"]["region"]["startColumn"],
2012            5
2013        );
2014    }
2015
2016    // ── Health SARIF rules include fullDescription from explain module ──
2017
2018    #[test]
2019    fn health_sarif_rules_have_full_descriptions() {
2020        let root = PathBuf::from("/project");
2021        let report = crate::health_types::HealthReport::default();
2022        let sarif = build_health_sarif(&report, &root);
2023        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
2024            .as_array()
2025            .unwrap();
2026        for rule in rules {
2027            let id = rule["id"].as_str().unwrap();
2028            assert!(
2029                rule.get("fullDescription").is_some(),
2030                "health rule {id} should have fullDescription"
2031            );
2032            assert!(
2033                rule.get("helpUri").is_some(),
2034                "health rule {id} should have helpUri"
2035            );
2036        }
2037    }
2038
2039    // ── Warn severity propagates correctly ──
2040
2041    #[test]
2042    fn sarif_warn_severity_produces_warning_level() {
2043        let root = PathBuf::from("/project");
2044        let mut results = AnalysisResults::default();
2045        results.unused_files.push(UnusedFile {
2046            path: root.join("src/dead.ts"),
2047        });
2048
2049        let rules = RulesConfig {
2050            unused_files: Severity::Warn,
2051            ..RulesConfig::default()
2052        };
2053
2054        let sarif = build_sarif(&results, &root, &rules);
2055        let entry = &sarif["runs"][0]["results"][0];
2056        assert_eq!(entry["level"], "warning");
2057    }
2058
2059    // ── Unused file has no region ──
2060
2061    #[test]
2062    fn sarif_unused_file_has_no_region() {
2063        let root = PathBuf::from("/project");
2064        let mut results = AnalysisResults::default();
2065        results.unused_files.push(UnusedFile {
2066            path: root.join("src/dead.ts"),
2067        });
2068
2069        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2070        let entry = &sarif["runs"][0]["results"][0];
2071        let phys = &entry["locations"][0]["physicalLocation"];
2072        assert!(phys.get("region").is_none());
2073    }
2074
2075    // ── Multiple unlisted deps with multiple import sites ──
2076
2077    #[test]
2078    fn sarif_unlisted_dep_multiple_import_sites() {
2079        let root = PathBuf::from("/project");
2080        let mut results = AnalysisResults::default();
2081        results.unlisted_dependencies.push(UnlistedDependency {
2082            package_name: "dotenv".to_string(),
2083            imported_from: vec![
2084                ImportSite {
2085                    path: root.join("src/a.ts"),
2086                    line: 1,
2087                    col: 0,
2088                },
2089                ImportSite {
2090                    path: root.join("src/b.ts"),
2091                    line: 5,
2092                    col: 0,
2093                },
2094            ],
2095        });
2096
2097        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2098        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2099        // One SARIF result per import site
2100        assert_eq!(entries.len(), 2);
2101        assert_eq!(
2102            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2103            "src/a.ts"
2104        );
2105        assert_eq!(
2106            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2107            "src/b.ts"
2108        );
2109    }
2110
2111    // ── Empty unlisted dep (no import sites) produces zero results ──
2112
2113    #[test]
2114    fn sarif_unlisted_dep_no_import_sites() {
2115        let root = PathBuf::from("/project");
2116        let mut results = AnalysisResults::default();
2117        results.unlisted_dependencies.push(UnlistedDependency {
2118            package_name: "phantom".to_string(),
2119            imported_from: vec![],
2120        });
2121
2122        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2123        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2124        // No import sites => no SARIF results for this unlisted dep
2125        assert!(entries.is_empty());
2126    }
2127}