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#[cfg(test)]
975mod tests {
976    use super::*;
977    use crate::report::test_helpers::sample_results;
978    use fallow_core::results::*;
979    use std::path::PathBuf;
980
981    #[test]
982    fn sarif_has_required_top_level_fields() {
983        let root = PathBuf::from("/project");
984        let results = AnalysisResults::default();
985        let sarif = build_sarif(&results, &root, &RulesConfig::default());
986
987        assert_eq!(
988            sarif["$schema"],
989            "https://json.schemastore.org/sarif-2.1.0.json"
990        );
991        assert_eq!(sarif["version"], "2.1.0");
992        assert!(sarif["runs"].is_array());
993    }
994
995    #[test]
996    fn sarif_has_tool_driver_info() {
997        let root = PathBuf::from("/project");
998        let results = AnalysisResults::default();
999        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1000
1001        let driver = &sarif["runs"][0]["tool"]["driver"];
1002        assert_eq!(driver["name"], "fallow");
1003        assert!(driver["version"].is_string());
1004        assert_eq!(
1005            driver["informationUri"],
1006            "https://github.com/fallow-rs/fallow"
1007        );
1008    }
1009
1010    #[test]
1011    fn sarif_declares_all_rules() {
1012        let root = PathBuf::from("/project");
1013        let results = AnalysisResults::default();
1014        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1015
1016        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1017            .as_array()
1018            .expect("rules should be an array");
1019        assert_eq!(rules.len(), 16);
1020
1021        let rule_ids: Vec<&str> = rules.iter().map(|r| r["id"].as_str().unwrap()).collect();
1022        assert!(rule_ids.contains(&"fallow/unused-file"));
1023        assert!(rule_ids.contains(&"fallow/unused-export"));
1024        assert!(rule_ids.contains(&"fallow/unused-type"));
1025        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1026        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1027        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1028        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1029        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1030        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1031        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1032        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1033        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1034        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1035        assert!(rule_ids.contains(&"fallow/circular-dependency"));
1036        assert!(rule_ids.contains(&"fallow/boundary-violation"));
1037    }
1038
1039    #[test]
1040    fn sarif_empty_results_no_results_entries() {
1041        let root = PathBuf::from("/project");
1042        let results = AnalysisResults::default();
1043        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1044
1045        let sarif_results = sarif["runs"][0]["results"]
1046            .as_array()
1047            .expect("results should be an array");
1048        assert!(sarif_results.is_empty());
1049    }
1050
1051    #[test]
1052    fn sarif_unused_file_result() {
1053        let root = PathBuf::from("/project");
1054        let mut results = AnalysisResults::default();
1055        results.unused_files.push(UnusedFile {
1056            path: root.join("src/dead.ts"),
1057        });
1058
1059        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1060        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1061        assert_eq!(entries.len(), 1);
1062
1063        let entry = &entries[0];
1064        assert_eq!(entry["ruleId"], "fallow/unused-file");
1065        // Default severity is "error" per RulesConfig::default()
1066        assert_eq!(entry["level"], "error");
1067        assert_eq!(
1068            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1069            "src/dead.ts"
1070        );
1071    }
1072
1073    #[test]
1074    fn sarif_unused_export_includes_region() {
1075        let root = PathBuf::from("/project");
1076        let mut results = AnalysisResults::default();
1077        results.unused_exports.push(UnusedExport {
1078            path: root.join("src/utils.ts"),
1079            export_name: "helperFn".to_string(),
1080            is_type_only: false,
1081            line: 10,
1082            col: 4,
1083            span_start: 120,
1084            is_re_export: false,
1085        });
1086
1087        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1088        let entry = &sarif["runs"][0]["results"][0];
1089        assert_eq!(entry["ruleId"], "fallow/unused-export");
1090
1091        let region = &entry["locations"][0]["physicalLocation"]["region"];
1092        assert_eq!(region["startLine"], 10);
1093        // SARIF columns are 1-based, code adds +1 to the 0-based col
1094        assert_eq!(region["startColumn"], 5);
1095    }
1096
1097    #[test]
1098    fn sarif_unresolved_import_is_error_level() {
1099        let root = PathBuf::from("/project");
1100        let mut results = AnalysisResults::default();
1101        results.unresolved_imports.push(UnresolvedImport {
1102            path: root.join("src/app.ts"),
1103            specifier: "./missing".to_string(),
1104            line: 1,
1105            col: 0,
1106            specifier_col: 0,
1107        });
1108
1109        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1110        let entry = &sarif["runs"][0]["results"][0];
1111        assert_eq!(entry["ruleId"], "fallow/unresolved-import");
1112        assert_eq!(entry["level"], "error");
1113    }
1114
1115    #[test]
1116    fn sarif_unlisted_dependency_points_to_import_site() {
1117        let root = PathBuf::from("/project");
1118        let mut results = AnalysisResults::default();
1119        results.unlisted_dependencies.push(UnlistedDependency {
1120            package_name: "chalk".to_string(),
1121            imported_from: vec![ImportSite {
1122                path: root.join("src/cli.ts"),
1123                line: 3,
1124                col: 0,
1125            }],
1126        });
1127
1128        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1129        let entry = &sarif["runs"][0]["results"][0];
1130        assert_eq!(entry["ruleId"], "fallow/unlisted-dependency");
1131        assert_eq!(entry["level"], "error");
1132        assert_eq!(
1133            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1134            "src/cli.ts"
1135        );
1136        let region = &entry["locations"][0]["physicalLocation"]["region"];
1137        assert_eq!(region["startLine"], 3);
1138        assert_eq!(region["startColumn"], 1);
1139    }
1140
1141    #[test]
1142    fn sarif_dependency_issues_point_to_package_json() {
1143        let root = PathBuf::from("/project");
1144        let mut results = AnalysisResults::default();
1145        results.unused_dependencies.push(UnusedDependency {
1146            package_name: "lodash".to_string(),
1147            location: DependencyLocation::Dependencies,
1148            path: root.join("package.json"),
1149            line: 5,
1150        });
1151        results.unused_dev_dependencies.push(UnusedDependency {
1152            package_name: "jest".to_string(),
1153            location: DependencyLocation::DevDependencies,
1154            path: root.join("package.json"),
1155            line: 5,
1156        });
1157
1158        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1159        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1160        for entry in entries {
1161            assert_eq!(
1162                entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1163                "package.json"
1164            );
1165        }
1166    }
1167
1168    #[test]
1169    fn sarif_duplicate_export_emits_one_result_per_location() {
1170        let root = PathBuf::from("/project");
1171        let mut results = AnalysisResults::default();
1172        results.duplicate_exports.push(DuplicateExport {
1173            export_name: "Config".to_string(),
1174            locations: vec![
1175                DuplicateLocation {
1176                    path: root.join("src/a.ts"),
1177                    line: 15,
1178                    col: 0,
1179                },
1180                DuplicateLocation {
1181                    path: root.join("src/b.ts"),
1182                    line: 30,
1183                    col: 0,
1184                },
1185            ],
1186        });
1187
1188        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1189        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1190        // One SARIF result per location, not one per DuplicateExport
1191        assert_eq!(entries.len(), 2);
1192        assert_eq!(entries[0]["ruleId"], "fallow/duplicate-export");
1193        assert_eq!(entries[1]["ruleId"], "fallow/duplicate-export");
1194        assert_eq!(
1195            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1196            "src/a.ts"
1197        );
1198        assert_eq!(
1199            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1200            "src/b.ts"
1201        );
1202    }
1203
1204    #[test]
1205    fn sarif_all_issue_types_produce_results() {
1206        let root = PathBuf::from("/project");
1207        let results = sample_results(&root);
1208        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1209
1210        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1211        // All issue types with one entry each; duplicate_exports has 2 locations => one extra SARIF result
1212        assert_eq!(entries.len(), results.total_issues() + 1);
1213
1214        let rule_ids: Vec<&str> = entries
1215            .iter()
1216            .map(|e| e["ruleId"].as_str().unwrap())
1217            .collect();
1218        assert!(rule_ids.contains(&"fallow/unused-file"));
1219        assert!(rule_ids.contains(&"fallow/unused-export"));
1220        assert!(rule_ids.contains(&"fallow/unused-type"));
1221        assert!(rule_ids.contains(&"fallow/unused-dependency"));
1222        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
1223        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
1224        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
1225        assert!(rule_ids.contains(&"fallow/test-only-dependency"));
1226        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
1227        assert!(rule_ids.contains(&"fallow/unused-class-member"));
1228        assert!(rule_ids.contains(&"fallow/unresolved-import"));
1229        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
1230        assert!(rule_ids.contains(&"fallow/duplicate-export"));
1231    }
1232
1233    #[test]
1234    fn sarif_serializes_to_valid_json() {
1235        let root = PathBuf::from("/project");
1236        let results = sample_results(&root);
1237        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1238
1239        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1240        let reparsed: serde_json::Value =
1241            serde_json::from_str(&json_str).expect("SARIF output should be valid JSON");
1242        assert_eq!(reparsed, sarif);
1243    }
1244
1245    #[test]
1246    fn sarif_file_write_produces_valid_sarif() {
1247        let root = PathBuf::from("/project");
1248        let results = sample_results(&root);
1249        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1250        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
1251
1252        let dir = std::env::temp_dir().join("fallow-test-sarif-file");
1253        let _ = std::fs::create_dir_all(&dir);
1254        let sarif_path = dir.join("results.sarif");
1255        std::fs::write(&sarif_path, &json_str).expect("should write SARIF file");
1256
1257        let contents = std::fs::read_to_string(&sarif_path).expect("should read SARIF file");
1258        let parsed: serde_json::Value =
1259            serde_json::from_str(&contents).expect("file should contain valid JSON");
1260
1261        assert_eq!(parsed["version"], "2.1.0");
1262        assert_eq!(
1263            parsed["$schema"],
1264            "https://json.schemastore.org/sarif-2.1.0.json"
1265        );
1266        let sarif_results = parsed["runs"][0]["results"]
1267            .as_array()
1268            .expect("results should be an array");
1269        assert!(!sarif_results.is_empty());
1270
1271        // Clean up
1272        let _ = std::fs::remove_file(&sarif_path);
1273        let _ = std::fs::remove_dir(&dir);
1274    }
1275
1276    // ── Health SARIF ──
1277
1278    #[test]
1279    fn health_sarif_empty_no_results() {
1280        let root = PathBuf::from("/project");
1281        let report = crate::health_types::HealthReport {
1282            summary: crate::health_types::HealthSummary {
1283                files_analyzed: 10,
1284                functions_analyzed: 50,
1285                ..Default::default()
1286            },
1287            ..Default::default()
1288        };
1289        let sarif = build_health_sarif(&report, &root);
1290        assert_eq!(sarif["version"], "2.1.0");
1291        let results = sarif["runs"][0]["results"].as_array().unwrap();
1292        assert!(results.is_empty());
1293        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1294            .as_array()
1295            .unwrap();
1296        assert_eq!(rules.len(), 12);
1297    }
1298
1299    #[test]
1300    fn health_sarif_cyclomatic_only() {
1301        let root = PathBuf::from("/project");
1302        let report = crate::health_types::HealthReport {
1303            findings: vec![crate::health_types::HealthFinding {
1304                path: root.join("src/utils.ts"),
1305                name: "parseExpression".to_string(),
1306                line: 42,
1307                col: 0,
1308                cyclomatic: 25,
1309                cognitive: 10,
1310                line_count: 80,
1311                param_count: 0,
1312                exceeded: crate::health_types::ExceededThreshold::Cyclomatic,
1313                severity: crate::health_types::FindingSeverity::High,
1314                crap: None,
1315                coverage_pct: None,
1316            }],
1317            summary: crate::health_types::HealthSummary {
1318                files_analyzed: 5,
1319                functions_analyzed: 20,
1320                functions_above_threshold: 1,
1321                ..Default::default()
1322            },
1323            ..Default::default()
1324        };
1325        let sarif = build_health_sarif(&report, &root);
1326        let entry = &sarif["runs"][0]["results"][0];
1327        assert_eq!(entry["ruleId"], "fallow/high-cyclomatic-complexity");
1328        assert_eq!(entry["level"], "warning");
1329        assert!(
1330            entry["message"]["text"]
1331                .as_str()
1332                .unwrap()
1333                .contains("cyclomatic complexity 25")
1334        );
1335        assert_eq!(
1336            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1337            "src/utils.ts"
1338        );
1339        let region = &entry["locations"][0]["physicalLocation"]["region"];
1340        assert_eq!(region["startLine"], 42);
1341        assert_eq!(region["startColumn"], 1);
1342    }
1343
1344    #[test]
1345    fn health_sarif_cognitive_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/api.ts"),
1350                name: "handleRequest".to_string(),
1351                line: 10,
1352                col: 4,
1353                cyclomatic: 8,
1354                cognitive: 20,
1355                line_count: 40,
1356                param_count: 0,
1357                exceeded: crate::health_types::ExceededThreshold::Cognitive,
1358                severity: crate::health_types::FindingSeverity::High,
1359                crap: None,
1360                coverage_pct: None,
1361            }],
1362            summary: crate::health_types::HealthSummary {
1363                files_analyzed: 3,
1364                functions_analyzed: 10,
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-cognitive-complexity");
1373        assert!(
1374            entry["message"]["text"]
1375                .as_str()
1376                .unwrap()
1377                .contains("cognitive complexity 20")
1378        );
1379        let region = &entry["locations"][0]["physicalLocation"]["region"];
1380        assert_eq!(region["startColumn"], 5); // col 4 + 1
1381    }
1382
1383    #[test]
1384    fn health_sarif_both_thresholds() {
1385        let root = PathBuf::from("/project");
1386        let report = crate::health_types::HealthReport {
1387            findings: vec![crate::health_types::HealthFinding {
1388                path: root.join("src/complex.ts"),
1389                name: "doEverything".to_string(),
1390                line: 1,
1391                col: 0,
1392                cyclomatic: 30,
1393                cognitive: 45,
1394                line_count: 100,
1395                param_count: 0,
1396                exceeded: crate::health_types::ExceededThreshold::Both,
1397                severity: crate::health_types::FindingSeverity::High,
1398                crap: None,
1399                coverage_pct: None,
1400            }],
1401            summary: crate::health_types::HealthSummary {
1402                files_analyzed: 1,
1403                functions_analyzed: 1,
1404                functions_above_threshold: 1,
1405                ..Default::default()
1406            },
1407            ..Default::default()
1408        };
1409        let sarif = build_health_sarif(&report, &root);
1410        let entry = &sarif["runs"][0]["results"][0];
1411        assert_eq!(entry["ruleId"], "fallow/high-complexity");
1412        let msg = entry["message"]["text"].as_str().unwrap();
1413        assert!(msg.contains("cyclomatic complexity 30"));
1414        assert!(msg.contains("cognitive complexity 45"));
1415    }
1416
1417    #[test]
1418    fn health_sarif_crap_only_emits_crap_rule() {
1419        // CRAP-only: cyclomatic + cognitive below their thresholds, CRAP at or
1420        // above the CRAP threshold. Rule must be `fallow/high-crap-score`.
1421        let root = PathBuf::from("/project");
1422        let report = crate::health_types::HealthReport {
1423            findings: vec![crate::health_types::HealthFinding {
1424                path: root.join("src/untested.ts"),
1425                name: "risky".to_string(),
1426                line: 8,
1427                col: 0,
1428                cyclomatic: 10,
1429                cognitive: 10,
1430                line_count: 20,
1431                param_count: 1,
1432                exceeded: crate::health_types::ExceededThreshold::Crap,
1433                severity: crate::health_types::FindingSeverity::High,
1434                crap: Some(82.2),
1435                coverage_pct: Some(12.0),
1436            }],
1437            summary: crate::health_types::HealthSummary {
1438                files_analyzed: 1,
1439                functions_analyzed: 1,
1440                functions_above_threshold: 1,
1441                ..Default::default()
1442            },
1443            ..Default::default()
1444        };
1445        let sarif = build_health_sarif(&report, &root);
1446        let entry = &sarif["runs"][0]["results"][0];
1447        assert_eq!(entry["ruleId"], "fallow/high-crap-score");
1448        let msg = entry["message"]["text"].as_str().unwrap();
1449        assert!(msg.contains("CRAP score 82.2"), "msg: {msg}");
1450        assert!(msg.contains("coverage 12%"), "msg: {msg}");
1451    }
1452
1453    #[test]
1454    fn health_sarif_cyclomatic_crap_uses_crap_rule() {
1455        // Cyclomatic + CRAP both exceeded. The CRAP-centric rule subsumes
1456        // the cyclomatic breach; only one SARIF result is emitted.
1457        let root = PathBuf::from("/project");
1458        let report = crate::health_types::HealthReport {
1459            findings: vec![crate::health_types::HealthFinding {
1460                path: root.join("src/hot.ts"),
1461                name: "branchy".to_string(),
1462                line: 1,
1463                col: 0,
1464                cyclomatic: 67,
1465                cognitive: 12,
1466                line_count: 80,
1467                param_count: 1,
1468                exceeded: crate::health_types::ExceededThreshold::CyclomaticCrap,
1469                severity: crate::health_types::FindingSeverity::Critical,
1470                crap: Some(182.0),
1471                coverage_pct: None,
1472            }],
1473            summary: crate::health_types::HealthSummary {
1474                files_analyzed: 1,
1475                functions_analyzed: 1,
1476                functions_above_threshold: 1,
1477                ..Default::default()
1478            },
1479            ..Default::default()
1480        };
1481        let sarif = build_health_sarif(&report, &root);
1482        let results = sarif["runs"][0]["results"].as_array().unwrap();
1483        assert_eq!(
1484            results.len(),
1485            1,
1486            "CyclomaticCrap should emit a single SARIF result under the CRAP rule"
1487        );
1488        assert_eq!(results[0]["ruleId"], "fallow/high-crap-score");
1489        let msg = results[0]["message"]["text"].as_str().unwrap();
1490        assert!(msg.contains("CRAP score 182"), "msg: {msg}");
1491        // coverage_pct absent => no coverage suffix
1492        assert!(!msg.contains("coverage"), "msg: {msg}");
1493    }
1494
1495    // ── Severity mapping ──
1496
1497    #[test]
1498    fn severity_to_sarif_level_error() {
1499        assert_eq!(severity_to_sarif_level(Severity::Error), "error");
1500    }
1501
1502    #[test]
1503    fn severity_to_sarif_level_warn() {
1504        assert_eq!(severity_to_sarif_level(Severity::Warn), "warning");
1505    }
1506
1507    #[test]
1508    fn severity_to_sarif_level_off() {
1509        assert_eq!(severity_to_sarif_level(Severity::Off), "warning");
1510    }
1511
1512    // ── Re-export properties ──
1513
1514    #[test]
1515    fn sarif_re_export_has_properties() {
1516        let root = PathBuf::from("/project");
1517        let mut results = AnalysisResults::default();
1518        results.unused_exports.push(UnusedExport {
1519            path: root.join("src/index.ts"),
1520            export_name: "reExported".to_string(),
1521            is_type_only: false,
1522            line: 1,
1523            col: 0,
1524            span_start: 0,
1525            is_re_export: true,
1526        });
1527
1528        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1529        let entry = &sarif["runs"][0]["results"][0];
1530        assert_eq!(entry["properties"]["is_re_export"], true);
1531        let msg = entry["message"]["text"].as_str().unwrap();
1532        assert!(msg.starts_with("Re-export"));
1533    }
1534
1535    #[test]
1536    fn sarif_non_re_export_has_no_properties() {
1537        let root = PathBuf::from("/project");
1538        let mut results = AnalysisResults::default();
1539        results.unused_exports.push(UnusedExport {
1540            path: root.join("src/utils.ts"),
1541            export_name: "foo".to_string(),
1542            is_type_only: false,
1543            line: 5,
1544            col: 0,
1545            span_start: 0,
1546            is_re_export: false,
1547        });
1548
1549        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1550        let entry = &sarif["runs"][0]["results"][0];
1551        assert!(entry.get("properties").is_none());
1552        let msg = entry["message"]["text"].as_str().unwrap();
1553        assert!(msg.starts_with("Export"));
1554    }
1555
1556    // ── Type re-export ──
1557
1558    #[test]
1559    fn sarif_type_re_export_message() {
1560        let root = PathBuf::from("/project");
1561        let mut results = AnalysisResults::default();
1562        results.unused_types.push(UnusedExport {
1563            path: root.join("src/index.ts"),
1564            export_name: "MyType".to_string(),
1565            is_type_only: true,
1566            line: 1,
1567            col: 0,
1568            span_start: 0,
1569            is_re_export: true,
1570        });
1571
1572        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1573        let entry = &sarif["runs"][0]["results"][0];
1574        assert_eq!(entry["ruleId"], "fallow/unused-type");
1575        let msg = entry["message"]["text"].as_str().unwrap();
1576        assert!(msg.starts_with("Type re-export"));
1577        assert_eq!(entry["properties"]["is_re_export"], true);
1578    }
1579
1580    // ── Dependency line == 0 skips region ──
1581
1582    #[test]
1583    fn sarif_dependency_line_zero_skips_region() {
1584        let root = PathBuf::from("/project");
1585        let mut results = AnalysisResults::default();
1586        results.unused_dependencies.push(UnusedDependency {
1587            package_name: "lodash".to_string(),
1588            location: DependencyLocation::Dependencies,
1589            path: root.join("package.json"),
1590            line: 0,
1591        });
1592
1593        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1594        let entry = &sarif["runs"][0]["results"][0];
1595        let phys = &entry["locations"][0]["physicalLocation"];
1596        assert!(phys.get("region").is_none());
1597    }
1598
1599    #[test]
1600    fn sarif_dependency_line_nonzero_has_region() {
1601        let root = PathBuf::from("/project");
1602        let mut results = AnalysisResults::default();
1603        results.unused_dependencies.push(UnusedDependency {
1604            package_name: "lodash".to_string(),
1605            location: DependencyLocation::Dependencies,
1606            path: root.join("package.json"),
1607            line: 7,
1608        });
1609
1610        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1611        let entry = &sarif["runs"][0]["results"][0];
1612        let region = &entry["locations"][0]["physicalLocation"]["region"];
1613        assert_eq!(region["startLine"], 7);
1614        assert_eq!(region["startColumn"], 1);
1615    }
1616
1617    // ── Type-only dependency line == 0 skips region ──
1618
1619    #[test]
1620    fn sarif_type_only_dep_line_zero_skips_region() {
1621        let root = PathBuf::from("/project");
1622        let mut results = AnalysisResults::default();
1623        results.type_only_dependencies.push(TypeOnlyDependency {
1624            package_name: "zod".to_string(),
1625            path: root.join("package.json"),
1626            line: 0,
1627        });
1628
1629        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1630        let entry = &sarif["runs"][0]["results"][0];
1631        let phys = &entry["locations"][0]["physicalLocation"];
1632        assert!(phys.get("region").is_none());
1633    }
1634
1635    // ── Circular dependency line == 0 skips region ──
1636
1637    #[test]
1638    fn sarif_circular_dep_line_zero_skips_region() {
1639        let root = PathBuf::from("/project");
1640        let mut results = AnalysisResults::default();
1641        results.circular_dependencies.push(CircularDependency {
1642            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1643            length: 2,
1644            line: 0,
1645            col: 0,
1646            is_cross_package: false,
1647        });
1648
1649        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1650        let entry = &sarif["runs"][0]["results"][0];
1651        let phys = &entry["locations"][0]["physicalLocation"];
1652        assert!(phys.get("region").is_none());
1653    }
1654
1655    #[test]
1656    fn sarif_circular_dep_line_nonzero_has_region() {
1657        let root = PathBuf::from("/project");
1658        let mut results = AnalysisResults::default();
1659        results.circular_dependencies.push(CircularDependency {
1660            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1661            length: 2,
1662            line: 5,
1663            col: 2,
1664            is_cross_package: false,
1665        });
1666
1667        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1668        let entry = &sarif["runs"][0]["results"][0];
1669        let region = &entry["locations"][0]["physicalLocation"]["region"];
1670        assert_eq!(region["startLine"], 5);
1671        assert_eq!(region["startColumn"], 3);
1672    }
1673
1674    // ── Unused optional dependency ──
1675
1676    #[test]
1677    fn sarif_unused_optional_dependency_result() {
1678        let root = PathBuf::from("/project");
1679        let mut results = AnalysisResults::default();
1680        results.unused_optional_dependencies.push(UnusedDependency {
1681            package_name: "fsevents".to_string(),
1682            location: DependencyLocation::OptionalDependencies,
1683            path: root.join("package.json"),
1684            line: 12,
1685        });
1686
1687        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1688        let entry = &sarif["runs"][0]["results"][0];
1689        assert_eq!(entry["ruleId"], "fallow/unused-optional-dependency");
1690        let msg = entry["message"]["text"].as_str().unwrap();
1691        assert!(msg.contains("optionalDependencies"));
1692    }
1693
1694    // ── Enum and class member SARIF messages ──
1695
1696    #[test]
1697    fn sarif_enum_member_message_format() {
1698        let root = PathBuf::from("/project");
1699        let mut results = AnalysisResults::default();
1700        results
1701            .unused_enum_members
1702            .push(fallow_core::results::UnusedMember {
1703                path: root.join("src/enums.ts"),
1704                parent_name: "Color".to_string(),
1705                member_name: "Purple".to_string(),
1706                kind: fallow_core::extract::MemberKind::EnumMember,
1707                line: 5,
1708                col: 2,
1709            });
1710
1711        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1712        let entry = &sarif["runs"][0]["results"][0];
1713        assert_eq!(entry["ruleId"], "fallow/unused-enum-member");
1714        let msg = entry["message"]["text"].as_str().unwrap();
1715        assert!(msg.contains("Enum member 'Color.Purple'"));
1716        let region = &entry["locations"][0]["physicalLocation"]["region"];
1717        assert_eq!(region["startColumn"], 3); // col 2 + 1
1718    }
1719
1720    #[test]
1721    fn sarif_class_member_message_format() {
1722        let root = PathBuf::from("/project");
1723        let mut results = AnalysisResults::default();
1724        results
1725            .unused_class_members
1726            .push(fallow_core::results::UnusedMember {
1727                path: root.join("src/service.ts"),
1728                parent_name: "API".to_string(),
1729                member_name: "fetch".to_string(),
1730                kind: fallow_core::extract::MemberKind::ClassMethod,
1731                line: 10,
1732                col: 4,
1733            });
1734
1735        let sarif = build_sarif(&results, &root, &RulesConfig::default());
1736        let entry = &sarif["runs"][0]["results"][0];
1737        assert_eq!(entry["ruleId"], "fallow/unused-class-member");
1738        let msg = entry["message"]["text"].as_str().unwrap();
1739        assert!(msg.contains("Class member 'API.fetch'"));
1740    }
1741
1742    // ── Duplication SARIF ──
1743
1744    #[test]
1745    #[expect(
1746        clippy::cast_possible_truncation,
1747        reason = "test line/col values are trivially small"
1748    )]
1749    fn duplication_sarif_structure() {
1750        use fallow_core::duplicates::*;
1751
1752        let root = PathBuf::from("/project");
1753        let report = DuplicationReport {
1754            clone_groups: vec![CloneGroup {
1755                instances: vec![
1756                    CloneInstance {
1757                        file: root.join("src/a.ts"),
1758                        start_line: 1,
1759                        end_line: 10,
1760                        start_col: 0,
1761                        end_col: 0,
1762                        fragment: String::new(),
1763                    },
1764                    CloneInstance {
1765                        file: root.join("src/b.ts"),
1766                        start_line: 5,
1767                        end_line: 14,
1768                        start_col: 2,
1769                        end_col: 0,
1770                        fragment: String::new(),
1771                    },
1772                ],
1773                token_count: 50,
1774                line_count: 10,
1775            }],
1776            clone_families: vec![],
1777            mirrored_directories: vec![],
1778            stats: DuplicationStats::default(),
1779        };
1780
1781        let sarif = serde_json::json!({
1782            "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
1783            "version": "2.1.0",
1784            "runs": [{
1785                "tool": {
1786                    "driver": {
1787                        "name": "fallow",
1788                        "version": env!("CARGO_PKG_VERSION"),
1789                        "informationUri": "https://github.com/fallow-rs/fallow",
1790                        "rules": [sarif_rule("fallow/code-duplication", "Duplicated code block", "warning")]
1791                    }
1792                },
1793                "results": []
1794            }]
1795        });
1796        // Just verify the function doesn't panic and produces expected structure
1797        let _ = sarif;
1798
1799        // Test the actual build path through print_duplication_sarif internals
1800        let mut sarif_results = Vec::new();
1801        for (i, group) in report.clone_groups.iter().enumerate() {
1802            for instance in &group.instances {
1803                sarif_results.push(sarif_result(
1804                    "fallow/code-duplication",
1805                    "warning",
1806                    &format!(
1807                        "Code clone group {} ({} lines, {} instances)",
1808                        i + 1,
1809                        group.line_count,
1810                        group.instances.len()
1811                    ),
1812                    &super::super::relative_uri(&instance.file, &root),
1813                    Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
1814                ));
1815            }
1816        }
1817        assert_eq!(sarif_results.len(), 2);
1818        assert_eq!(sarif_results[0]["ruleId"], "fallow/code-duplication");
1819        assert!(
1820            sarif_results[0]["message"]["text"]
1821                .as_str()
1822                .unwrap()
1823                .contains("10 lines")
1824        );
1825        let region0 = &sarif_results[0]["locations"][0]["physicalLocation"]["region"];
1826        assert_eq!(region0["startLine"], 1);
1827        assert_eq!(region0["startColumn"], 1); // start_col 0 + 1
1828        let region1 = &sarif_results[1]["locations"][0]["physicalLocation"]["region"];
1829        assert_eq!(region1["startLine"], 5);
1830        assert_eq!(region1["startColumn"], 3); // start_col 2 + 1
1831    }
1832
1833    // ── sarif_rule fallback (unknown rule ID) ──
1834
1835    #[test]
1836    fn sarif_rule_known_id_has_full_description() {
1837        let rule = sarif_rule("fallow/unused-file", "fallback text", "error");
1838        assert!(rule.get("fullDescription").is_some());
1839        assert!(rule.get("helpUri").is_some());
1840    }
1841
1842    #[test]
1843    fn sarif_rule_unknown_id_uses_fallback() {
1844        let rule = sarif_rule("fallow/nonexistent", "fallback text", "warning");
1845        assert_eq!(rule["shortDescription"]["text"], "fallback text");
1846        assert!(rule.get("fullDescription").is_none());
1847        assert!(rule.get("helpUri").is_none());
1848        assert_eq!(rule["defaultConfiguration"]["level"], "warning");
1849    }
1850
1851    // ── sarif_result without region ──
1852
1853    #[test]
1854    fn sarif_result_no_region_omits_region_key() {
1855        let result = sarif_result("rule/test", "error", "test msg", "src/file.ts", None);
1856        let phys = &result["locations"][0]["physicalLocation"];
1857        assert!(phys.get("region").is_none());
1858        assert_eq!(phys["artifactLocation"]["uri"], "src/file.ts");
1859    }
1860
1861    #[test]
1862    fn sarif_result_with_region_includes_region() {
1863        let result = sarif_result(
1864            "rule/test",
1865            "error",
1866            "test msg",
1867            "src/file.ts",
1868            Some((10, 5)),
1869        );
1870        let region = &result["locations"][0]["physicalLocation"]["region"];
1871        assert_eq!(region["startLine"], 10);
1872        assert_eq!(region["startColumn"], 5);
1873    }
1874
1875    // ── Health SARIF refactoring targets ──
1876
1877    #[test]
1878    fn health_sarif_includes_refactoring_targets() {
1879        use crate::health_types::*;
1880
1881        let root = PathBuf::from("/project");
1882        let report = HealthReport {
1883            summary: HealthSummary {
1884                files_analyzed: 10,
1885                functions_analyzed: 50,
1886                ..Default::default()
1887            },
1888            targets: vec![RefactoringTarget {
1889                path: root.join("src/complex.ts"),
1890                priority: 85.0,
1891                efficiency: 42.5,
1892                recommendation: "Split high-impact file".into(),
1893                category: RecommendationCategory::SplitHighImpact,
1894                effort: EffortEstimate::Medium,
1895                confidence: Confidence::High,
1896                factors: vec![],
1897                evidence: None,
1898            }],
1899            ..Default::default()
1900        };
1901
1902        let sarif = build_health_sarif(&report, &root);
1903        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1904        assert_eq!(entries.len(), 1);
1905        assert_eq!(entries[0]["ruleId"], "fallow/refactoring-target");
1906        assert_eq!(entries[0]["level"], "warning");
1907        let msg = entries[0]["message"]["text"].as_str().unwrap();
1908        assert!(msg.contains("high impact"));
1909        assert!(msg.contains("Split high-impact file"));
1910        assert!(msg.contains("42.5"));
1911    }
1912
1913    #[test]
1914    fn health_sarif_includes_coverage_gaps() {
1915        use crate::health_types::*;
1916
1917        let root = PathBuf::from("/project");
1918        let report = HealthReport {
1919            summary: HealthSummary {
1920                files_analyzed: 10,
1921                functions_analyzed: 50,
1922                ..Default::default()
1923            },
1924            coverage_gaps: Some(CoverageGaps {
1925                summary: CoverageGapSummary {
1926                    runtime_files: 2,
1927                    covered_files: 0,
1928                    file_coverage_pct: 0.0,
1929                    untested_files: 1,
1930                    untested_exports: 1,
1931                },
1932                files: vec![UntestedFile {
1933                    path: root.join("src/app.ts"),
1934                    value_export_count: 2,
1935                }],
1936                exports: vec![UntestedExport {
1937                    path: root.join("src/app.ts"),
1938                    export_name: "loader".into(),
1939                    line: 12,
1940                    col: 4,
1941                }],
1942            }),
1943            ..Default::default()
1944        };
1945
1946        let sarif = build_health_sarif(&report, &root);
1947        let entries = sarif["runs"][0]["results"].as_array().unwrap();
1948        assert_eq!(entries.len(), 2);
1949        assert_eq!(entries[0]["ruleId"], "fallow/untested-file");
1950        assert_eq!(
1951            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
1952            "src/app.ts"
1953        );
1954        assert!(
1955            entries[0]["message"]["text"]
1956                .as_str()
1957                .unwrap()
1958                .contains("2 value exports")
1959        );
1960        assert_eq!(entries[1]["ruleId"], "fallow/untested-export");
1961        assert_eq!(
1962            entries[1]["locations"][0]["physicalLocation"]["region"]["startLine"],
1963            12
1964        );
1965        assert_eq!(
1966            entries[1]["locations"][0]["physicalLocation"]["region"]["startColumn"],
1967            5
1968        );
1969    }
1970
1971    // ── Health SARIF rules include fullDescription from explain module ──
1972
1973    #[test]
1974    fn health_sarif_rules_have_full_descriptions() {
1975        let root = PathBuf::from("/project");
1976        let report = crate::health_types::HealthReport::default();
1977        let sarif = build_health_sarif(&report, &root);
1978        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
1979            .as_array()
1980            .unwrap();
1981        for rule in rules {
1982            let id = rule["id"].as_str().unwrap();
1983            assert!(
1984                rule.get("fullDescription").is_some(),
1985                "health rule {id} should have fullDescription"
1986            );
1987            assert!(
1988                rule.get("helpUri").is_some(),
1989                "health rule {id} should have helpUri"
1990            );
1991        }
1992    }
1993
1994    // ── Warn severity propagates correctly ──
1995
1996    #[test]
1997    fn sarif_warn_severity_produces_warning_level() {
1998        let root = PathBuf::from("/project");
1999        let mut results = AnalysisResults::default();
2000        results.unused_files.push(UnusedFile {
2001            path: root.join("src/dead.ts"),
2002        });
2003
2004        let rules = RulesConfig {
2005            unused_files: Severity::Warn,
2006            ..RulesConfig::default()
2007        };
2008
2009        let sarif = build_sarif(&results, &root, &rules);
2010        let entry = &sarif["runs"][0]["results"][0];
2011        assert_eq!(entry["level"], "warning");
2012    }
2013
2014    // ── Unused file has no region ──
2015
2016    #[test]
2017    fn sarif_unused_file_has_no_region() {
2018        let root = PathBuf::from("/project");
2019        let mut results = AnalysisResults::default();
2020        results.unused_files.push(UnusedFile {
2021            path: root.join("src/dead.ts"),
2022        });
2023
2024        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2025        let entry = &sarif["runs"][0]["results"][0];
2026        let phys = &entry["locations"][0]["physicalLocation"];
2027        assert!(phys.get("region").is_none());
2028    }
2029
2030    // ── Multiple unlisted deps with multiple import sites ──
2031
2032    #[test]
2033    fn sarif_unlisted_dep_multiple_import_sites() {
2034        let root = PathBuf::from("/project");
2035        let mut results = AnalysisResults::default();
2036        results.unlisted_dependencies.push(UnlistedDependency {
2037            package_name: "dotenv".to_string(),
2038            imported_from: vec![
2039                ImportSite {
2040                    path: root.join("src/a.ts"),
2041                    line: 1,
2042                    col: 0,
2043                },
2044                ImportSite {
2045                    path: root.join("src/b.ts"),
2046                    line: 5,
2047                    col: 0,
2048                },
2049            ],
2050        });
2051
2052        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2053        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2054        // One SARIF result per import site
2055        assert_eq!(entries.len(), 2);
2056        assert_eq!(
2057            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2058            "src/a.ts"
2059        );
2060        assert_eq!(
2061            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
2062            "src/b.ts"
2063        );
2064    }
2065
2066    // ── Empty unlisted dep (no import sites) produces zero results ──
2067
2068    #[test]
2069    fn sarif_unlisted_dep_no_import_sites() {
2070        let root = PathBuf::from("/project");
2071        let mut results = AnalysisResults::default();
2072        results.unlisted_dependencies.push(UnlistedDependency {
2073            package_name: "phantom".to_string(),
2074            imported_from: vec![],
2075        });
2076
2077        let sarif = build_sarif(&results, &root, &RulesConfig::default());
2078        let entries = sarif["runs"][0]["results"].as_array().unwrap();
2079        // No import sites => no SARIF results for this unlisted dep
2080        assert!(entries.is_empty());
2081    }
2082}