Skip to main content

fallow_output/
check.rs

1use std::collections::BTreeMap;
2use std::path::Path;
3use std::time::Duration;
4
5use fallow_types::envelope::{
6    BaselineDeltas, BaselineMatch, CheckSummary, ElapsedMs, EntryPoints, Meta, RegressionResult,
7    SchemaVersion, ToolVersion,
8};
9use fallow_types::output::{IssueAction, NextStep};
10use fallow_types::output_health::{HealthFindingAction, HealthFindingActionType};
11use fallow_types::results::AnalysisResults;
12use fallow_types::workspace::WorkspaceDiagnostic;
13use serde::Serialize;
14
15use crate::HealthReport;
16use crate::root_envelopes::{attach_telemetry_meta, serialize_named_json_output};
17
18/// Current schema version for the dead-code/check JSON envelope.
19pub const CHECK_SCHEMA_VERSION: u32 = 11;
20
21/// Schema projection for the dead-code envelope's exact version.
22#[cfg(feature = "schema")]
23#[expect(dead_code, reason = "schema-only type used by the field projection")]
24#[derive(schemars::JsonSchema)]
25#[schemars(extend("const" = CHECK_SCHEMA_VERSION))]
26struct CheckSchemaVersion(u32);
27
28/// Current schema version for the `fallow architecture` JSON envelope.
29///
30/// The architecture body is the dead-code body, so a change to that shared
31/// body bumps this version and [`CHECK_SCHEMA_VERSION`] together.
32pub const ARCHITECTURE_SCHEMA_VERSION: u32 = 2;
33
34/// Schema projection for the architecture envelope's exact version.
35///
36/// The schema emitter registers this type by name and points the
37/// `ArchitectureOutput` and `ArchitectureGroupedOutput` definitions at it.
38#[cfg(feature = "schema")]
39#[expect(dead_code, reason = "schema-only type used by the field projection")]
40#[derive(schemars::JsonSchema)]
41#[schemars(extend("const" = ARCHITECTURE_SCHEMA_VERSION))]
42pub struct ArchitectureSchemaVersion(u32);
43
44/// The commands that share the dead-code JSON body.
45///
46/// `fallow dead-code` and `fallow architecture` serialize the same
47/// [`CheckOutput`] and [`CheckGroupedOutput`] structs. Only the root `kind`
48/// and `schema_version` are different. A closed enum keeps an unknown kind
49/// string off the wire.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum CheckEnvelope {
52    /// `fallow dead-code`, and every embedded `check` section.
53    #[default]
54    DeadCode,
55    /// `fallow architecture`.
56    Architecture,
57}
58
59impl CheckEnvelope {
60    /// The root `kind` of the flat envelope.
61    #[must_use]
62    pub const fn kind(self) -> &'static str {
63        match self {
64            Self::DeadCode => "dead-code",
65            Self::Architecture => "architecture",
66        }
67    }
68
69    /// The root `kind` of the `--group-by` envelope.
70    #[must_use]
71    pub const fn grouped_kind(self) -> &'static str {
72        match self {
73            Self::DeadCode => "dead-code-grouped",
74            Self::Architecture => "architecture-grouped",
75        }
76    }
77
78    /// The `schema_version` that the envelope reports.
79    #[must_use]
80    pub const fn schema_version(self) -> u32 {
81        match self {
82            Self::DeadCode => CHECK_SCHEMA_VERSION,
83            Self::Architecture => ARCHITECTURE_SCHEMA_VERSION,
84        }
85    }
86
87    /// The subcommand that writes the envelope.
88    #[must_use]
89    pub const fn command(self) -> &'static str {
90        match self {
91            Self::DeadCode => "dead-code",
92            Self::Architecture => "architecture",
93        }
94    }
95}
96
97#[expect(
98    clippy::trivially_copy_pass_by_ref,
99    reason = "serde `skip_serializing_if` passes the field by reference"
100)]
101const fn is_zero(count: &usize) -> bool {
102    *count == 0
103}
104
105/// Envelope emitted by `fallow dead-code --format json` (plus the `check`
106/// block inside the combined and audit envelopes).
107///
108/// The body is the full `AnalysisResults` flattened into the envelope so
109/// every issue array (`unused_files`, `unused_exports`, ...) lives at the
110/// top level, matching the existing wire shape. `entry_points` lifts the
111/// otherwise `#[serde(skip)]`'d `AnalysisResults::entry_point_summary` back
112/// into the JSON output. `summary` carries the per-category counts the
113/// JSON layer always emits.
114#[derive(Debug, Clone, Serialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116#[cfg_attr(feature = "schema", schemars(title = "fallow dead-code --format json"))]
117pub struct CheckOutput {
118    /// Dead-code output schema version; currently [`CHECK_SCHEMA_VERSION`].
119    #[cfg_attr(feature = "schema", schemars(with = "CheckSchemaVersion"))]
120    pub schema_version: SchemaVersion,
121    /// Fallow CLI version that produced this output.
122    pub version: ToolVersion,
123    /// Wall-clock analysis duration in milliseconds.
124    pub elapsed_ms: ElapsedMs,
125    /// Total findings across all issue arrays; excludes `next_steps`.
126    pub total_issues: usize,
127    /// Entry-point totals per source, when the analysis recorded them.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub entry_points: Option<EntryPoints>,
130    /// Per-category finding counts.
131    pub summary: CheckSummary,
132    /// Full analysis results, flattened so each issue array sits at the
133    /// envelope root.
134    #[serde(flatten)]
135    pub results: AnalysisResults,
136    /// Count deltas against the matched baseline, in baseline runs.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub baseline_deltas: Option<BaselineDeltas>,
139    /// Which baseline snapshot was matched, in baseline runs.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub baseline: Option<BaselineMatch>,
142    /// This run's view of the loaded baseline, present only in baseline runs.
143    /// Carries the staleness counts, the advisory verdict and `gate_trips`, the
144    /// same boolean `--fail-on-stale-baseline` exits on, so a CI integration
145    /// reads one field instead of restating the rule. Read `change_scoped`
146    /// before dividing `matched_entries` by `baseline_entries`: a narrowed run
147    /// can report `matched_entries: 0` on a healthy baseline.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub baseline_staleness: Option<crate::BaselineStaleness>,
150    /// The answer to `--finding-id`, present only when the run received one
151    /// or more `--finding-id` values. The report then holds only the
152    /// requested findings. Read `missing` as resolved only when `conclusive`
153    /// is true; a scope, a baseline or a filter can hide a finding that still
154    /// exists. See [`crate::FindingIdQuery`].
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub finding_id_query: Option<crate::FindingIdQuery>,
157    /// Regression verdict against the baseline, in `--fail-on-regression` runs.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub regression: Option<RegressionResult>,
160    /// The verdict of every gate this run evaluated, keyed by name. The CLI
161    /// always emits it, with the command's default exit rule in it also when
162    /// no flag armed a gate, so a CI integration reads the verdict instead of
163    /// guessing from a process status it usually cannot see. A gate fails the
164    /// build when `status` is `fail` and `enforced` is true. The typed
165    /// programmatic API runs no CLI gate and leaves it absent. See
166    /// [`crate::GateOutcomes`].
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub gate_outcomes: Option<crate::GateOutcomes>,
169    /// Every narrowing or shaping request this run received, keyed by name,
170    /// absent when it was asked for nothing. An entry whose `status` is not
171    /// `applied` means the run could not do what it was asked and reported
172    /// something wider instead, so what follows is a valid report of a scope
173    /// nobody requested. Honoured requests are published too, with
174    /// `status: "applied"`, so an absent object means "nothing was asked for",
175    /// never "nothing failed". See [`crate::RequestOutcomes`].
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub request_outcomes: Option<crate::RequestOutcomes>,
178    /// Applied Git refs for exact workspace packages. Absent when no package
179    /// baselines were selected, including runs with a global changed-since ref.
180    #[serde(default, skip_serializing_if = "Vec::is_empty")]
181    pub package_baselines: Vec<crate::PackageBaselineStatus>,
182    /// `_meta` block. A `--format json` run of the CLI always sets
183    /// `telemetry.analysis_run_id`. With `--explain`, it also holds the docs
184    /// URL and the rule definitions.
185    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
186    pub meta: Option<Meta>,
187    /// Non-fatal diagnostics about the project itself, from all three stages
188    /// that record them (issue #473):
189    ///
190    /// - workspace discovery, at config load: `undeclared-workspace`,
191    ///   `malformed-package-json`, `glob-matched-no-package-json`,
192    ///   `workspace-glob-outside-root`, `workspace-pattern-dir-missing`,
193    ///   `nested-project-root`, `malformed-tsconfig`,
194    ///   `tsconfig-reference-dir-missing`;
195    /// - source discovery, during the file walk: `skipped-large-file`,
196    ///   `skipped-minified-file`, `skipped-source-dotdir`,
197    ///   `excluded-by-default-ignore`, `source-read-failure`,
198    ///   `source-parse-degraded`, `source-nesting-too-deep`;
199    /// - dead-code analysis, from the dependency-catalog and override
200    ///   detectors: `malformed-pnpm-workspace-yaml`,
201    ///   `bun-lockb-override-resolution-skipped`;
202    /// - framework plugins, while they read their own build configs:
203    ///   `plugin-config-unreadable`, `plugin-effect-not-modeled`;
204    /// - the dead-code result, for config patterns that matched nothing:
205    ///   `ignore-dependencies-glob-unmatched`,
206    ///   `ignore-findings-pattern-unmatched`.
207    ///
208    /// Analysis-stage and plugin-stage kinds therefore reach only the envelopes
209    /// whose run includes a dead-code analyze pass, never a standalone
210    /// `fallow dupes --format json`. `path` is project-root-relative with
211    /// forward slashes; the array is omitted when empty. The same list is
212    /// repeated on each top-level command's envelope so single-command
213    /// consumers see it without having to look at a separate top-level field.
214    ///
215    /// A diagnostic here is advisory and never withholds a finding. Where an
216    /// entry reports a source file this run never fully analyzed
217    /// (`source-parse-degraded`, `source-nesting-too-deep`,
218    /// `source-read-failure`, `skipped-large-file`, `skipped-minified-file`,
219    /// `skipped-source-dotdir`) it can distort a verdict, so the affected
220    /// `unused_files[]`, `unused_exports[]`, and dependency entries
221    /// additionally carry the caveat themselves in their own
222    /// optional `reachability_caveats[]` array, and a reader who never scrolls
223    /// back up to this list still sees it. `fallow fix` reads the same array
224    /// and withholds the removal while a caveat stands.
225    ///
226    /// `excluded-by-default-ignore` is the one source-discovery kind that
227    /// reports unseen files without raising a caveat. It names a built-in
228    /// ignore pattern (`**/dist/**`, `**/build/**`, `**/coverage/**`, or one
229    /// of the four minified-bundle globs) that removed candidate source files
230    /// from the walk, which is designed behavior on generated output rather
231    /// than a degraded run, so it is advisory only and no finding inherits it.
232    /// One entry per pattern, never per file, so the array stays bounded on a
233    /// project of any size. Gitignored trees are pruned before the walk sees
234    /// them and count zero, and `**/node_modules/**` is never reported:
235    /// installed dependencies are not the first-party source the kind is
236    /// about.
237    #[serde(default, skip_serializing_if = "Vec::is_empty")]
238    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
239    /// Read-only follow-up commands computed from this run's findings, emitted
240    /// at the JSON root so an agent acting on the output is pointed at fallow's
241    /// adjacent verification capabilities (trace, complexity breakdown, audit,
242    /// workspace scoping). Each command is runnable as-is and never mutating;
243    /// see [`NextStep`] for both contracts. Omitted when empty or when
244    /// `FALLOW_SUGGESTIONS=off`; does NOT contribute to `total_issues`.
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub next_steps: Vec<NextStep>,
247}
248
249/// Envelope emitted by `fallow dead-code --group-by ... --format json`.
250///
251/// Issues are partitioned into resolver buckets (CODEOWNERS team, directory
252/// prefix, workspace package, or GitLab CODEOWNERS section) instead of flat
253/// arrays. Each bucket carries the same issue-array shape as the ungrouped
254/// `CheckOutput` body, plus per-group `key` / `owners` / `total_issues`.
255#[derive(Debug, Clone, Serialize)]
256#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
257#[cfg_attr(
258    feature = "schema",
259    schemars(
260        title = "fallow dead-code --group-by <owner|directory|package|section> --format json"
261    )
262)]
263pub struct CheckGroupedOutput {
264    /// Dead-code output schema version; currently [`CHECK_SCHEMA_VERSION`].
265    #[cfg_attr(feature = "schema", schemars(with = "CheckSchemaVersion"))]
266    pub schema_version: SchemaVersion,
267    /// Fallow CLI version that produced this output.
268    pub version: ToolVersion,
269    /// Wall-clock analysis duration in milliseconds.
270    pub elapsed_ms: ElapsedMs,
271    /// Resolver the issues were grouped by.
272    pub grouped_by: GroupByMode,
273    /// Total findings across all groups.
274    pub total_issues: usize,
275    /// One bucket per resolver key.
276    pub groups: Vec<CheckGroupedEntry>,
277    /// `true` when the `unused-load-data-key` detector abstained for the whole
278    /// project. The abstain has no file, so it is on the root and not in a
279    /// group. An empty `unused_load_data_keys` with this flag set does not
280    /// mean the project is clean: the rule could not run safely. Serialized
281    /// only when `true`, like the flat `CheckOutput` field.
282    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
283    pub unused_load_data_keys_global_abstain: bool,
284    /// Number of export and member findings that the run hid because their
285    /// file is an unused file. The count covers the whole run, so it is on
286    /// the root and not in a group. Serialized only when not zero, like the
287    /// flat `CheckOutput` field.
288    #[serde(default, skip_serializing_if = "is_zero")]
289    pub cascade_hidden: usize,
290    /// This run's view of the loaded baseline, present only in baseline runs.
291    /// Carries the staleness counts, the advisory verdict and `gate_trips`, the
292    /// same boolean `--fail-on-stale-baseline` exits on, so a CI integration
293    /// reads one field instead of restating the rule. Read `change_scoped`
294    /// before dividing `matched_entries` by `baseline_entries`: a narrowed run
295    /// can report `matched_entries: 0` on a healthy baseline.
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub baseline_staleness: Option<crate::BaselineStaleness>,
298    /// The answer to `--finding-id`, present only when the run received one
299    /// or more `--finding-id` values. The report then holds only the
300    /// requested findings. Read `missing` as resolved only when `conclusive`
301    /// is true; a scope, a baseline or a filter can hide a finding that still
302    /// exists. See [`crate::FindingIdQuery`].
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub finding_id_query: Option<crate::FindingIdQuery>,
305    /// The verdict of every gate this run evaluated, keyed by name. The CLI
306    /// always emits it, with the command's default exit rule in it also when
307    /// no flag armed a gate, so a CI integration reads the verdict instead of
308    /// guessing from a process status it usually cannot see. A gate fails the
309    /// build when `status` is `fail` and `enforced` is true. The typed
310    /// programmatic API runs no CLI gate and leaves it absent. See
311    /// [`crate::GateOutcomes`].
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub gate_outcomes: Option<crate::GateOutcomes>,
314    /// Every narrowing or shaping request this run received, keyed by name,
315    /// absent when it was asked for nothing. An entry whose `status` is not
316    /// `applied` means the run could not do what it was asked and reported
317    /// something wider instead, so what follows is a valid report of a scope
318    /// nobody requested. Honoured requests are published too, with
319    /// `status: "applied"`, so an absent object means "nothing was asked for",
320    /// never "nothing failed". See [`crate::RequestOutcomes`].
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub request_outcomes: Option<crate::RequestOutcomes>,
323    /// Applied package Git refs, omitted outside package-baseline runs.
324    #[serde(default, skip_serializing_if = "Vec::is_empty")]
325    pub package_baselines: Vec<crate::PackageBaselineStatus>,
326    /// `_meta` block. A `--format json` run of the CLI always sets
327    /// `telemetry.analysis_run_id`. With `--explain`, it also holds the docs
328    /// URL and the rule definitions.
329    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
330    pub meta: Option<Meta>,
331    /// Diagnostics collected for the full analysis before issue grouping.
332    /// See [`CheckOutput::workspace_diagnostics`] for the contract.
333    #[serde(default, skip_serializing_if = "Vec::is_empty")]
334    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
335    /// Read-only follow-up commands computed from the full (ungrouped) findings.
336    /// See [`CheckOutput::next_steps`] for the contract.
337    #[serde(default, skip_serializing_if = "Vec::is_empty")]
338    pub next_steps: Vec<NextStep>,
339}
340
341/// Single resolver bucket inside `CheckGroupedOutput`. Carries the group's
342/// identifier, optional section owners, and a per-group flattened
343/// `AnalysisResults`.
344#[derive(Debug, Clone, Serialize)]
345#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
346pub struct CheckGroupedEntry {
347    /// Resolver key: team name, directory prefix, package name, or section.
348    pub key: String,
349    /// Owners of a GitLab CODEOWNERS section; present for section grouping.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub owners: Option<Vec<String>>,
352    /// Findings in this group.
353    pub total_issues: usize,
354    /// Group-scoped analysis results, flattened like the ungrouped body.
355    #[serde(flatten)]
356    pub results: AnalysisResults,
357}
358
359/// Resolver mode label for grouped envelopes (dead-code, dupes, health).
360///
361/// `owner` groups by CODEOWNERS team, `directory` groups by top-level
362/// directory prefix, `package` groups by workspace package name, `section`
363/// groups by GitLab CODEOWNERS `[Section]` header name.
364#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
365#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
366#[serde(rename_all = "lowercase")]
367pub enum GroupByMode {
368    /// Group by CODEOWNERS team.
369    Owner,
370    /// Group by top-level directory prefix.
371    Directory,
372    /// Group by workspace package name.
373    Package,
374    /// Group by GitLab CODEOWNERS `[Section]` header name.
375    Section,
376}
377
378/// Inputs for building the dead-code JSON envelope.
379pub struct CheckOutputInput {
380    /// Dead-code output schema version to report.
381    pub schema_version: u32,
382    /// Fallow CLI version to report.
383    pub version: String,
384    /// Wall-clock analysis duration; serialized as whole milliseconds.
385    pub elapsed: Duration,
386    /// Engine analysis results to embed.
387    pub results: AnalysisResults,
388    /// Whether duplicate-export findings are fixable via config edits, which
389    /// flips their `config_fixable` action flag.
390    pub config_fixable: bool,
391    /// `_meta` block to attach when `--explain` was passed.
392    pub meta: Option<Meta>,
393    /// Workspace-discovery, source-discovery, and analysis-stage diagnostics.
394    /// See [`CheckOutput::workspace_diagnostics`] for the contract.
395    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
396    /// Read-only follow-up commands computed from this run's findings.
397    pub next_steps: Vec<NextStep>,
398}
399
400/// Build the typed dead-code JSON envelope from engine results.
401#[must_use]
402pub fn build_check_output(input: CheckOutputInput) -> CheckOutput {
403    let mut results = input.results;
404    apply_config_fixable_to_duplicate_exports(&mut results, input.config_fixable);
405    harmonize_multi_kind_suppress_line_actions(&mut results);
406    let mut meta = input.meta;
407    if let Some(meta) = meta.as_mut() {
408        crate::retain_reported_rules(meta, [&results]);
409    }
410    CheckOutput {
411        schema_version: SchemaVersion(input.schema_version),
412        version: ToolVersion(input.version),
413        elapsed_ms: ElapsedMs(input.elapsed.as_millis() as u64),
414        total_issues: results.total_issues(),
415        entry_points: results
416            .entry_point_summary
417            .as_ref()
418            .map(|entry_points| EntryPoints {
419                total: entry_points.total,
420                sources: entry_points
421                    .by_source
422                    .iter()
423                    .map(|(key, value)| (key.replace(' ', "_"), *value))
424                    .collect(),
425            }),
426        summary: build_check_summary(&results),
427        results,
428        baseline_deltas: None,
429        baseline: None,
430        baseline_staleness: None,
431        finding_id_query: None,
432        regression: None,
433        gate_outcomes: None,
434        request_outcomes: None,
435        package_baselines: Vec::new(),
436        meta,
437        workspace_diagnostics: input.workspace_diagnostics,
438        next_steps: input.next_steps,
439    }
440}
441
442fn serialize_check_family_json_output<T: Serialize>(
443    output: T,
444    kind: &'static str,
445    analysis_run_id: Option<&str>,
446) -> Result<serde_json::Value, serde_json::Error> {
447    let mut value = serialize_named_json_output(output, kind)?;
448    attach_telemetry_meta(&mut value, analysis_run_id);
449    Ok(value)
450}
451
452/// Serialize `fallow dead-code --format json`.
453///
454/// # Errors
455///
456/// Returns a serde error when the dead-code output cannot be converted to JSON.
457pub fn serialize_check_json_output(
458    output: CheckOutput,
459    analysis_run_id: Option<&str>,
460) -> Result<serde_json::Value, serde_json::Error> {
461    serialize_check_family_json_output(output, "dead-code", analysis_run_id)
462}
463
464/// Serialize `fallow dead-code --group-by ... --format json`.
465///
466/// # Errors
467///
468/// Returns a serde error when the grouped dead-code output cannot be converted
469/// to JSON.
470pub fn serialize_check_grouped_json_output(
471    output: CheckGroupedOutput,
472    analysis_run_id: Option<&str>,
473) -> Result<serde_json::Value, serde_json::Error> {
474    serialize_check_family_json_output(output, "dead-code-grouped", analysis_run_id)
475}
476
477/// Serialize `fallow architecture --format json`.
478///
479/// The body is the dead-code body. The caller sets `schema_version` to
480/// [`ARCHITECTURE_SCHEMA_VERSION`].
481///
482/// # Errors
483///
484/// Returns a serde error when the output cannot be converted to JSON.
485pub fn serialize_architecture_json_output(
486    output: CheckOutput,
487    analysis_run_id: Option<&str>,
488) -> Result<serde_json::Value, serde_json::Error> {
489    serialize_check_family_json_output(output, CheckEnvelope::Architecture.kind(), analysis_run_id)
490}
491
492/// Serialize `fallow architecture --group-by ... --format json`.
493///
494/// # Errors
495///
496/// Returns a serde error when the grouped output cannot be converted to JSON.
497pub fn serialize_architecture_grouped_json_output(
498    output: CheckGroupedOutput,
499    analysis_run_id: Option<&str>,
500) -> Result<serde_json::Value, serde_json::Error> {
501    serialize_check_family_json_output(
502        output,
503        CheckEnvelope::Architecture.grouped_kind(),
504        analysis_run_id,
505    )
506}
507
508/// Mark every duplicate-export finding as fixable through a config edit when
509/// the project's config supports automated fixes.
510pub fn apply_config_fixable_to_duplicate_exports(
511    results: &mut AnalysisResults,
512    config_fixable: bool,
513) {
514    if !config_fixable {
515        return;
516    }
517    for finding in &mut results.duplicate_exports {
518        finding.set_config_fixable(true);
519    }
520}
521
522type SuppressAnchor = (String, u32);
523
524macro_rules! visit_suppress_line_findings {
525    ($results:expr, $visit:expr) => {{
526        let results = $results;
527        for finding in &results.unused_exports {
528            $visit(&finding.export.path, finding.export.line, &finding.actions);
529        }
530        for finding in &results.unused_types {
531            $visit(&finding.export.path, finding.export.line, &finding.actions);
532        }
533        for finding in &results.private_type_leaks {
534            $visit(&finding.leak.path, finding.leak.line, &finding.actions);
535        }
536        for finding in &results.deprecated_exports_in_use {
537            $visit(&finding.export.path, finding.export.line, &finding.actions);
538        }
539        for finding in &results.unused_enum_members {
540            $visit(&finding.member.path, finding.member.line, &finding.actions);
541        }
542        for finding in &results.unused_class_members {
543            $visit(&finding.member.path, finding.member.line, &finding.actions);
544        }
545        for finding in &results.unused_store_members {
546            $visit(&finding.member.path, finding.member.line, &finding.actions);
547        }
548        for finding in &results.unused_namespace_members {
549            $visit(&finding.member.path, finding.member.line, &finding.actions);
550        }
551        for finding in &results.unused_protected_class_members {
552            $visit(&finding.member.path, finding.member.line, &finding.actions);
553        }
554        for finding in &results.namespace_escapes {
555            $visit(&finding.escape.path, finding.escape.line, &finding.actions);
556        }
557        for finding in &results.test_only_exports {
558            $visit(&finding.export.path, finding.export.line, &finding.actions);
559        }
560        for finding in &results.unresolved_imports {
561            $visit(&finding.import.path, finding.import.line, &finding.actions);
562        }
563        for finding in &results.unused_dependencies {
564            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
565        }
566        for finding in &results.unused_dev_dependencies {
567            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
568        }
569        for finding in &results.unused_optional_dependencies {
570            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
571        }
572        for finding in &results.type_only_dependencies {
573            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
574        }
575        for finding in &results.test_only_dependencies {
576            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
577        }
578        for finding in &results.dev_dependencies_in_production {
579            $visit(&finding.dep.path, finding.dep.line, &finding.actions);
580        }
581        for finding in &results.circular_dependencies {
582            if let Some(path) = finding.cycle.files.first() {
583                $visit(path, finding.cycle.line, &finding.actions);
584            }
585        }
586        for finding in &results.package_cycles {
587            if let Some(edge) = finding.cycle.edges.first() {
588                $visit(&edge.path, edge.line, &finding.actions);
589            }
590        }
591        for finding in &results.boundary_violations {
592            $visit(
593                &finding.violation.from_path,
594                finding.violation.line,
595                &finding.actions,
596            );
597        }
598        for finding in &results.boundary_coverage_violations {
599            $visit(
600                &finding.violation.path,
601                finding.violation.line,
602                &finding.actions,
603            );
604        }
605        for finding in &results.boundary_call_violations {
606            $visit(
607                &finding.violation.path,
608                finding.violation.line,
609                &finding.actions,
610            );
611        }
612        for finding in &results.policy_violations {
613            $visit(
614                &finding.violation.path,
615                finding.violation.line,
616                &finding.actions,
617            );
618        }
619        for finding in &results.unused_catalog_entries {
620            $visit(&finding.entry.path, finding.entry.line, &finding.actions);
621        }
622        for finding in &results.empty_catalog_groups {
623            $visit(&finding.group.path, finding.group.line, &finding.actions);
624        }
625        for finding in &results.unresolved_catalog_references {
626            $visit(
627                &finding.reference.path,
628                finding.reference.line,
629                &finding.actions,
630            );
631        }
632        for finding in &results.unused_dependency_overrides {
633            $visit(&finding.entry.path, finding.entry.line, &finding.actions);
634        }
635        for finding in &results.misconfigured_dependency_overrides {
636            $visit(&finding.entry.path, finding.entry.line, &finding.actions);
637        }
638        for finding in &results.invalid_client_exports {
639            $visit(&finding.export.path, finding.export.line, &finding.actions);
640        }
641        for finding in &results.mixed_client_server_barrels {
642            $visit(&finding.barrel.path, finding.barrel.line, &finding.actions);
643        }
644        for finding in &results.misplaced_directives {
645            $visit(
646                &finding.directive_site.path,
647                finding.directive_site.line,
648                &finding.actions,
649            );
650        }
651        for finding in &results.unprovided_injects {
652            $visit(&finding.inject.path, finding.inject.line, &finding.actions);
653        }
654        for finding in &results.unrendered_components {
655            $visit(
656                &finding.component.path,
657                finding.component.line,
658                &finding.actions,
659            );
660        }
661        for finding in &results.route_collisions {
662            $visit(
663                &finding.collision.path,
664                finding.collision.line,
665                &finding.actions,
666            );
667        }
668        for finding in &results.dynamic_segment_name_conflicts {
669            $visit(
670                &finding.conflict.path,
671                finding.conflict.line,
672                &finding.actions,
673            );
674        }
675        for finding in &results.unused_component_props {
676            $visit(&finding.prop.path, finding.prop.line, &finding.actions);
677        }
678        for finding in &results.absent_component_props {
679            $visit(&finding.prop.path, finding.prop.line, &finding.actions);
680        }
681        for finding in &results.constant_parameters {
682            $visit(
683                &finding.parameter.path,
684                finding.parameter.line,
685                &finding.actions,
686            );
687        }
688        for finding in &results.unused_component_emits {
689            $visit(&finding.emit.path, finding.emit.line, &finding.actions);
690        }
691        for finding in &results.unused_component_inputs {
692            $visit(&finding.input.path, finding.input.line, &finding.actions);
693        }
694        for finding in &results.unused_component_outputs {
695            $visit(&finding.output.path, finding.output.line, &finding.actions);
696        }
697        for finding in &results.unused_svelte_events {
698            $visit(&finding.event.path, finding.event.line, &finding.actions);
699        }
700        for finding in &results.unused_effect_layers {
701            $visit(&finding.layer.path, finding.layer.line, &finding.actions);
702        }
703        for finding in &results.duplicate_export_aliases {
704            $visit(&finding.alias.path, finding.alias.line, &finding.actions);
705        }
706        for finding in &results.unused_tagged_errors {
707            $visit(&finding.error.path, finding.error.line, &finding.actions);
708        }
709        for finding in &results.unproduced_catch_tags {
710            $visit(
711                &finding.catch_tag.path,
712                finding.catch_tag.line,
713                &finding.actions,
714            );
715        }
716        for finding in &results.unused_server_actions {
717            $visit(&finding.action.path, finding.action.line, &finding.actions);
718        }
719        for finding in &results.unused_load_data_keys {
720            $visit(&finding.key.path, finding.key.line, &finding.actions);
721        }
722        for finding in &results.prop_drilling_chains {
723            if let Some(hop) = finding.chain.hops.first() {
724                $visit(&hop.file, hop.line, &finding.actions);
725            }
726        }
727        for finding in &results.thin_wrappers {
728            $visit(
729                &finding.wrapper.file,
730                finding.wrapper.line,
731                &finding.actions,
732            );
733        }
734        for finding in &results.duplicate_prop_shapes {
735            $visit(&finding.shape.file, finding.shape.line, &finding.actions);
736        }
737    }};
738}
739
740macro_rules! visit_suppress_line_findings_mut {
741    ($results:expr, $visit:expr) => {{
742        let results = $results;
743        for finding in &mut results.unused_exports {
744            $visit(
745                &finding.export.path,
746                finding.export.line,
747                &mut finding.actions,
748            );
749        }
750        for finding in &mut results.unused_types {
751            $visit(
752                &finding.export.path,
753                finding.export.line,
754                &mut finding.actions,
755            );
756        }
757        for finding in &mut results.private_type_leaks {
758            $visit(&finding.leak.path, finding.leak.line, &mut finding.actions);
759        }
760        for finding in &mut results.deprecated_exports_in_use {
761            $visit(
762                &finding.export.path,
763                finding.export.line,
764                &mut finding.actions,
765            );
766        }
767        for finding in &mut results.unused_enum_members {
768            $visit(
769                &finding.member.path,
770                finding.member.line,
771                &mut finding.actions,
772            );
773        }
774        for finding in &mut results.unused_class_members {
775            $visit(
776                &finding.member.path,
777                finding.member.line,
778                &mut finding.actions,
779            );
780        }
781        for finding in &mut results.unused_store_members {
782            $visit(
783                &finding.member.path,
784                finding.member.line,
785                &mut finding.actions,
786            );
787        }
788        for finding in &mut results.unused_namespace_members {
789            $visit(
790                &finding.member.path,
791                finding.member.line,
792                &mut finding.actions,
793            );
794        }
795        for finding in &mut results.unused_protected_class_members {
796            $visit(
797                &finding.member.path,
798                finding.member.line,
799                &mut finding.actions,
800            );
801        }
802        for finding in &mut results.namespace_escapes {
803            $visit(
804                &finding.escape.path,
805                finding.escape.line,
806                &mut finding.actions,
807            );
808        }
809        for finding in &mut results.test_only_exports {
810            $visit(
811                &finding.export.path,
812                finding.export.line,
813                &mut finding.actions,
814            );
815        }
816        for finding in &mut results.unresolved_imports {
817            $visit(
818                &finding.import.path,
819                finding.import.line,
820                &mut finding.actions,
821            );
822        }
823        for finding in &mut results.unused_dependencies {
824            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
825        }
826        for finding in &mut results.unused_dev_dependencies {
827            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
828        }
829        for finding in &mut results.unused_optional_dependencies {
830            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
831        }
832        for finding in &mut results.type_only_dependencies {
833            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
834        }
835        for finding in &mut results.test_only_dependencies {
836            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
837        }
838        for finding in &mut results.dev_dependencies_in_production {
839            $visit(&finding.dep.path, finding.dep.line, &mut finding.actions);
840        }
841        for finding in &mut results.circular_dependencies {
842            if let Some(path) = finding.cycle.files.first() {
843                $visit(path, finding.cycle.line, &mut finding.actions);
844            }
845        }
846        for finding in &mut results.package_cycles {
847            if let Some(edge) = finding.cycle.edges.first() {
848                $visit(&edge.path, edge.line, &mut finding.actions);
849            }
850        }
851        for finding in &mut results.boundary_violations {
852            $visit(
853                &finding.violation.from_path,
854                finding.violation.line,
855                &mut finding.actions,
856            );
857        }
858        for finding in &mut results.boundary_coverage_violations {
859            $visit(
860                &finding.violation.path,
861                finding.violation.line,
862                &mut finding.actions,
863            );
864        }
865        for finding in &mut results.boundary_call_violations {
866            $visit(
867                &finding.violation.path,
868                finding.violation.line,
869                &mut finding.actions,
870            );
871        }
872        for finding in &mut results.policy_violations {
873            $visit(
874                &finding.violation.path,
875                finding.violation.line,
876                &mut finding.actions,
877            );
878        }
879        for finding in &mut results.unused_catalog_entries {
880            $visit(
881                &finding.entry.path,
882                finding.entry.line,
883                &mut finding.actions,
884            );
885        }
886        for finding in &mut results.empty_catalog_groups {
887            $visit(
888                &finding.group.path,
889                finding.group.line,
890                &mut finding.actions,
891            );
892        }
893        for finding in &mut results.unresolved_catalog_references {
894            $visit(
895                &finding.reference.path,
896                finding.reference.line,
897                &mut finding.actions,
898            );
899        }
900        for finding in &mut results.unused_dependency_overrides {
901            $visit(
902                &finding.entry.path,
903                finding.entry.line,
904                &mut finding.actions,
905            );
906        }
907        for finding in &mut results.misconfigured_dependency_overrides {
908            $visit(
909                &finding.entry.path,
910                finding.entry.line,
911                &mut finding.actions,
912            );
913        }
914        for finding in &mut results.invalid_client_exports {
915            $visit(
916                &finding.export.path,
917                finding.export.line,
918                &mut finding.actions,
919            );
920        }
921        for finding in &mut results.mixed_client_server_barrels {
922            $visit(
923                &finding.barrel.path,
924                finding.barrel.line,
925                &mut finding.actions,
926            );
927        }
928        for finding in &mut results.misplaced_directives {
929            $visit(
930                &finding.directive_site.path,
931                finding.directive_site.line,
932                &mut finding.actions,
933            );
934        }
935        for finding in &mut results.unprovided_injects {
936            $visit(
937                &finding.inject.path,
938                finding.inject.line,
939                &mut finding.actions,
940            );
941        }
942        for finding in &mut results.unrendered_components {
943            $visit(
944                &finding.component.path,
945                finding.component.line,
946                &mut finding.actions,
947            );
948        }
949        for finding in &mut results.route_collisions {
950            $visit(
951                &finding.collision.path,
952                finding.collision.line,
953                &mut finding.actions,
954            );
955        }
956        for finding in &mut results.dynamic_segment_name_conflicts {
957            $visit(
958                &finding.conflict.path,
959                finding.conflict.line,
960                &mut finding.actions,
961            );
962        }
963        for finding in &mut results.unused_component_props {
964            $visit(&finding.prop.path, finding.prop.line, &mut finding.actions);
965        }
966        for finding in &mut results.absent_component_props {
967            $visit(&finding.prop.path, finding.prop.line, &mut finding.actions);
968        }
969        for finding in &mut results.constant_parameters {
970            $visit(
971                &finding.parameter.path,
972                finding.parameter.line,
973                &mut finding.actions,
974            );
975        }
976        for finding in &mut results.unused_component_emits {
977            $visit(&finding.emit.path, finding.emit.line, &mut finding.actions);
978        }
979        for finding in &mut results.unused_component_inputs {
980            $visit(
981                &finding.input.path,
982                finding.input.line,
983                &mut finding.actions,
984            );
985        }
986        for finding in &mut results.unused_component_outputs {
987            $visit(
988                &finding.output.path,
989                finding.output.line,
990                &mut finding.actions,
991            );
992        }
993        for finding in &mut results.unused_svelte_events {
994            $visit(
995                &finding.event.path,
996                finding.event.line,
997                &mut finding.actions,
998            );
999        }
1000        for finding in &mut results.unused_effect_layers {
1001            $visit(
1002                &finding.layer.path,
1003                finding.layer.line,
1004                &mut finding.actions,
1005            );
1006        }
1007        for finding in &mut results.duplicate_export_aliases {
1008            $visit(
1009                &finding.alias.path,
1010                finding.alias.line,
1011                &mut finding.actions,
1012            );
1013        }
1014        for finding in &mut results.unused_tagged_errors {
1015            $visit(
1016                &finding.error.path,
1017                finding.error.line,
1018                &mut finding.actions,
1019            );
1020        }
1021        for finding in &mut results.unproduced_catch_tags {
1022            $visit(
1023                &finding.catch_tag.path,
1024                finding.catch_tag.line,
1025                &mut finding.actions,
1026            );
1027        }
1028        for finding in &mut results.unused_server_actions {
1029            $visit(
1030                &finding.action.path,
1031                finding.action.line,
1032                &mut finding.actions,
1033            );
1034        }
1035        for finding in &mut results.unused_load_data_keys {
1036            $visit(&finding.key.path, finding.key.line, &mut finding.actions);
1037        }
1038        for finding in &mut results.prop_drilling_chains {
1039            if let Some(hop) = finding.chain.hops.first() {
1040                $visit(&hop.file, hop.line, &mut finding.actions);
1041            }
1042        }
1043        for finding in &mut results.thin_wrappers {
1044            $visit(
1045                &finding.wrapper.file,
1046                finding.wrapper.line,
1047                &mut finding.actions,
1048            );
1049        }
1050        for finding in &mut results.duplicate_prop_shapes {
1051            $visit(
1052                &finding.shape.file,
1053                finding.shape.line,
1054                &mut finding.actions,
1055            );
1056        }
1057    }};
1058}
1059
1060/// Merge same-line suppress actions so multi-kind findings share one comment.
1061///
1062/// This runs on typed `AnalysisResults` before serialization. It replaces the
1063/// older JSON-object walk for normal check output and keeps the action contract
1064/// owned by the output builders.
1065pub fn harmonize_multi_kind_suppress_line_actions(results: &mut AnalysisResults) {
1066    let mut anchors: BTreeMap<SuppressAnchor, Vec<String>> = BTreeMap::new();
1067    collect_dead_code_suppress_line_anchors(results, &mut anchors);
1068    retain_multi_kind_anchors(&mut anchors);
1069    if anchors.is_empty() {
1070        return;
1071    }
1072    rewrite_dead_code_suppress_line_actions(results, &anchors);
1073}
1074
1075/// Merge same-line suppress actions across dead-code and health sections.
1076///
1077/// Combined and audit output can surface both dead-code and complexity findings
1078/// anchored to the same source line. This keeps the single-line suppress hint
1079/// typed until the final JSON serialization step.
1080pub fn harmonize_dead_code_health_suppress_line_actions(
1081    dead_code: Option<&mut AnalysisResults>,
1082    health: Option<&mut HealthReport>,
1083) {
1084    let mut anchors: BTreeMap<SuppressAnchor, Vec<String>> = BTreeMap::new();
1085    if let Some(results) = dead_code.as_deref() {
1086        collect_dead_code_suppress_line_anchors(results, &mut anchors);
1087    }
1088    if let Some(report) = health.as_deref() {
1089        collect_health_suppress_line_anchors(report, &mut anchors);
1090    }
1091
1092    retain_multi_kind_anchors(&mut anchors);
1093    if anchors.is_empty() {
1094        return;
1095    }
1096
1097    if let Some(results) = dead_code {
1098        rewrite_dead_code_suppress_line_actions(results, &anchors);
1099    }
1100    if let Some(report) = health {
1101        rewrite_health_suppress_line_actions(report, &anchors);
1102    }
1103}
1104
1105fn retain_multi_kind_anchors(anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>) {
1106    anchors.retain(|_, kinds| {
1107        sort_suppression_kinds(kinds);
1108        kinds.dedup();
1109        kinds.len() > 1
1110    });
1111}
1112
1113fn collect_dead_code_suppress_line_anchors(
1114    results: &AnalysisResults,
1115    anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>,
1116) {
1117    visit_suppress_line_findings!(results, |path: &Path, line, actions: &[IssueAction]| {
1118        collect_action_kinds(path, line, actions, anchors);
1119    });
1120}
1121
1122fn rewrite_dead_code_suppress_line_actions(
1123    results: &mut AnalysisResults,
1124    anchors: &BTreeMap<SuppressAnchor, Vec<String>>,
1125) {
1126    visit_suppress_line_findings_mut!(
1127        results,
1128        |path: &Path, line, actions: &mut Vec<IssueAction>| {
1129            let anchor = suppress_anchor(path, line);
1130            if let Some(kinds) = anchors.get(&anchor) {
1131                let comment = format!("// fallow-ignore-next-line {}", kinds.join(", "));
1132                rewrite_action_comments(actions, &comment);
1133            }
1134        }
1135    );
1136}
1137
1138fn collect_health_suppress_line_anchors(
1139    report: &HealthReport,
1140    anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>,
1141) {
1142    for finding in &report.findings {
1143        collect_health_action_kinds(
1144            &finding.violation.path,
1145            finding.violation.line,
1146            &finding.actions,
1147            anchors,
1148        );
1149    }
1150    for finding in &report.prop_drilling_chains {
1151        if let Some(hop) = finding.chain.hops.first() {
1152            collect_action_kinds(&hop.file, hop.line, &finding.actions, anchors);
1153        }
1154    }
1155}
1156
1157fn rewrite_health_suppress_line_actions(
1158    report: &mut HealthReport,
1159    anchors: &BTreeMap<SuppressAnchor, Vec<String>>,
1160) {
1161    for finding in &mut report.findings {
1162        let anchor = suppress_anchor(&finding.violation.path, finding.violation.line);
1163        if let Some(kinds) = anchors.get(&anchor) {
1164            let comment = format!("// fallow-ignore-next-line {}", kinds.join(", "));
1165            rewrite_health_action_comments(&mut finding.actions, &comment);
1166        }
1167    }
1168    for finding in &mut report.prop_drilling_chains {
1169        if let Some(hop) = finding.chain.hops.first() {
1170            let anchor = suppress_anchor(&hop.file, hop.line);
1171            if let Some(kinds) = anchors.get(&anchor) {
1172                let comment = format!("// fallow-ignore-next-line {}", kinds.join(", "));
1173                rewrite_action_comments(&mut finding.actions, &comment);
1174            }
1175        }
1176    }
1177}
1178
1179fn collect_action_kinds(
1180    path: &Path,
1181    line: u32,
1182    actions: &[IssueAction],
1183    anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>,
1184) {
1185    for action in actions {
1186        if let Some(comment) = suppress_line_comment(action) {
1187            let kinds = anchors.entry(suppress_anchor(path, line)).or_default();
1188            for kind in parse_suppress_line_comment(comment) {
1189                if !kinds.iter().any(|existing| existing == &kind) {
1190                    kinds.push(kind);
1191                }
1192            }
1193        }
1194    }
1195}
1196
1197fn collect_health_action_kinds(
1198    path: &Path,
1199    line: u32,
1200    actions: &[HealthFindingAction],
1201    anchors: &mut BTreeMap<SuppressAnchor, Vec<String>>,
1202) {
1203    for action in actions {
1204        if let Some(comment) = health_suppress_line_comment(action) {
1205            let kinds = anchors.entry(suppress_anchor(path, line)).or_default();
1206            for kind in parse_suppress_line_comment(comment) {
1207                if !kinds.iter().any(|existing| existing == &kind) {
1208                    kinds.push(kind);
1209                }
1210            }
1211        }
1212    }
1213}
1214
1215fn rewrite_action_comments(actions: &mut [IssueAction], comment: &str) {
1216    for action in actions {
1217        if let IssueAction::SuppressLine(suppress) = action {
1218            suppress.comment = comment.to_string();
1219        }
1220    }
1221}
1222
1223fn rewrite_health_action_comments(actions: &mut [HealthFindingAction], comment: &str) {
1224    for action in actions {
1225        if matches!(action.kind, HealthFindingActionType::SuppressLine) {
1226            action.comment = Some(comment.to_string());
1227        }
1228    }
1229}
1230
1231fn suppress_anchor(path: &Path, line: u32) -> SuppressAnchor {
1232    (path.display().to_string(), line)
1233}
1234
1235fn suppress_line_comment(action: &IssueAction) -> Option<&str> {
1236    match action {
1237        IssueAction::SuppressLine(action) => Some(&action.comment),
1238        _ => None,
1239    }
1240}
1241
1242fn health_suppress_line_comment(action: &HealthFindingAction) -> Option<&str> {
1243    matches!(action.kind, HealthFindingActionType::SuppressLine)
1244        .then_some(())
1245        .and(action.comment.as_deref())
1246}
1247
1248fn parse_suppress_line_comment(comment: &str) -> Vec<String> {
1249    comment
1250        .strip_prefix("// fallow-ignore-next-line ")
1251        .map(|rest| {
1252            rest.split(|c: char| c == ',' || c.is_whitespace())
1253                .filter(|token| !token.is_empty())
1254                .map(str::to_string)
1255                .collect()
1256        })
1257        .unwrap_or_default()
1258}
1259
1260fn sort_suppression_kinds(kinds: &mut [String]) {
1261    kinds.sort_by_key(|kind| suppression_kind_rank(kind));
1262}
1263
1264fn suppression_kind_rank(kind: &str) -> usize {
1265    match kind {
1266        "unused-file" => 0,
1267        "unused-export" => 1,
1268        "unused-type" => 2,
1269        "private-type-leak" => 3,
1270        "unused-enum-member" => 4,
1271        "unused-class-member" => 5,
1272        "unused-store-member" => 6,
1273        "unresolved-import" => 7,
1274        "unlisted-dependency" => 8,
1275        "duplicate-export" => 9,
1276        "circular-dependency" => 10,
1277        "re-export-cycle" => 11,
1278        "boundary-violation" => 12,
1279        "code-duplication" => 13,
1280        "complexity" => 14,
1281        "unprovided-inject" => 15,
1282        "unrendered-component" => 16,
1283        "unused-server-action" => 17,
1284        "deprecated-export-in-use" => 18,
1285        "package-cycle" => 19,
1286        "unused-namespace-member" => 20,
1287        "unused-protected-class-member" => 21,
1288        "namespace-escape" => 22,
1289        _ => usize::MAX,
1290    }
1291}
1292
1293/// Compute the per-category `CheckSummary` from analysis results.
1294#[must_use]
1295pub fn build_check_summary(results: &AnalysisResults) -> CheckSummary {
1296    CheckSummary {
1297        total_issues: results.total_issues(),
1298        prop_drilling_chains: results.enforced_prop_drilling_count(),
1299        thin_wrappers: results.enforced_thin_wrapper_count(),
1300        duplicate_prop_shapes: results.enforced_duplicate_prop_shape_count(),
1301        unused_files: results.unused_files.len(),
1302        unused_exports: results.unused_exports.len(),
1303        unused_types: results.unused_types.len(),
1304        private_type_leaks: results.private_type_leaks.len(),
1305        deprecated_exports_in_use: results.deprecated_exports_in_use.len(),
1306        unused_dependencies: results.unused_dependencies.len()
1307            + results.unused_dev_dependencies.len()
1308            + results.unused_optional_dependencies.len(),
1309        unused_enum_members: results.unused_enum_members.len(),
1310        unused_class_members: results.unused_class_members.len(),
1311        unused_namespace_members: results.unused_namespace_members.len(),
1312        unused_protected_class_members: results.unused_protected_class_members.len(),
1313        namespace_escapes: results.namespace_escapes.len(),
1314        test_only_exports: results.test_only_exports.len(),
1315        unused_store_members: results.unused_store_members.len(),
1316        unresolved_imports: results.unresolved_imports.len(),
1317        unlisted_dependencies: results.unlisted_dependencies.len(),
1318        unlisted_binaries: results.unlisted_binaries.len(),
1319        duplicate_exports: results.duplicate_exports.len(),
1320        duplicate_export_aliases: results.duplicate_export_aliases.len(),
1321        type_only_dependencies: results.type_only_dependencies.len(),
1322        test_only_dependencies: results.test_only_dependencies.len(),
1323        dev_dependencies_in_production: results.dev_dependencies_in_production.len(),
1324        circular_dependencies: results.circular_dependencies.len(),
1325        re_export_cycles: results.re_export_cycles.len(),
1326        package_cycles: results.package_cycles.len(),
1327        boundary_violations: results.boundary_violations.len(),
1328        boundary_coverage_violations: results.boundary_coverage_violations.len(),
1329        boundary_call_violations: results.boundary_call_violations.len(),
1330        policy_violations: results.policy_violations.len(),
1331        stale_suppressions: results.stale_suppressions.len(),
1332        unused_catalog_entries: results.unused_catalog_entries.len(),
1333        empty_catalog_groups: results.empty_catalog_groups.len(),
1334        unresolved_catalog_references: results.unresolved_catalog_references.len(),
1335        unused_dependency_overrides: results.unused_dependency_overrides.len(),
1336        misconfigured_dependency_overrides: results.misconfigured_dependency_overrides.len(),
1337        invalid_client_exports: results.invalid_client_exports.len(),
1338        mixed_client_server_barrels: results.mixed_client_server_barrels.len(),
1339        misplaced_directives: results.misplaced_directives.len(),
1340        unprovided_injects: results.unprovided_injects.len(),
1341        unrendered_components: results.unrendered_components.len(),
1342        unused_component_props: results.unused_component_props.len(),
1343        absent_component_props: results.absent_component_props.len(),
1344        constant_parameters: results.constant_parameters.len(),
1345        unused_component_emits: results.unused_component_emits.len(),
1346        unused_component_inputs: results.unused_component_inputs.len(),
1347        unused_component_outputs: results.unused_component_outputs.len(),
1348        unused_svelte_events: results.unused_svelte_events.len(),
1349        unused_effect_layers: results.unused_effect_layers.len(),
1350        unused_tagged_errors: results.unused_tagged_errors.len(),
1351        unproduced_catch_tags: results.unproduced_catch_tags.len(),
1352        unused_server_actions: results.unused_server_actions.len(),
1353        unused_load_data_keys: results.unused_load_data_keys.len(),
1354        route_collisions: results.route_collisions.len(),
1355        dynamic_segment_name_conflicts: results.dynamic_segment_name_conflicts.len(),
1356    }
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361    use super::*;
1362    use crate::{ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding};
1363    use fallow_types::output_dead_code::{
1364        ReachabilityCaveat, UnusedExportFinding, UnusedFileFinding, UnusedTypeFinding,
1365    };
1366    use fallow_types::results::{UnusedExport, UnusedFile};
1367    use fallow_types::workspace::WorkspaceDiagnosticKind;
1368
1369    #[test]
1370    fn build_check_output_counts_issues_and_entry_points() {
1371        let mut results = AnalysisResults::default();
1372        results
1373            .unused_files
1374            .push(UnusedFileFinding::with_actions(UnusedFile {
1375                path: "src/unused.ts".into(),
1376            }));
1377
1378        let output = build_check_output(CheckOutputInput {
1379            schema_version: 7,
1380            version: "0.0.0".to_string(),
1381            elapsed: Duration::from_millis(42),
1382            results,
1383            config_fixable: false,
1384            meta: None,
1385            workspace_diagnostics: Vec::new(),
1386            next_steps: Vec::new(),
1387        });
1388
1389        assert_eq!(output.schema_version.0, 7);
1390        assert_eq!(output.total_issues, 1);
1391        assert_eq!(output.summary.unused_files, 1);
1392        assert_eq!(output.elapsed_ms.0, 42);
1393    }
1394
1395    #[test]
1396    fn build_check_output_harmonizes_multi_kind_suppress_actions_typed() {
1397        let mut results = AnalysisResults::default();
1398        let path = std::path::PathBuf::from("/project/src/shared.ts");
1399        results
1400            .unused_exports
1401            .push(UnusedExportFinding::with_actions(UnusedExport {
1402                path: path.clone(),
1403                export_name: "value".to_string(),
1404                is_type_only: false,
1405                line: 7,
1406                col: 0,
1407                span_start: 0,
1408                is_re_export: false,
1409                deprecated: false,
1410                deprecated_reason: None,
1411            }));
1412        results
1413            .unused_types
1414            .push(UnusedTypeFinding::with_actions(UnusedExport {
1415                path,
1416                export_name: "TypeOnly".to_string(),
1417                is_type_only: true,
1418                line: 7,
1419                col: 0,
1420                span_start: 0,
1421                is_re_export: false,
1422                deprecated: false,
1423                deprecated_reason: None,
1424            }));
1425
1426        let output = build_check_output(CheckOutputInput {
1427            schema_version: 7,
1428            version: "0.0.0".to_string(),
1429            elapsed: Duration::from_millis(42),
1430            results,
1431            config_fixable: false,
1432            meta: None,
1433            workspace_diagnostics: Vec::new(),
1434            next_steps: Vec::new(),
1435        });
1436
1437        let export_comment = suppress_comment(&output.results.unused_exports[0].actions);
1438        let type_comment = suppress_comment(&output.results.unused_types[0].actions);
1439        assert_eq!(
1440            export_comment,
1441            Some("// fallow-ignore-next-line unused-export, unused-type")
1442        );
1443        assert_eq!(type_comment, export_comment);
1444    }
1445
1446    #[test]
1447    fn harmonize_dead_code_health_suppress_actions_typed() {
1448        let mut results = AnalysisResults::default();
1449        let path = std::path::PathBuf::from("/project/src/shared.ts");
1450        results
1451            .unused_exports
1452            .push(UnusedExportFinding::with_actions(UnusedExport {
1453                path: path.clone(),
1454                export_name: "value".to_string(),
1455                is_type_only: false,
1456                line: 7,
1457                col: 0,
1458                span_start: 0,
1459                is_re_export: false,
1460                deprecated: false,
1461                deprecated_reason: None,
1462            }));
1463        let mut health = HealthReport {
1464            findings: vec![HealthFinding::new(
1465                ComplexityViolation {
1466                    path,
1467                    name: "expensive".to_string(),
1468                    line: 7,
1469                    col: 0,
1470                    cyclomatic: 22,
1471                    standard_cyclomatic: None,
1472                    cognitive: 18,
1473                    line_count: 40,
1474                    param_count: 1,
1475                    react_hook_count: 0,
1476                    react_jsx_max_depth: 0,
1477                    react_prop_count: 0,
1478                    react_hook_profile: None,
1479                    exceeded: ExceededThreshold::Both,
1480                    severity: FindingSeverity::High,
1481                    effective_severity: None,
1482                    crap: None,
1483                    mutation: None,
1484                    coverage_pct: None,
1485                    coverage_tier: None,
1486                    coverage_source: None,
1487                    inherited_from: None,
1488                    component_rollup: None,
1489                    contributions: Vec::new(),
1490                    effective_thresholds: None,
1491                    threshold_source: None,
1492                    override_comment_line: None,
1493                    max_file_lines: None,
1494                },
1495                vec![HealthFindingAction {
1496                    kind: HealthFindingActionType::SuppressLine,
1497                    auto_fixable: false,
1498                    description: "Suppress with an inline comment above the function declaration"
1499                        .to_string(),
1500                    note: None,
1501                    comment: Some("// fallow-ignore-next-line complexity".to_string()),
1502                    placement: Some("above-function-declaration".to_string()),
1503                    target_path: None,
1504                }],
1505                None,
1506            )],
1507            ..HealthReport::default()
1508        };
1509
1510        harmonize_dead_code_health_suppress_line_actions(Some(&mut results), Some(&mut health));
1511
1512        assert_eq!(
1513            suppress_comment(&results.unused_exports[0].actions),
1514            Some("// fallow-ignore-next-line unused-export, complexity")
1515        );
1516        assert_eq!(
1517            health.findings[0].actions[0].comment.as_deref(),
1518            Some("// fallow-ignore-next-line unused-export, complexity")
1519        );
1520    }
1521
1522    #[test]
1523    fn check_json_output_uses_output_owned_root_contract() {
1524        let output = build_check_output(CheckOutputInput {
1525            schema_version: 7,
1526            version: "0.0.0".to_string(),
1527            elapsed: Duration::from_millis(42),
1528            results: AnalysisResults::default(),
1529            config_fixable: false,
1530            meta: None,
1531            workspace_diagnostics: Vec::new(),
1532            next_steps: Vec::new(),
1533        });
1534
1535        let value = serialize_check_json_output(output, Some("run-check"))
1536            .expect("check output should serialize");
1537
1538        assert_eq!(value["kind"], "dead-code");
1539        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-check");
1540    }
1541
1542    #[test]
1543    fn architecture_json_output_has_architecture_kind_and_version() {
1544        let envelope = CheckEnvelope::Architecture;
1545        let output = build_check_output(CheckOutputInput {
1546            schema_version: envelope.schema_version(),
1547            version: "0.0.0".to_string(),
1548            elapsed: Duration::from_millis(1),
1549            results: AnalysisResults::default(),
1550            config_fixable: false,
1551            meta: None,
1552            workspace_diagnostics: Vec::new(),
1553            next_steps: Vec::new(),
1554        });
1555
1556        let value = serialize_architecture_json_output(output, Some("run-arch"))
1557            .expect("architecture output should serialize");
1558
1559        assert_eq!(value["kind"], "architecture");
1560        assert_eq!(value["schema_version"], ARCHITECTURE_SCHEMA_VERSION);
1561        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-arch");
1562    }
1563
1564    #[test]
1565    fn check_envelope_names_each_family_member() {
1566        assert_eq!(CheckEnvelope::DeadCode.kind(), "dead-code");
1567        assert_eq!(CheckEnvelope::DeadCode.grouped_kind(), "dead-code-grouped");
1568        assert_eq!(
1569            CheckEnvelope::DeadCode.schema_version(),
1570            CHECK_SCHEMA_VERSION
1571        );
1572        assert_eq!(CheckEnvelope::DeadCode.command(), "dead-code");
1573        assert_eq!(CheckEnvelope::Architecture.kind(), "architecture");
1574        assert_eq!(
1575            CheckEnvelope::Architecture.grouped_kind(),
1576            "architecture-grouped"
1577        );
1578        assert_eq!(
1579            CheckEnvelope::Architecture.schema_version(),
1580            ARCHITECTURE_SCHEMA_VERSION
1581        );
1582        assert_eq!(CheckEnvelope::Architecture.command(), "architecture");
1583    }
1584
1585    /// The degraded-parse caveat has to travel WITH the finding it can distort,
1586    /// because a reader looking at a `delete-file` action never sees the
1587    /// diagnostic at the other end of the envelope. It is advisory about the
1588    /// FINDING and decisive only about the MUTATION: the actions array keeps
1589    /// its shape and its order, the mutating action reports
1590    /// `auto_fixable: false`, and a clean finding stays byte-identical.
1591    #[test]
1592    fn reachability_caveats_are_absent_when_clean_and_named_when_flagged() {
1593        let mut results = AnalysisResults::default();
1594        results
1595            .unused_files
1596            .push(UnusedFileFinding::with_actions(UnusedFile {
1597                path: "/project/src/clean.ts".into(),
1598            }));
1599        let mut flagged = UnusedFileFinding::with_actions(UnusedFile {
1600            path: "/project/src/orphan.ts".into(),
1601        });
1602        flagged.reachability_caveats = vec![
1603            ReachabilityCaveat::IncompleteFileAnalysis,
1604            ReachabilityCaveat::IncompleteImportGraph,
1605        ];
1606        results.unused_files.push(flagged);
1607
1608        let output = build_check_output(CheckOutputInput {
1609            schema_version: 7,
1610            version: "0.0.0".to_string(),
1611            elapsed: Duration::from_millis(1),
1612            results,
1613            config_fixable: false,
1614            meta: None,
1615            workspace_diagnostics: Vec::new(),
1616            next_steps: Vec::new(),
1617        });
1618        let value =
1619            serialize_check_json_output(output, None).expect("dead-code output should serialize");
1620
1621        let entries = value["unused_files"]
1622            .as_array()
1623            .expect("unused_files array")
1624            .clone();
1625        let find = |name: &str| {
1626            entries
1627                .iter()
1628                .find(|entry| {
1629                    entry["path"]
1630                        .as_str()
1631                        .is_some_and(|path| path.ends_with(name))
1632                })
1633                .cloned()
1634                .expect("finding present")
1635        };
1636
1637        assert!(
1638            find("clean.ts").get("reachability_caveats").is_none(),
1639            "a finding with no caveat must keep the previous wire shape exactly"
1640        );
1641
1642        let flagged = find("orphan.ts");
1643        assert_eq!(
1644            flagged["reachability_caveats"],
1645            serde_json::json!(["incomplete-file-analysis", "incomplete-import-graph"]),
1646            "both caveats are named on the wire, in declaration order"
1647        );
1648        assert_eq!(
1649            flagged["actions"].as_array().map(Vec::len),
1650            Some(2),
1651            "the caveat never trims the finding's actions"
1652        );
1653        assert_eq!(
1654            flagged["actions"][0]["type"], "delete-file",
1655            "nor reorders them, so a consumer reading actions[0].type is unaffected"
1656        );
1657        assert_eq!(
1658            flagged["actions"][0]["auto_fixable"],
1659            serde_json::json!(false),
1660            "but the mutation it gates must not advertise itself as applicable"
1661        );
1662    }
1663
1664    #[test]
1665    fn grouped_check_json_output_uses_output_owned_root_contract() {
1666        let root = std::path::Path::new("/project");
1667        let output = CheckGroupedOutput {
1668            gate_outcomes: None,
1669            request_outcomes: None,
1670            package_baselines: Vec::new(),
1671            baseline_staleness: None,
1672            finding_id_query: None,
1673            schema_version: SchemaVersion(7),
1674            version: ToolVersion("0.0.0".to_string()),
1675            elapsed_ms: ElapsedMs(1),
1676            grouped_by: GroupByMode::Directory,
1677            total_issues: 0,
1678            groups: Vec::new(),
1679            unused_load_data_keys_global_abstain: false,
1680            cascade_hidden: 0,
1681            meta: None,
1682            workspace_diagnostics: vec![WorkspaceDiagnostic::new(
1683                root,
1684                root.join("src/unreadable.ts"),
1685                WorkspaceDiagnosticKind::SourceReadFailure {
1686                    error: "permission denied".to_string(),
1687                },
1688            )],
1689            next_steps: Vec::new(),
1690        };
1691
1692        let value = serialize_check_grouped_json_output(output, Some("run-group"))
1693            .expect("grouped check output should serialize");
1694
1695        assert_eq!(value["kind"], "dead-code-grouped");
1696        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-group");
1697        assert_eq!(
1698            value["workspace_diagnostics"][0]["path"],
1699            "/project/src/unreadable.ts"
1700        );
1701        assert_eq!(
1702            value["workspace_diagnostics"][0]["kind"],
1703            "source-read-failure"
1704        );
1705    }
1706
1707    #[test]
1708    fn architecture_grouped_json_output_has_grouped_kind() {
1709        let output = CheckGroupedOutput {
1710            gate_outcomes: None,
1711            request_outcomes: None,
1712            package_baselines: Vec::new(),
1713            baseline_staleness: None,
1714            finding_id_query: None,
1715            schema_version: SchemaVersion(ARCHITECTURE_SCHEMA_VERSION),
1716            version: ToolVersion("0.0.0".to_string()),
1717            elapsed_ms: ElapsedMs(1),
1718            grouped_by: GroupByMode::Directory,
1719            total_issues: 0,
1720            groups: Vec::new(),
1721            unused_load_data_keys_global_abstain: false,
1722            cascade_hidden: 0,
1723            meta: None,
1724            workspace_diagnostics: Vec::new(),
1725            next_steps: Vec::new(),
1726        };
1727        let grouped = serialize_architecture_grouped_json_output(output, None)
1728            .expect("grouped architecture output should serialize");
1729        assert_eq!(grouped["kind"], "architecture-grouped");
1730        assert_eq!(grouped["schema_version"], ARCHITECTURE_SCHEMA_VERSION);
1731    }
1732
1733    #[test]
1734    fn workspace_diagnostics_serialize_typed_kind_path_message() {
1735        let root = std::path::Path::new("/project");
1736        let output = build_check_output(CheckOutputInput {
1737            schema_version: 7,
1738            version: "0.0.0".to_string(),
1739            elapsed: Duration::from_millis(1),
1740            results: AnalysisResults::default(),
1741            config_fixable: false,
1742            meta: None,
1743            workspace_diagnostics: vec![WorkspaceDiagnostic::new(
1744                root,
1745                root.join("packages/legacy"),
1746                WorkspaceDiagnosticKind::UndeclaredWorkspace,
1747            )],
1748            next_steps: Vec::new(),
1749        });
1750
1751        let value = serde_json::to_value(&output).expect("check output serializes");
1752        let diag = &value["workspace_diagnostics"][0];
1753        assert_eq!(diag["kind"], "undeclared-workspace");
1754        assert!(
1755            diag["path"]
1756                .as_str()
1757                .is_some_and(|path| path.contains("packages/legacy")),
1758            "path field is carried verbatim: {diag}"
1759        );
1760        assert!(
1761            diag["message"]
1762                .as_str()
1763                .is_some_and(|message| message.contains("packages/legacy")),
1764            "message is rendered from kind + path: {diag}"
1765        );
1766    }
1767
1768    #[test]
1769    fn source_read_failure_workspace_diagnostic_serializes_error_payload() {
1770        let root = std::path::Path::new("/project");
1771        let output = build_check_output(CheckOutputInput {
1772            schema_version: 7,
1773            version: "0.0.0".to_string(),
1774            elapsed: Duration::from_millis(1),
1775            results: AnalysisResults::default(),
1776            config_fixable: false,
1777            meta: None,
1778            workspace_diagnostics: vec![WorkspaceDiagnostic::new(
1779                root,
1780                root.join("src/removed.ts"),
1781                WorkspaceDiagnosticKind::SourceReadFailure {
1782                    error: "No such file or directory".to_string(),
1783                },
1784            )],
1785            next_steps: Vec::new(),
1786        });
1787
1788        let value = serde_json::to_value(&output).expect("check output serializes");
1789        let diagnostic = &value["workspace_diagnostics"][0];
1790        assert_eq!(diagnostic["kind"], "source-read-failure");
1791        assert_eq!(diagnostic["error"], "No such file or directory");
1792        assert!(
1793            diagnostic["message"]
1794                .as_str()
1795                .is_some_and(|message| message.contains("src/removed.ts"))
1796        );
1797    }
1798
1799    fn suppress_comment(actions: &[IssueAction]) -> Option<&str> {
1800        actions.iter().find_map(|action| match action {
1801            IssueAction::SuppressLine(action) => Some(action.comment.as_str()),
1802            _ => None,
1803        })
1804    }
1805}