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