Skip to main content

fallow_types/
results.rs

1//! Analysis result types for all issue categories.
2
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::extract::{
8    MemberKind, SecurityControlKind, SecurityUrlShape, SkippedSecurityCalleeExpressionKind,
9    SkippedSecurityCalleeReason,
10};
11use crate::output::{
12    FixAction, FixActionType, IssueAction, SuppressLineAction, SuppressLineKind, SuppressLineScope,
13};
14use crate::output_dead_code::{
15    AbsentComponentPropFinding, BoundaryCallViolationFinding, BoundaryCoverageViolationFinding,
16    BoundaryViolationFinding, CircularDependencyFinding, DeprecatedExportInUseFinding,
17    DevDependencyInProductionFinding, DuplicateExportAliasFinding, DuplicateExportFinding,
18    DuplicatePropShapeFinding, DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding,
19    InvalidClientExportFinding, MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
20    MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
21    PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding, RouteCollisionFinding,
22    TestOnlyDependencyFinding, ThinWrapperFinding, TypeOnlyDependencyFinding,
23    UnlistedBinaryFinding, UnlistedDependencyFinding, UnprovidedInjectFinding,
24    UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding, UnresolvedImportFinding,
25    UnusedCatalogEntryFinding, UnusedClassMemberFinding, UnusedComponentEmitFinding,
26    UnusedComponentInputFinding, UnusedComponentOutputFinding, UnusedComponentPropFinding,
27    UnusedDependencyFinding, UnusedDependencyOverrideFinding, UnusedDevDependencyFinding,
28    UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
29    UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding, UnusedServerActionFinding,
30    UnusedStoreMemberFinding, UnusedSvelteEventFinding, UnusedTypeFinding,
31};
32pub use crate::output_dead_code::{
33    UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
34};
35#[path = "results_component_health.rs"]
36mod component_health;
37
38pub use component_health::ERROR_ONLY_RESULT_KEYS;
39
40use crate::serde_path;
41use crate::suppress::closest_known_kind_name;
42#[path = "results_ignore_findings.rs"]
43mod ignore_findings;
44use ignore_findings::classify_ignore_findings_fields;
45
46#[path = "results_merge_parts.rs"]
47mod merge_parts;
48use merge_parts::split_merge_parts;
49
50/// Summary of detected entry points, grouped by discovery source.
51///
52/// Used to surface entry-point detection status in human and JSON output,
53/// so library authors can verify that fallow found the right entry points.
54#[derive(Debug, Clone, Default)]
55#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
56pub struct EntryPointSummary {
57    /// Total number of entry points detected.
58    pub total: usize,
59    /// Breakdown by source category (e.g., "package.json" -> 3, "plugin" -> 12).
60    /// Sorted by key for deterministic output.
61    pub by_source: Vec<(String, usize)>,
62}
63
64/// Per-component render fan-in counts plus the precomputed concentration aggregates.
65///
66/// DESCRIPTIVE blast-radius signal (NOT a rule, finding, or threshold): the
67/// component-graph analogue of module-level fan-in. Module fan-in counts
68/// importing MODULES; render fan-in counts JSX render CALL SITES (a shared
69/// `<Button>` is rendered in far more places than it is imported).
70///
71/// `per_component` is the internal carrier (keyed for hotspot path annotation),
72/// `#[serde(skip)]` on [`AnalysisResults`] so it never appears under bare
73/// `fallow` / `audit`; the aggregates feed the descriptive `VitalSigns` block
74/// (`p95_render_fan_in` / `render_fan_in_high_pct` / `max_render_fan_in`).
75///
76/// UNDERCOUNT is the documented safe direction: a child rendered via a JSX
77/// spread, a dynamic / `createElement(var)` form, or a member-expression tag
78/// (`<Lib.Button/>`) is not resolved by the shared `ChildResolver` and so
79/// increments no component's fan-in. A true high-fan-in component can only be
80/// undersold, never falsely flagged. A rare name-collision over-credit is
81/// possible via the default-import sole-component fallback (inherited verbatim
82/// from the prop-drilling / thin-wrapper resolver); low-harm for a descriptive,
83/// non-gating metric.
84#[derive(Debug, Clone, Default)]
85pub struct RenderFanInMetric {
86    /// Per-component render-site + distinct-parent counts. Keyed by
87    /// `(component file path, component name)` so the hotspot surface can map a
88    /// file back to its top component's fan-in. Components rendered nowhere ARE
89    /// included as a real `0` so the percentile distribution is not skewed.
90    pub per_component: Vec<RenderFanInComponent>,
91    /// 95th-percentile DISTINCT-PARENTS render fan-in across components (the
92    /// per-component distribution analogue of the module-fan-in p95). `None` on
93    /// an empty population. Mirrors `compute_coupling_concentration`.
94    pub p95_distinct_parents: Option<u32>,
95    /// Percentage of components whose distinct-parents render fan-in exceeds the
96    /// `max(p95, 10)` threshold (the same floor coupling concentration uses).
97    /// `None` on an empty population.
98    pub high_pct: Option<f64>,
99    /// The single highest DISTINCT-PARENTS count across all components (the
100    /// headline blast-radius number: the most distinct render LOCATIONS any one
101    /// component is rendered from, the honest edit-ripple count). `None` on an
102    /// empty population. `render_sites` (incl. repeats) is secondary per-component
103    /// context, never the headline.
104    pub max_distinct_parents: Option<u32>,
105}
106
107/// One component's render fan-in detail: how many JSX render SITES target it and
108/// how many DISTINCT parent components render it.
109#[derive(Debug, Clone)]
110pub struct RenderFanInComponent {
111    /// Absolute path of the file declaring the component.
112    pub file: PathBuf,
113    /// The component name.
114    pub component: String,
115    /// Total JSX render SITES that resolve to this component across the project
116    /// (each capitalized / member JSX tag is one site). SECONDARY context ("incl.
117    /// repeats"): a single parent rendering one child five times is five sites but
118    /// one distinct parent, so render_sites overcounts blast radius.
119    pub render_sites: u32,
120    /// Distinct `(parent_file, parent_component)` keys that render this
121    /// component. The HEADLINE blast-radius axis: the honest count of distinct
122    /// render LOCATIONS, the percentiled distribution analogue of "distinct importers".
123    pub distinct_parents: u32,
124}
125
126/// Per-kind hook counts for a React component, summarized from `hook_uses`.
127/// DESCRIPTIVE editor context (the LSP code-lens hook breakdown), never a
128/// finding, severity, or `total_issues` input. `custom` collects every
129/// `use*`-named call that is not one of the four built-ins.
130#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct ReactHookSummary {
132    /// `useState(...)` call count.
133    pub state: u16,
134    /// `useEffect(...)` call count.
135    pub effect: u16,
136    /// `useMemo(...)` call count.
137    pub memo: u16,
138    /// `useCallback(...)` call count.
139    pub callback: u16,
140    /// Count of any other `use*`-named call (a custom hook).
141    pub custom: u16,
142}
143
144/// A prop-drilling trace for a prop at the ROOT of a forwarding chain.
145/// DESCRIPTIVE ambient editor context (the LSP per-prop hover): the prop is
146/// forwarded unchanged through `depth` components before a component
147/// substantively consumes it. Reuses the `prop-drilling` chain machinery's
148/// abstain ladder (spread / `cloneElement` / dynamic / provider-in-subtree drop
149/// the whole chain), so the trace is honest. NOT a finding (the opt-in
150/// `prop-drilling` rule owns the finding); this rides the `#[serde(skip)]`
151/// `ReactComponentIntel` carrier.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct ReactPropDrill {
154    /// The chain depth = number of components the prop is forwarded THROUGH
155    /// (source + intermediates + consumer), matching `PropDrillingChain.depth`.
156    pub depth: u32,
157    /// The ordered component names from source to consumer (`hops[0]` owns the
158    /// prop, the last consumes it).
159    pub hops: Vec<String>,
160}
161
162/// Per-prop usage intelligence for one React component prop. DESCRIPTIVE editor
163/// context (the LSP per-prop hover): whether the prop is read in the component
164/// body and how many render sites pass it. NOT a finding (the
165/// `unused-component-prop` React arm owns the deadness rule); this is ambient
166/// signal. `anchor_line` / `anchor_col` follow the same convention the React
167/// `unused-component-prop` findings use (1-based line, byte-derived col from
168/// `byte_offset_to_line_col`).
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct ReactPropIntel {
171    /// The declared prop name.
172    pub name: String,
173    /// 1-based line of the prop declaration (anchors the hover).
174    pub anchor_line: u32,
175    /// Column of the prop declaration (byte-derived, matching the React
176    /// `unused-component-prop` finding convention).
177    pub anchor_col: u32,
178    /// Whether the prop is referenced in the component body (`used_in_script`
179    /// for the React arm: a resolved reference to the destructured local).
180    pub used_in_body: bool,
181    /// Count of render sites (test/spec/story/fixture files excluded) whose
182    /// passed-attribute set contains this prop name.
183    pub passed_from_sites: u32,
184    /// A prop-drilling trace, present only when this prop is the ROOT of a
185    /// forwarding chain that reaches a consumer through `>= N` pass-through
186    /// components. `None` for an ordinary prop. Test/spec/story/fixture source
187    /// components never carry a drill trace.
188    pub drill: Option<ReactPropDrill>,
189}
190
191/// Per-component render + prop + hook intelligence for one React component.
192/// DESCRIPTIVE ambient editor context surfaced by the LSP (a component summary
193/// code lens plus per-prop hovers), NOT a finding, IssueKind, severity, or
194/// `total_issues` input. Carried in-process on the `#[serde(skip)]`
195/// `AnalysisResults::react_component_intel` field (like
196/// [`RenderFanInMetric`]); never serialized, so bare `fallow` / `audit` and the
197/// JSON / schema surface are untouched.
198///
199/// Counts are HONEST: test/spec/story/fixture render sites are excluded from
200/// `render_sites`, `distinct_parents`, and per-prop `passed_from_sites`, and
201/// `distinct_parents` (not the repeat-inflated `render_sites`) is the headline,
202/// mirroring the render-fan-in metric's discipline.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct ReactComponentIntel {
205    /// Absolute path of the file declaring the component.
206    pub path: PathBuf,
207    /// The component name.
208    pub component_name: String,
209    /// 1-based line of the component definition (anchors the code lens).
210    pub anchor_line: u32,
211    /// Column of the component definition (byte-derived).
212    pub anchor_col: u32,
213    /// Total JSX render SITES that resolve to this component (each capitalized /
214    /// member JSX tag is one site). SECONDARY context: a single parent rendering
215    /// the child five times is five sites but one distinct parent.
216    pub render_sites: u32,
217    /// Distinct `(parent_file, parent_component)` keys rendering this component.
218    /// The HEADLINE blast-radius count (never the repeat-inflated site count).
219    pub distinct_parents: u32,
220    /// Number of declared props on this component.
221    pub prop_count: u16,
222    /// Per-kind hook counts.
223    pub hooks: ReactHookSummary,
224    /// Per-prop usage intelligence (one entry per declared prop).
225    pub props: Vec<ReactPropIntel>,
226}
227
228/// Complete analysis results.
229///
230/// # Examples
231///
232/// ```
233/// use fallow_types::output_dead_code::UnusedFileFinding;
234/// use fallow_types::results::{AnalysisResults, UnusedFile};
235/// use std::path::PathBuf;
236///
237/// let mut results = AnalysisResults::default();
238/// assert_eq!(results.total_issues(), 0);
239/// assert!(!results.has_issues());
240///
241/// results
242///     .unused_files
243///     .push(UnusedFileFinding::with_actions(UnusedFile {
244///         path: PathBuf::from("src/dead.ts"),
245///     }));
246/// assert_eq!(results.total_issues(), 1);
247/// assert!(results.has_issues());
248/// ```
249#[derive(Debug, Default, Clone, Serialize, Deserialize)]
250#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
251pub struct AnalysisResults {
252    /// Files not reachable from any entry point. Wrapped in
253    /// [`UnusedFileFinding`] so each entry carries a typed `actions` array
254    /// natively, replacing the pre-2.76 post-pass injection.
255    pub unused_files: Vec<UnusedFileFinding>,
256    /// Exports never imported by other modules. Wrapped in
257    /// [`UnusedExportFinding`] so each entry carries a typed `actions`
258    /// array natively.
259    pub unused_exports: Vec<UnusedExportFinding>,
260    /// Type exports never imported by other modules. Wrapped in
261    /// [`UnusedTypeFinding`]: the inner [`UnusedExport`] struct is shared
262    /// with `unused_exports` but the wrapper emits a type-targeted fix
263    /// description.
264    pub unused_types: Vec<UnusedTypeFinding>,
265    /// Exported symbols whose public signature references same-file private
266    /// types. Wrapped in [`PrivateTypeLeakFinding`] so each entry carries a
267    /// typed `actions` array natively.
268    pub private_type_leaks: Vec<PrivateTypeLeakFinding>,
269    /// Exports marked `@deprecated` that still have at least one consumer in
270    /// a reachable file. Wrapped in [`DeprecatedExportInUseFinding`]. Opt-in: the
271    /// `deprecated-exports-in-use` rule defaults to `off`.
272    #[serde(default)]
273    pub deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
274    /// Dependencies listed in package.json but never imported. Wrapped in
275    /// [`UnusedDependencyFinding`] so each entry carries a typed `actions`
276    /// array natively. The fix action swaps from `remove-dependency` to
277    /// `move-dependency` when `used_in_workspaces` is non-empty.
278    pub unused_dependencies: Vec<UnusedDependencyFinding>,
279    /// Dev dependencies listed in package.json but never imported. Wrapped
280    /// in [`UnusedDevDependencyFinding`]: same bare struct as
281    /// `unused_dependencies` with a `devDependencies`-targeted fix
282    /// description.
283    pub unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
284    /// Optional dependencies listed in package.json but never imported.
285    /// Wrapped in [`UnusedOptionalDependencyFinding`] with an
286    /// `optionalDependencies`-targeted fix description.
287    pub unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
288    /// Enum members never accessed. Wrapped in
289    /// [`UnusedEnumMemberFinding`] so each entry carries a typed `actions`
290    /// array natively.
291    pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
292    /// Class members never accessed. Wrapped in
293    /// [`UnusedClassMemberFinding`]: same inner [`UnusedMember`] struct as
294    /// `unused_enum_members`, with a class-targeted fix description and the
295    /// `auto_fixable: false` default to reflect dependency-injection
296    /// patterns.
297    pub unused_class_members: Vec<UnusedClassMemberFinding>,
298    /// Exported members of an exported TypeScript namespace that no code
299    /// reads. Wrapped in [`UnusedNamespaceMemberFinding`]: same inner
300    /// [`UnusedMember`] struct as `unused_enum_members`. `member_name` is the
301    /// dotted path from the exported namespace (`Inner.x`).
302    #[serde(default, skip_serializing_if = "Vec::is_empty")]
303    pub unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
304    /// Store members (Pinia `state` / `getters` / `actions` key, or a
305    /// setup-store returned key) declared but never accessed by any consumer
306    /// project-wide. Wrapped in [`UnusedStoreMemberFinding`]: same inner
307    /// [`UnusedMember`] struct as `unused_class_members`, with a
308    /// store-targeted fix description. Cross-graph: the store binding is
309    /// imported (the module is reachable) yet a specific member is dead.
310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
311    pub unused_store_members: Vec<UnusedStoreMemberFinding>,
312    /// Import specifiers that could not be resolved. Wrapped in
313    /// [`UnresolvedImportFinding`] so each entry carries a typed `actions`
314    /// array natively.
315    pub unresolved_imports: Vec<UnresolvedImportFinding>,
316    /// Dependencies used in code but not listed in package.json. Wrapped in
317    /// [`UnlistedDependencyFinding`].
318    pub unlisted_dependencies: Vec<UnlistedDependencyFinding>,
319    /// Binaries that package.json scripts or process calls run, but that no
320    /// installed or listed package provides. Wrapped in
321    /// [`UnlistedBinaryFinding`].
322    #[serde(default)]
323    pub unlisted_binaries: Vec<UnlistedBinaryFinding>,
324    /// Exports with the same name across multiple modules. Wrapped in
325    /// [`DuplicateExportFinding`] so each entry carries a typed `actions`
326    /// array natively, with the position-0 `add-to-config` `ignoreExports`
327    /// snippet wired in at wrapper construction.
328    pub duplicate_exports: Vec<DuplicateExportFinding>,
329    /// One module that exports one binding under two or more names. Wrapped
330    /// in [`DuplicateExportAliasFinding`]. Default severity is `warn`.
331    #[serde(default, skip_serializing_if = "Vec::is_empty")]
332    pub duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
333    /// Production dependencies only used via type-only imports (could be
334    /// devDependencies). Only populated in production mode. Wrapped in
335    /// [`TypeOnlyDependencyFinding`].
336    pub type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
337    /// Production dependencies only imported by test files (could be
338    /// devDependencies). Wrapped in [`TestOnlyDependencyFinding`].
339    #[serde(default)]
340    pub test_only_dependencies: Vec<TestOnlyDependencyFinding>,
341    /// devDependencies imported by production (non-test, non-config) source code
342    /// via a runtime/value import; they should be promoted to dependencies.
343    /// The promote-side mirror of [`TestOnlyDependencyFinding`]. Wrapped in
344    /// [`DevDependencyInProductionFinding`].
345    #[serde(default)]
346    pub dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
347    /// Circular dependency chains detected in the module graph. Wrapped in
348    /// [`CircularDependencyFinding`] so each entry carries a typed `actions`
349    /// array natively.
350    pub circular_dependencies: Vec<CircularDependencyFinding>,
351    /// Cycles or self-loops in the re-export edge subgraph (barrel files
352    /// re-exporting from each other in a loop). Wrapped in
353    /// [`ReExportCycleFinding`] so each entry carries a typed `actions`
354    /// array natively (a `refactor-re-export-cycle` informational primary
355    /// plus a `suppress-file` secondary; cycles are file-scoped so a single
356    /// suppression breaks the cycle).
357    #[serde(default)]
358    pub re_export_cycles: Vec<ReExportCycleFinding>,
359    /// Dependency cycles between workspace packages, built from resolved
360    /// cross-package imports. Wrapped in [`PackageCycleFinding`] so each
361    /// entry carries a typed `actions` array natively.
362    #[serde(default)]
363    pub package_cycles: Vec<PackageCycleFinding>,
364    /// Imports that cross architecture boundary rules. Wrapped in
365    /// [`BoundaryViolationFinding`] so each entry carries a typed `actions`
366    /// array natively.
367    #[serde(default)]
368    pub boundary_violations: Vec<BoundaryViolationFinding>,
369    /// Files that matched no architecture boundary zone while
370    /// `boundaries.coverage.requireAllFiles` was enabled.
371    #[serde(default)]
372    pub boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
373    /// Calls from zoned files to callees forbidden for that zone via
374    /// `boundaries.calls.forbidden`. Wrapped in
375    /// [`BoundaryCallViolationFinding`] so each entry carries a typed
376    /// `actions` array natively.
377    #[serde(default)]
378    pub boundary_call_violations: Vec<BoundaryCallViolationFinding>,
379    /// Banned calls, imports, and catalogue-derived effects matched by
380    /// declarative rule packs
381    /// (`rulePacks` config). Wrapped in [`PolicyViolationFinding`] so each
382    /// entry carries a typed `actions` array natively. Each finding carries
383    /// its effective per-rule severity.
384    #[serde(default)]
385    pub policy_violations: Vec<PolicyViolationFinding>,
386    /// Suppression comments or JSDoc tags that no longer match any issue.
387    #[serde(default)]
388    pub stale_suppressions: Vec<StaleSuppression>,
389    /// Entries in package manager catalog sections not referenced by any
390    /// workspace package via the catalog: protocol. Supports
391    /// `pnpm-workspace.yaml` catalogs and Bun root `package.json` catalogs.
392    /// Wrapped in [`UnusedCatalogEntryFinding`] so each entry carries a typed
393    /// `actions` array natively, with per-instance `auto_fixable` derived
394    /// from `hardcoded_consumers` and the catalog source file.
395    #[serde(default)]
396    pub unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
397    /// Named groups under package manager catalogs sections that declare no
398    /// package entries. The top-level catalog: map is not reported. Wrapped in
399    /// [`EmptyCatalogGroupFinding`].
400    #[serde(default)]
401    pub empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
402    /// Workspace package.json references to catalogs (`catalog:` or
403    /// `catalog:<name>`) that do not declare the consumed package. The package
404    /// manager install will error until the named catalog grows to include the
405    /// package or the reference is switched / removed. Wrapped in
406    /// [`UnresolvedCatalogReferenceFinding`] with the discriminated
407    /// `add-catalog-entry` / `update-catalog-reference` primary at position 0.
408    #[serde(default)]
409    pub unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
410    /// Entries in pnpm-workspace.yaml's overrides section, package.json's
411    /// pnpm.overrides block, npm or Bun's top-level overrides object, or Bun's
412    /// top-level resolutions object,
413    /// whose target package is not declared by any workspace package and is
414    /// not present in pnpm-lock.yaml, package-lock.json, npm-shrinkwrap.json,
415    /// or bun.lock. Default severity is warn because projects without a
416    /// readable lockfile fall back to manifest-only checks; the hint field
417    /// flags those conservative cases. When the only lockfile is bun's binary
418    /// bun.lockb, resolution cannot be read and the check emits nothing.
419    /// Wrapped in [`UnusedDependencyOverrideFinding`].
420    #[serde(default)]
421    pub unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
422    /// Package-manager override or resolution entries whose key or value does
423    /// not parse in the declaration source's grammar (empty key, empty value,
424    /// malformed selector, unbalanced parent matcher). The package manager may
425    /// reject or ignore these at install time. Default severity is error. Wrapped in
426    /// [`MisconfiguredDependencyOverrideFinding`].
427    #[serde(default)]
428    pub misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
429    /// `"use client"` files that export a Next.js server-only / route-segment
430    /// config name (e.g. `metadata`, `revalidate`, `GET`). Next.js rejects this
431    /// at build time. Wrapped in [`InvalidClientExportFinding`] so each entry
432    /// carries a typed `actions` array natively. Default severity is `warn`.
433    #[serde(default)]
434    pub invalid_client_exports: Vec<InvalidClientExportFinding>,
435    /// Barrel files that re-export BOTH a `"use client"` origin module AND a
436    /// server-only origin module (the Next.js App Router footgun). Wrapped in
437    /// [`MixedClientServerBarrelFinding`] so each entry carries a typed
438    /// `actions` array natively. Default severity is `warn`.
439    #[serde(default)]
440    pub mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
441    /// `"use client"` / `"use server"` directives written as expression
442    /// statements after a non-directive statement, so the RSC bundler parses
443    /// them as ordinary strings and silently ignores them. Wrapped in
444    /// [`MisplacedDirectiveFinding`] so each entry carries a typed `actions`
445    /// array natively. Default severity is `warn`.
446    #[serde(default)]
447    pub misplaced_directives: Vec<MisplacedDirectiveFinding>,
448    /// Vue `inject(KEY)` / Svelte `getContext(KEY)` calls whose symbol KEY is
449    /// provided nowhere in the project (the injected-never-provided dead-half).
450    /// Wrapped in [`UnprovidedInjectFinding`] so each entry carries a typed
451    /// `actions` array natively. Default severity is `warn`.
452    #[serde(default, skip_serializing_if = "Vec::is_empty")]
453    pub unprovided_injects: Vec<UnprovidedInjectFinding>,
454    /// Vue/Svelte single-file components that are reachable but rendered nowhere
455    /// (the imported-but-never-rendered dead-half). Wrapped in
456    /// [`UnrenderedComponentFinding`] so each entry carries a typed `actions`
457    /// array natively. Default severity is `warn`.
458    #[serde(default, skip_serializing_if = "Vec::is_empty")]
459    pub unrendered_components: Vec<UnrenderedComponentFinding>,
460    /// Next.js App Router route files that resolve to the same URL within one
461    /// app-root (a guaranteed `next build` failure). Wrapped in
462    /// [`RouteCollisionFinding`] so each entry carries a typed `actions` array
463    /// natively. One finding per colliding file. Default severity is `warn`.
464    #[serde(default)]
465    pub route_collisions: Vec<RouteCollisionFinding>,
466    /// Sibling Next.js dynamic route segments at one tree position using
467    /// different param spellings (a dev / runtime error; `next build` does NOT
468    /// catch it). Wrapped in [`DynamicSegmentNameConflictFinding`] so each entry
469    /// carries a typed `actions` array natively. Default severity is `warn`.
470    #[serde(default)]
471    pub dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
472    /// Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, and React props
473    /// referenced nowhere in their own component. Wrapped in
474    /// [`UnusedComponentPropFinding`] so each entry carries a typed `actions`
475    /// array natively. Default severity is `warn`.
476    #[serde(default, skip_serializing_if = "Vec::is_empty")]
477    pub unused_component_props: Vec<UnusedComponentPropFinding>,
478    /// Used optional component inputs absent from inspected reachable callers. Off by default.
479    #[serde(default, skip_serializing_if = "Vec::is_empty")]
480    pub absent_component_props: Vec<AbsentComponentPropFinding>,
481    /// Vue `<script setup>` `defineEmits` events emitted nowhere in their own SFC
482    /// (no `emit('<name>')` call). Wrapped in [`UnusedComponentEmitFinding`] so
483    /// each entry carries a typed `actions` array natively. Default severity is
484    /// `warn`.
485    #[serde(default, skip_serializing_if = "Vec::is_empty")]
486    pub unused_component_emits: Vec<UnusedComponentEmitFinding>,
487    /// Angular `@Input()` / signal `input()` / `model()` inputs read nowhere in
488    /// their own component (neither the template nor the class body). Wrapped in
489    /// [`UnusedComponentInputFinding`] so each entry carries a typed `actions`
490    /// array natively. Default severity is `warn`.
491    #[serde(default, skip_serializing_if = "Vec::is_empty")]
492    pub unused_component_inputs: Vec<UnusedComponentInputFinding>,
493    /// Angular `@Output()` / signal `output()` outputs emitted nowhere in their
494    /// own component (no `this.<output>.emit(...)`). Wrapped in
495    /// [`UnusedComponentOutputFinding`] so each entry carries a typed `actions`
496    /// array natively. Default severity is `warn`.
497    #[serde(default, skip_serializing_if = "Vec::is_empty")]
498    pub unused_component_outputs: Vec<UnusedComponentOutputFinding>,
499    /// Svelte components dispatching a custom event via `createEventDispatcher()`
500    /// whose event name is listened to nowhere project-wide (cross-file
501    /// dead-output direction). Wrapped in [`UnusedSvelteEventFinding`] so each
502    /// entry carries a typed `actions` array natively. Default severity is
503    /// `warn`.
504    #[serde(default, skip_serializing_if = "Vec::is_empty")]
505    pub unused_svelte_events: Vec<UnusedSvelteEventFinding>,
506    /// Effect layers composed only into other layers that nothing uses.
507    /// Gated on the project declaring `effect`. Default severity is `warn`.
508    #[serde(default, skip_serializing_if = "Vec::is_empty")]
509    pub unused_effect_layers: Vec<UnusedEffectLayerFinding>,
510    /// Effect tagged error classes that only type positions or `catchTag`
511    /// handlers reference. Gated on the project declaring `effect`. Default
512    /// severity is `warn`.
513    #[serde(default, skip_serializing_if = "Vec::is_empty")]
514    pub unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
515    /// `catchTag` / `catchTags` handlers for a project tag that no code
516    /// produces and that no `unused_tagged_errors` entry covers. Gated on the
517    /// project declaring `effect`. Default severity is `warn`.
518    #[serde(default, skip_serializing_if = "Vec::is_empty")]
519    pub unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
520    /// Next.js Server Actions (exports of `"use server"` files) that no code in
521    /// the project references. Reclassified out of `unused_exports` for
522    /// `"use server"` files. Wrapped in [`UnusedServerActionFinding`] so each
523    /// entry carries a typed `actions` array natively. Default severity is
524    /// `warn`.
525    #[serde(default, skip_serializing_if = "Vec::is_empty")]
526    pub unused_server_actions: Vec<UnusedServerActionFinding>,
527    /// SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object keys
528    /// read by no consumer. Wrapped in [`UnusedLoadDataKeyFinding`] so each entry
529    /// carries a typed `actions` array natively. Default severity is `warn`.
530    #[serde(default, skip_serializing_if = "Vec::is_empty")]
531    pub unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
532    /// `true` when the `unused-load-data-key` detector abstained project-wide
533    /// because a whole-object use of `page.data` / `$page.data` was seen
534    /// somewhere (S1 observability: an empty `unused_load_data_keys` with this
535    /// flag set is NOT a clean bill, it means the rule could not run safely).
536    /// Serialized only when `true` so the default JSON contract is unchanged.
537    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
538    pub unused_load_data_keys_global_abstain: bool,
539    /// React/Preact props forwarded unchanged through `>= N` intermediate
540    /// pass-through components until a consumer (located per-chain records).
541    /// Wrapped in [`PropDrillingChainFinding`] so each entry carries a typed
542    /// `actions` array natively. Health signal: the rule defaults to `off`
543    /// (opt-in), so this is dormant and populated ONLY when the user enables it.
544    #[serde(default, skip_serializing_if = "Vec::is_empty")]
545    pub prop_drilling_chains: Vec<PropDrillingChainFinding>,
546    /// React/Preact components whose entire body is a single spread-forwarded
547    /// child render (`return <Child {...props}/>`): pure structural indirection,
548    /// a candidate for inlining at call sites. Wrapped in [`ThinWrapperFinding`]
549    /// so each entry carries a typed `actions` array natively. Health signal: the
550    /// rule defaults to `off` (opt-in), so this is dormant and populated ONLY
551    /// when the user enables it.
552    #[serde(default, skip_serializing_if = "Vec::is_empty")]
553    pub thin_wrappers: Vec<ThinWrapperFinding>,
554    /// React/Preact components that participate in a duplicate-prop-shape group:
555    /// three or more components across two or more files whose statically-known
556    /// prop NAME set is identical after stripping ubiquitous DOM / passthrough
557    /// names (a missing shared `Props` type / base component). Wrapped in
558    /// [`DuplicatePropShapeFinding`] so each entry carries a typed `actions`
559    /// array and its sibling roster natively. Health signal: the rule defaults to
560    /// `off` (opt-in), so this is dormant and populated ONLY when the user
561    /// enables it.
562    #[serde(default, skip_serializing_if = "Vec::is_empty")]
563    pub duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
564    /// Number of `unused_exports`, `unused_types`, `unused_class_members` and
565    /// `unused_enum_members` findings that this run did not report because
566    /// their file is an unused file. Deleting the file removes them, so they
567    /// add no information. `--show-cascade` or the `showCascade` config key
568    /// keeps them in the report, and then this count is zero. The count is
569    /// taken after the scope and the rules and before a baseline. Serialized
570    /// only when not zero, so a run without such findings keeps its JSON.
571    #[serde(default, skip_serializing_if = "is_zero")]
572    pub cascade_hidden: usize,
573    /// In-process state of the unused-file cascade filter: the unused-file
574    /// candidates of the detector and the findings that the filter removed.
575    /// Skipped in machine output; [`Self::cascade_hidden`] is the public count.
576    #[serde(skip)]
577    #[cfg_attr(feature = "schema", schemars(skip))]
578    pub cascade: CascadeState,
579    /// Number of suppression entries that matched an issue during analysis.
580    /// Human output uses this for the suppression footer; it is skipped in
581    /// machine output to avoid changing the public JSON issue contract.
582    #[serde(skip)]
583    pub suppression_count: usize,
584    /// Number of component props exempted from `unused-component-props` this run
585    /// because their local destructure binding name matched
586    /// `unusedComponentProps.ignorePattern`. Drives a human-output note so a
587    /// typo'd pattern (matching nothing) is not a silent no-op; skipped in
588    /// machine output, like [`Self::suppression_count`].
589    #[serde(skip)]
590    pub unused_component_props_exempted: usize,
591    /// Suppression comments present in analyzed files this run (every present
592    /// marker, all kinds, not only consumed ones). Internal: read in-process by
593    /// `fallow impact` to distinguish a genuinely resolved finding from one
594    /// silenced by a `fallow-ignore`. Skipped during serialization, like
595    /// [`Self::suppression_count`], so the public JSON output contract is
596    /// unchanged.
597    #[serde(skip)]
598    pub active_suppressions: Vec<ActiveSuppression>,
599    /// Detected feature flag patterns. Advisory output, not included in issue counts.
600    /// Skipped during default serialization: injected separately in JSON output when enabled.
601    #[serde(skip)]
602    pub feature_flags: Vec<FeatureFlag>,
603    /// Local security candidates (e.g. `client-server-leak`). CANDIDATES for
604    /// downstream agent verification, NOT verified vulnerabilities. Off by
605    /// default; populated only when the corresponding `security_*` rule is
606    /// enabled (forced on by `fallow security`). Excluded from `total_issues`
607    /// and skipped during serialization so they never surface under bare
608    /// `fallow` or the `audit` gate; the `fallow security` command reads this
609    /// field and emits its own envelope. Mirrors [`Self::feature_flags`].
610    #[serde(skip)]
611    pub security_findings: Vec<SecurityFinding>,
612    /// In-band blind-spot count: number of `"use client"` files whose transitive
613    /// import cone contains a dynamic `import()` the reachability BFS cannot
614    /// follow. Surfaced by `fallow security` so a leak hidden behind an
615    /// unresolved edge is never silently reported as "clean". Skipped during
616    /// serialization like [`Self::security_findings`].
617    #[serde(skip)]
618    pub security_unresolved_edge_files: usize,
619    /// In-band blind-spot count: number of sink-shaped nodes the catalogue
620    /// detector could not flatten to a static callee path (dynamic dispatch,
621    /// computed members, aliased bindings). Surfaced by `fallow security` so an
622    /// empty catalogue result with a non-zero count is not reported as "clean".
623    /// Skipped during serialization like [`Self::security_findings`].
624    #[serde(skip)]
625    pub security_unresolved_callee_sites: usize,
626    /// Location samples for sink-shaped nodes the catalogue detector could not
627    /// flatten to a static callee path. Skipped during default serialization;
628    /// `fallow security` summarizes this metadata in its own envelope.
629    #[serde(skip)]
630    pub security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
631    /// Usage counts for all exports across the project. Used by the LSP for Code Lens.
632    /// Not included in issue counts -- this is metadata, not an issue type.
633    /// Skipped during serialization: this is internal LSP data, not part of the JSON output schema.
634    #[serde(skip)]
635    pub export_usages: Vec<ExportUsage>,
636    /// Summary of detected entry points, grouped by discovery source.
637    /// Not included in issue counts -- this is informational metadata.
638    /// Skipped during serialization: rendered separately in JSON output.
639    #[serde(skip)]
640    pub entry_point_summary: Option<EntryPointSummary>,
641    /// Internal component render metrics, exposed through health aggregates.
642    #[serde(skip)]
643    pub render_fan_in: Option<RenderFanInMetric>,
644    /// Internal component intelligence used by editor overlays.
645    #[serde(skip)]
646    pub react_component_intel: Vec<ReactComponentIntel>,
647    /// Reachable files in the discovery scope, captured before report filters.
648    /// Empty or deserialized scope cannot grant semantic usage credit.
649    #[serde(skip)]
650    #[cfg_attr(feature = "schema", schemars(skip))]
651    pub semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
652    /// Plugin-owned framework contracts carried only into the optional
653    /// semantic reconciliation pass.
654    #[serde(skip)]
655    #[cfg_attr(feature = "schema", schemars(skip))]
656    pub semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
657}
658
659#[expect(
660    clippy::trivially_copy_pass_by_ref,
661    reason = "serde `skip_serializing_if` passes the field by reference"
662)]
663const fn is_zero(count: &usize) -> bool {
664    *count == 0
665}
666
667/// In-process state of the unused-file cascade filter.
668///
669/// An unused file in the report makes every export and member finding in it
670/// redundant: deleting the file removes them. The filter needs the files that
671/// a suppression comment removed from the report, and it keeps the findings
672/// that it removed, because a baseline entry for such a finding still
673/// describes the project and must not count as stale.
674#[derive(Debug, Default, Clone)]
675pub struct CascadeState {
676    /// Unused files whose finding an inline `fallow-ignore-file unused-file`
677    /// comment suppressed. The cascade filter treats them as reported, so a
678    /// suppression comment never makes a hidden finding visible again. An
679    /// issue-type selection without unused files clears this list.
680    pub suppressed_unused_files: Vec<PathBuf>,
681    /// The findings that the filter removed from the report.
682    pub hidden: CascadeHiddenFindings,
683}
684
685/// Findings that the unused-file cascade filter removed from the report.
686#[derive(Debug, Default, Clone)]
687pub struct CascadeHiddenFindings {
688    /// Hidden `unused_exports` findings.
689    pub unused_exports: Vec<UnusedExportFinding>,
690    /// Hidden `unused_types` findings.
691    pub unused_types: Vec<UnusedTypeFinding>,
692    /// Hidden `unused_enum_members` findings.
693    pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
694    /// Hidden `unused_class_members` findings.
695    pub unused_class_members: Vec<UnusedClassMemberFinding>,
696}
697
698impl CascadeHiddenFindings {
699    /// Number of hidden findings.
700    #[must_use]
701    pub fn len(&self) -> usize {
702        self.unused_exports.len()
703            + self.unused_types.len()
704            + self.unused_enum_members.len()
705            + self.unused_class_members.len()
706    }
707
708    /// Whether the filter removed no finding.
709    #[must_use]
710    pub fn is_empty(&self) -> bool {
711        self.len() == 0
712    }
713
714    /// The hidden findings as a result set, for a baseline comparison.
715    #[must_use]
716    pub fn to_results(&self) -> AnalysisResults {
717        AnalysisResults {
718            unused_exports: self.unused_exports.clone(),
719            unused_types: self.unused_types.clone(),
720            unused_enum_members: self.unused_enum_members.clone(),
721            unused_class_members: self.unused_class_members.clone(),
722            ..AnalysisResults::default()
723        }
724    }
725
726    fn extend(&mut self, other: Self) {
727        self.unused_exports.extend(other.unused_exports);
728        self.unused_types.extend(other.unused_types);
729        self.unused_enum_members.extend(other.unused_enum_members);
730        self.unused_class_members.extend(other.unused_class_members);
731    }
732}
733
734/// Move each finding that `covered` selects from `findings` to `hidden`.
735fn move_covered<T>(
736    findings: &mut Vec<T>,
737    hidden: &mut Vec<T>,
738    path_of: impl Fn(&T) -> &Path,
739    covered: &dyn Fn(&Path) -> bool,
740) {
741    let (moved, kept): (Vec<T>, Vec<T>) = std::mem::take(findings)
742        .into_iter()
743        .partition(|finding| covered(path_of(finding)));
744    *findings = kept;
745    hidden.extend(moved);
746}
747
748struct AnalysisResultsCoreMergeParts {
749    unused_files: Vec<UnusedFileFinding>,
750    unused_exports: Vec<UnusedExportFinding>,
751    unused_types: Vec<UnusedTypeFinding>,
752    private_type_leaks: Vec<PrivateTypeLeakFinding>,
753    deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
754    unused_enum_members: Vec<UnusedEnumMemberFinding>,
755    unused_class_members: Vec<UnusedClassMemberFinding>,
756    unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
757    unused_store_members: Vec<UnusedStoreMemberFinding>,
758    unresolved_imports: Vec<UnresolvedImportFinding>,
759    boundary_violations: Vec<BoundaryViolationFinding>,
760    boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
761    boundary_call_violations: Vec<BoundaryCallViolationFinding>,
762    policy_violations: Vec<PolicyViolationFinding>,
763    stale_suppressions: Vec<StaleSuppression>,
764}
765
766struct AnalysisResultsGraphMergeParts {
767    unused_dependencies: Vec<UnusedDependencyFinding>,
768    unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
769    unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
770    unlisted_dependencies: Vec<UnlistedDependencyFinding>,
771    unlisted_binaries: Vec<UnlistedBinaryFinding>,
772    duplicate_exports: Vec<DuplicateExportFinding>,
773    duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
774    type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
775    test_only_dependencies: Vec<TestOnlyDependencyFinding>,
776    dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
777    circular_dependencies: Vec<CircularDependencyFinding>,
778    re_export_cycles: Vec<ReExportCycleFinding>,
779    package_cycles: Vec<PackageCycleFinding>,
780}
781
782struct AnalysisResultsWorkspaceMergeParts {
783    unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
784    empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
785    unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
786    unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
787    misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
788}
789
790struct AnalysisResultsFrameworkMergeParts {
791    invalid_client_exports: Vec<InvalidClientExportFinding>,
792    mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
793    misplaced_directives: Vec<MisplacedDirectiveFinding>,
794    unprovided_injects: Vec<UnprovidedInjectFinding>,
795    unrendered_components: Vec<UnrenderedComponentFinding>,
796    route_collisions: Vec<RouteCollisionFinding>,
797    dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
798    unused_component_props: Vec<UnusedComponentPropFinding>,
799    absent_component_props: Vec<AbsentComponentPropFinding>,
800    unused_component_emits: Vec<UnusedComponentEmitFinding>,
801    unused_component_inputs: Vec<UnusedComponentInputFinding>,
802    unused_component_outputs: Vec<UnusedComponentOutputFinding>,
803    unused_svelte_events: Vec<UnusedSvelteEventFinding>,
804    unused_effect_layers: Vec<UnusedEffectLayerFinding>,
805    unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
806    unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
807    unused_server_actions: Vec<UnusedServerActionFinding>,
808    unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
809    unused_load_data_keys_global_abstain: bool,
810    prop_drilling_chains: Vec<PropDrillingChainFinding>,
811    thin_wrappers: Vec<ThinWrapperFinding>,
812    duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
813}
814
815struct AnalysisResultsMetadataMergeParts {
816    cascade_hidden: usize,
817    cascade: CascadeState,
818    suppression_count: usize,
819    unused_component_props_exempted: usize,
820    active_suppressions: Vec<ActiveSuppression>,
821    feature_flags: Vec<FeatureFlag>,
822    security_findings: Vec<SecurityFinding>,
823    security_unresolved_edge_files: usize,
824    security_unresolved_callee_sites: usize,
825    security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
826    export_usages: Vec<ExportUsage>,
827    entry_point_summary: Option<EntryPointSummary>,
828    render_fan_in: Option<RenderFanInMetric>,
829    react_component_intel: Vec<ReactComponentIntel>,
830    semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
831    semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
832}
833
834macro_rules! counted_analysis_result_fields {
835    ($callback:ident $(, $arg:expr)? ) => {
836        $callback! {
837            $($arg,)?
838            unused_files => "unused_files",
839            unused_exports => "unused_exports",
840            unused_types => "unused_types",
841            private_type_leaks => "private_type_leaks",
842            deprecated_exports_in_use => "deprecated_exports_in_use",
843            unused_dependencies => "unused_dependencies",
844            unused_dev_dependencies => "unused_dev_dependencies",
845            unused_optional_dependencies => "unused_optional_dependencies",
846            unused_enum_members => "unused_enum_members",
847            unused_class_members => "unused_class_members",
848            unused_namespace_members => "unused_namespace_members",
849            unused_store_members => "unused_store_members",
850            unresolved_imports => "unresolved_imports",
851            unlisted_dependencies => "unlisted_dependencies",
852            unlisted_binaries => "unlisted_binaries",
853            duplicate_exports => "duplicate_exports",
854            duplicate_export_aliases => "duplicate_export_aliases",
855            type_only_dependencies => "type_only_dependencies",
856            test_only_dependencies => "test_only_dependencies",
857            dev_dependencies_in_production => "dev_dependencies_in_production",
858            circular_dependencies => "circular_dependencies",
859            re_export_cycles => "re_export_cycles",
860            package_cycles => "package_cycles",
861            boundary_violations => "boundary_violations",
862            boundary_coverage_violations => "boundary_coverage_violations",
863            boundary_call_violations => "boundary_call_violations",
864            policy_violations => "policy_violations",
865            stale_suppressions => "stale_suppressions",
866            unused_catalog_entries => "unused_catalog_entries",
867            empty_catalog_groups => "empty_catalog_groups",
868            unresolved_catalog_references => "unresolved_catalog_references",
869            unused_dependency_overrides => "unused_dependency_overrides",
870            misconfigured_dependency_overrides => "misconfigured_dependency_overrides",
871            invalid_client_exports => "invalid_client_exports",
872            mixed_client_server_barrels => "mixed_client_server_barrels",
873            misplaced_directives => "misplaced_directives",
874            unprovided_injects => "unprovided_injects",
875            unrendered_components => "unrendered_components",
876            route_collisions => "route_collisions",
877            dynamic_segment_name_conflicts => "dynamic_segment_name_conflicts",
878            unused_component_props => "unused_component_props",
879            absent_component_props => "absent_component_props",
880            unused_component_emits => "unused_component_emits",
881            unused_component_inputs => "unused_component_inputs",
882            unused_component_outputs => "unused_component_outputs",
883            unused_svelte_events => "unused_svelte_events",
884            unused_effect_layers => "unused_effect_layers",
885            unused_tagged_errors => "unused_tagged_errors",
886            unproduced_catch_tags => "unproduced_catch_tags",
887            unused_server_actions => "unused_server_actions",
888            unused_load_data_keys => "unused_load_data_keys",
889        }
890    };
891}
892
893trait FindingIgnorePolicy {
894    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool;
895}
896
897macro_rules! impl_single_source_dead_code {
898    ($($finding:ty => $($field:ident).+),+ $(,)?) => {
899        $(
900            impl FindingIgnorePolicy for $finding {
901                fn should_ignore(
902                    &self,
903                    predicate: &mut impl FnMut(&Path) -> bool,
904                ) -> bool {
905                    predicate(&self.$($field).+)
906                }
907            }
908        )+
909    };
910}
911
912impl_single_source_dead_code! {
913    UnusedFileFinding => file.path,
914    UnusedExportFinding => export.path,
915    UnusedTypeFinding => export.path,
916    PrivateTypeLeakFinding => leak.path,
917    DeprecatedExportInUseFinding => export.path,
918    UnusedEnumMemberFinding => member.path,
919    UnusedClassMemberFinding => member.path,
920    UnusedNamespaceMemberFinding => member.path,
921    UnusedStoreMemberFinding => member.path,
922    UnresolvedImportFinding => import.path,
923    UnprovidedInjectFinding => inject.path,
924    UnrenderedComponentFinding => component.path,
925    UnusedComponentPropFinding => prop.path,
926    AbsentComponentPropFinding => prop.path,
927    UnusedComponentEmitFinding => emit.path,
928    UnusedComponentInputFinding => input.path,
929    UnusedComponentOutputFinding => output.path,
930    UnusedSvelteEventFinding => event.path,
931    UnusedEffectLayerFinding => layer.path,
932    DuplicateExportAliasFinding => alias.path,
933    UnusedTaggedErrorFinding => error.path,
934    UnproducedCatchTagFinding => catch_tag.path,
935    UnusedServerActionFinding => action.path,
936    UnusedLoadDataKeyFinding => key.path,
937    ThinWrapperFinding => wrapper.file,
938    DuplicatePropShapeFinding => shape.file,
939}
940
941macro_rules! impl_never_ignored_finding {
942    ($($finding:ty),+ $(,)?) => {
943        $(
944            impl FindingIgnorePolicy for $finding {
945                fn should_ignore(
946                    &self,
947                    _predicate: &mut impl FnMut(&Path) -> bool,
948                ) -> bool {
949                    false
950                }
951            }
952        )+
953    };
954}
955
956impl_never_ignored_finding! {
957    UnusedDependencyFinding,
958    UnusedDevDependencyFinding,
959    UnusedOptionalDependencyFinding,
960    TypeOnlyDependencyFinding,
961    TestOnlyDependencyFinding,
962    DevDependencyInProductionFinding,
963    UnusedCatalogEntryFinding,
964    EmptyCatalogGroupFinding,
965    UnresolvedCatalogReferenceFinding,
966    UnusedDependencyOverrideFinding,
967    MisconfiguredDependencyOverrideFinding,
968    BoundaryViolationFinding,
969    BoundaryCoverageViolationFinding,
970    BoundaryCallViolationFinding,
971    PolicyViolationFinding,
972    StaleSuppression,
973    InvalidClientExportFinding,
974    MixedClientServerBarrelFinding,
975    MisplacedDirectiveFinding,
976    RouteCollisionFinding,
977    DynamicSegmentNameConflictFinding,
978}
979
980fn all_nonempty_paths_match<'a>(
981    mut paths: impl Iterator<Item = &'a PathBuf>,
982    predicate: &mut impl FnMut(&Path) -> bool,
983) -> bool {
984    let Some(first) = paths.next() else {
985        return false;
986    };
987    predicate(first) && paths.all(|path| predicate(path))
988}
989
990impl FindingIgnorePolicy for UnlistedDependencyFinding {
991    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
992        all_nonempty_paths_match(
993            self.dep.imported_from.iter().map(|site| &site.path),
994            predicate,
995        )
996    }
997}
998
999impl FindingIgnorePolicy for UnlistedBinaryFinding {
1000    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1001        all_nonempty_paths_match(self.binary.used_in.iter().map(|site| &site.path), predicate)
1002    }
1003}
1004
1005impl FindingIgnorePolicy for DuplicateExportFinding {
1006    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1007        all_nonempty_paths_match(
1008            self.export.locations.iter().map(|location| &location.path),
1009            predicate,
1010        )
1011    }
1012}
1013
1014impl FindingIgnorePolicy for CircularDependencyFinding {
1015    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1016        all_nonempty_paths_match(self.cycle.files.iter(), predicate)
1017    }
1018}
1019
1020impl FindingIgnorePolicy for ReExportCycleFinding {
1021    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1022        all_nonempty_paths_match(self.cycle.files.iter(), predicate)
1023    }
1024}
1025
1026impl FindingIgnorePolicy for PackageCycleFinding {
1027    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1028        all_nonempty_paths_match(self.cycle.edges.iter().map(|edge| &edge.path), predicate)
1029    }
1030}
1031
1032impl FindingIgnorePolicy for PropDrillingChainFinding {
1033    fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1034        all_nonempty_paths_match(self.chain.hops.iter().map(|hop| &hop.file), predicate)
1035    }
1036}
1037
1038/// Source-owned health families hidden by `ignoreFindings`.
1039///
1040/// These live outside the unconditional counted table: only explicit error
1041/// findings contribute to `total_issues`; warnings remain advisory.
1042macro_rules! uncounted_source_owned_result_fields {
1043    ($callback:ident $(, $arg:expr)? ) => {
1044        $callback! {
1045            $($arg,)?
1046            prop_drilling_chains => "prop_drilling_chains",
1047            thin_wrappers => "thin_wrappers",
1048            duplicate_prop_shapes => "duplicate_prop_shapes",
1049        }
1050    };
1051}
1052
1053macro_rules! remove_configured_ignored_findings {
1054    ($state:expr, $($field:ident => $key:literal,)+) => {{
1055        let (results, predicate) = $state;
1056        $(
1057            results.$field.retain(|issue| {
1058                !issue.should_ignore(&mut *predicate)
1059            });
1060        )+
1061    }};
1062}
1063
1064macro_rules! counted_result_key_slice {
1065    ($($field:ident => $key:literal,)+) => {
1066        &[$($key),+, "prop_drilling_chains", "thin_wrappers", "duplicate_prop_shapes"]
1067    };
1068}
1069
1070macro_rules! counted_result_field_sum {
1071    ($results:expr, $($field:ident => $key:literal,)+) => {
1072        0 $(+ ($results).$field.len())+
1073    };
1074}
1075#[path = "results_key_findings.rs"]
1076mod result_key_findings;
1077
1078/// Serialized `AnalysisResults` arrays that contribute to [`AnalysisResults::total_issues`].
1079pub const TOTAL_ISSUE_RESULT_KEYS: &[&str] =
1080    counted_analysis_result_fields!(counted_result_key_slice);
1081
1082impl AnalysisResults {
1083    /// Remove the export and member findings whose file `covered` selects.
1084    ///
1085    /// Only `unused_exports`, `unused_types`, `unused_enum_members` and
1086    /// `unused_class_members` change. A removed finding moves to
1087    /// [`CascadeState::hidden`] and [`Self::cascade_hidden`] counts it. A second
1088    /// call removes only findings that a later stage added, so the pass is
1089    /// idempotent.
1090    pub fn hide_cascade_findings(&mut self, covered: &dyn Fn(&Path) -> bool) {
1091        let mut hidden = CascadeHiddenFindings::default();
1092        move_covered(
1093            &mut self.unused_exports,
1094            &mut hidden.unused_exports,
1095            |finding| finding.export.path.as_path(),
1096            covered,
1097        );
1098        move_covered(
1099            &mut self.unused_types,
1100            &mut hidden.unused_types,
1101            |finding| finding.export.path.as_path(),
1102            covered,
1103        );
1104        move_covered(
1105            &mut self.unused_enum_members,
1106            &mut hidden.unused_enum_members,
1107            |finding| finding.member.path.as_path(),
1108            covered,
1109        );
1110        move_covered(
1111            &mut self.unused_class_members,
1112            &mut hidden.unused_class_members,
1113            |finding| finding.member.path.as_path(),
1114            covered,
1115        );
1116        self.cascade_hidden += hidden.len();
1117        self.cascade.hidden.extend(hidden);
1118    }
1119
1120    /// Move the findings that [`Self::hide_cascade_findings`] removed back
1121    /// into the report and reset [`Self::cascade_hidden`].
1122    ///
1123    /// Metrics that measure the code, such as the vital signs, read the
1124    /// result set after this call, so their value does not depend on
1125    /// `showCascade`.
1126    pub fn restore_cascade_findings(&mut self) {
1127        let hidden = std::mem::take(&mut self.cascade.hidden);
1128        self.unused_exports.extend(hidden.unused_exports);
1129        self.unused_types.extend(hidden.unused_types);
1130        self.unused_enum_members.extend(hidden.unused_enum_members);
1131        self.unused_class_members
1132            .extend(hidden.unused_class_members);
1133        self.cascade_hidden = 0;
1134    }
1135
1136    /// Remove dead-code findings whose complete, non-empty source-owner set
1137    /// matches `is_ignored`.
1138    ///
1139    /// Architecture, policy, suppression-hygiene, framework-correctness,
1140    /// security, and package/project findings are retained. Context paths
1141    /// embedded in a dead-code finding are not owners.
1142    #[doc(hidden)]
1143    pub fn remove_ignored_dead_code_findings(&mut self, mut is_ignored: impl FnMut(&Path) -> bool) {
1144        classify_ignore_findings_fields(self);
1145        counted_analysis_result_fields!(
1146            remove_configured_ignored_findings,
1147            (&mut *self, &mut is_ignored)
1148        );
1149        uncounted_source_owned_result_fields!(
1150            remove_configured_ignored_findings,
1151            (&mut *self, &mut is_ignored)
1152        );
1153    }
1154
1155    /// Total number of issues found.
1156    ///
1157    /// Sums across all issue categories (unused files, exports, types,
1158    /// dependencies, members, unresolved imports, unlisted deps, duplicates,
1159    /// type-only deps, circular deps, and boundary violations).
1160    ///
1161    /// # Examples
1162    ///
1163    /// ```
1164    /// use fallow_types::output_dead_code::{UnresolvedImportFinding, UnusedFileFinding};
1165    /// use fallow_types::results::{AnalysisResults, UnresolvedImport, UnusedFile};
1166    /// use std::path::PathBuf;
1167    ///
1168    /// let mut results = AnalysisResults::default();
1169    /// results
1170    ///     .unused_files
1171    ///     .push(UnusedFileFinding::with_actions(UnusedFile {
1172    ///         path: PathBuf::from("a.ts"),
1173    ///     }));
1174    /// results
1175    ///     .unresolved_imports
1176    ///     .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
1177    ///         path: PathBuf::from("b.ts"),
1178    ///         specifier: "./missing".to_string(),
1179    ///         line: 1,
1180    ///         col: 0,
1181    ///         specifier_col: 0,
1182    ///     }));
1183    /// assert_eq!(results.total_issues(), 2);
1184    /// ```
1185    #[must_use]
1186    pub const fn total_issues(&self) -> usize {
1187        counted_analysis_result_fields!(counted_result_field_sum, self)
1188            + self.enforced_prop_drilling_count()
1189            + self.enforced_thin_wrapper_count()
1190            + self.enforced_duplicate_prop_shape_count()
1191    }
1192
1193    /// Whether any issues were found.
1194    #[must_use]
1195    pub const fn has_issues(&self) -> bool {
1196        self.total_issues() > 0
1197    }
1198
1199    /// Merge `other` into `self`, taking the union of every field.
1200    ///
1201    /// This is the single canonical way to combine two [`AnalysisResults`]
1202    /// (the LSP merges per-project-root results through it). The method
1203    /// exhaustively destructures `Self`, so adding a field to the struct
1204    /// becomes a compile error here instead of a silently-dropped field. See
1205    /// issue #444.
1206    ///
1207    /// Every `Vec` field is appended (callers dedup downstream where needed,
1208    /// e.g. the LSP's identity-keyed `dedup_results`). `suppression_count`
1209    /// sums; `entry_point_summary` keeps `self`'s value when present and
1210    /// otherwise adopts `other`'s.
1211    pub fn merge_into(&mut self, other: Self) {
1212        let (core, graph, workspace, framework, metadata) = split_merge_parts(other);
1213        self.merge_core_findings(core);
1214        self.merge_dependency_and_graph_findings(graph);
1215        self.merge_workspace_findings(workspace);
1216        self.merge_framework_findings(framework);
1217        self.merge_metadata_and_security(metadata);
1218    }
1219
1220    fn merge_core_findings(&mut self, parts: AnalysisResultsCoreMergeParts) {
1221        self.unused_files.extend(parts.unused_files);
1222        self.unused_exports.extend(parts.unused_exports);
1223        self.unused_types.extend(parts.unused_types);
1224        self.private_type_leaks.extend(parts.private_type_leaks);
1225        self.deprecated_exports_in_use
1226            .extend(parts.deprecated_exports_in_use);
1227        self.unused_enum_members.extend(parts.unused_enum_members);
1228        self.unused_class_members.extend(parts.unused_class_members);
1229        self.unused_namespace_members
1230            .extend(parts.unused_namespace_members);
1231        self.unused_store_members.extend(parts.unused_store_members);
1232        self.unresolved_imports.extend(parts.unresolved_imports);
1233        self.boundary_violations.extend(parts.boundary_violations);
1234        self.boundary_coverage_violations
1235            .extend(parts.boundary_coverage_violations);
1236        self.boundary_call_violations
1237            .extend(parts.boundary_call_violations);
1238        self.policy_violations.extend(parts.policy_violations);
1239        self.stale_suppressions.extend(parts.stale_suppressions);
1240    }
1241
1242    fn merge_dependency_and_graph_findings(&mut self, parts: AnalysisResultsGraphMergeParts) {
1243        self.unused_dependencies.extend(parts.unused_dependencies);
1244        self.unused_dev_dependencies
1245            .extend(parts.unused_dev_dependencies);
1246        self.unused_optional_dependencies
1247            .extend(parts.unused_optional_dependencies);
1248        self.unlisted_dependencies
1249            .extend(parts.unlisted_dependencies);
1250        self.unlisted_binaries.extend(parts.unlisted_binaries);
1251        self.duplicate_exports.extend(parts.duplicate_exports);
1252        self.duplicate_export_aliases
1253            .extend(parts.duplicate_export_aliases);
1254        self.type_only_dependencies
1255            .extend(parts.type_only_dependencies);
1256        self.test_only_dependencies
1257            .extend(parts.test_only_dependencies);
1258        self.dev_dependencies_in_production
1259            .extend(parts.dev_dependencies_in_production);
1260        self.circular_dependencies
1261            .extend(parts.circular_dependencies);
1262        self.re_export_cycles.extend(parts.re_export_cycles);
1263        self.package_cycles.extend(parts.package_cycles);
1264    }
1265
1266    fn merge_workspace_findings(&mut self, parts: AnalysisResultsWorkspaceMergeParts) {
1267        self.unused_catalog_entries
1268            .extend(parts.unused_catalog_entries);
1269        self.empty_catalog_groups.extend(parts.empty_catalog_groups);
1270        self.unresolved_catalog_references
1271            .extend(parts.unresolved_catalog_references);
1272        self.unused_dependency_overrides
1273            .extend(parts.unused_dependency_overrides);
1274        self.misconfigured_dependency_overrides
1275            .extend(parts.misconfigured_dependency_overrides);
1276    }
1277
1278    fn merge_framework_findings(&mut self, parts: AnalysisResultsFrameworkMergeParts) {
1279        self.invalid_client_exports
1280            .extend(parts.invalid_client_exports);
1281        self.mixed_client_server_barrels
1282            .extend(parts.mixed_client_server_barrels);
1283        self.misplaced_directives.extend(parts.misplaced_directives);
1284        self.unprovided_injects.extend(parts.unprovided_injects);
1285        self.unrendered_components
1286            .extend(parts.unrendered_components);
1287        self.route_collisions.extend(parts.route_collisions);
1288        self.dynamic_segment_name_conflicts
1289            .extend(parts.dynamic_segment_name_conflicts);
1290        self.unused_component_props
1291            .extend(parts.unused_component_props);
1292        self.absent_component_props
1293            .extend(parts.absent_component_props);
1294        self.unused_component_emits
1295            .extend(parts.unused_component_emits);
1296        self.unused_component_inputs
1297            .extend(parts.unused_component_inputs);
1298        self.unused_component_outputs
1299            .extend(parts.unused_component_outputs);
1300        self.unused_svelte_events.extend(parts.unused_svelte_events);
1301        self.unused_effect_layers.extend(parts.unused_effect_layers);
1302        self.unused_tagged_errors.extend(parts.unused_tagged_errors);
1303        self.unproduced_catch_tags
1304            .extend(parts.unproduced_catch_tags);
1305        self.unused_server_actions
1306            .extend(parts.unused_server_actions);
1307        self.unused_load_data_keys
1308            .extend(parts.unused_load_data_keys);
1309        self.unused_load_data_keys_global_abstain |= parts.unused_load_data_keys_global_abstain;
1310        self.prop_drilling_chains.extend(parts.prop_drilling_chains);
1311        self.thin_wrappers.extend(parts.thin_wrappers);
1312        self.duplicate_prop_shapes
1313            .extend(parts.duplicate_prop_shapes);
1314    }
1315
1316    fn merge_metadata_and_security(&mut self, parts: AnalysisResultsMetadataMergeParts) {
1317        self.semantic_reachable_files
1318            .extend(parts.semantic_reachable_files);
1319        self.feature_flags.extend(parts.feature_flags);
1320        self.security_findings.extend(parts.security_findings);
1321        self.security_unresolved_edge_files += parts.security_unresolved_edge_files;
1322        self.security_unresolved_callee_sites += parts.security_unresolved_callee_sites;
1323        self.security_unresolved_callee_diagnostics
1324            .extend(parts.security_unresolved_callee_diagnostics);
1325        self.export_usages.extend(parts.export_usages);
1326        self.active_suppressions.extend(parts.active_suppressions);
1327        self.suppression_count += parts.suppression_count;
1328        self.cascade_hidden += parts.cascade_hidden;
1329        self.cascade
1330            .suppressed_unused_files
1331            .extend(parts.cascade.suppressed_unused_files);
1332        self.cascade.hidden.extend(parts.cascade.hidden);
1333        self.unused_component_props_exempted += parts.unused_component_props_exempted;
1334        if self.entry_point_summary.is_none() {
1335            self.entry_point_summary = parts.entry_point_summary;
1336        }
1337        if self.render_fan_in.is_none() {
1338            self.render_fan_in = parts.render_fan_in;
1339        }
1340        self.react_component_intel
1341            .extend(parts.react_component_intel);
1342        for contract in parts.semantic_framework_contracts {
1343            if !self.semantic_framework_contracts.contains(&contract) {
1344                self.semantic_framework_contracts.push(contract);
1345            }
1346        }
1347    }
1348
1349    /// Sort all result arrays for deterministic output ordering.
1350    ///
1351    /// Parallel collection (rayon, `FxHashMap` iteration) does not guarantee
1352    /// insertion order, so the same project can produce different orderings
1353    /// across runs. This method canonicalises every result list by sorting on
1354    /// (path, line, col, name) so that JSON/SARIF/human output is stable.
1355    pub fn sort(&mut self) {
1356        self.semantic_framework_contracts.sort();
1357        self.sort_core_findings();
1358        self.sort_dependency_findings();
1359        self.sort_graph_findings();
1360        self.sort_catalog_findings();
1361        self.sort_metadata_findings();
1362        self.sort_export_usages();
1363    }
1364
1365    fn sort_core_findings(&mut self) {
1366        self.sort_core_declaration_findings();
1367        self.sort_core_member_findings();
1368        self.sort_core_framework_findings();
1369        self.sort_core_route_and_load_findings();
1370    }
1371
1372    fn sort_core_declaration_findings(&mut self) {
1373        self.unused_files
1374            .sort_by(|a, b| a.file.path.cmp(&b.file.path));
1375
1376        self.unused_exports.sort_by(|a, b| {
1377            a.export
1378                .path
1379                .cmp(&b.export.path)
1380                .then(a.export.line.cmp(&b.export.line))
1381                .then(a.export.export_name.cmp(&b.export.export_name))
1382        });
1383
1384        self.unused_types.sort_by(|a, b| {
1385            a.export
1386                .path
1387                .cmp(&b.export.path)
1388                .then(a.export.line.cmp(&b.export.line))
1389                .then(a.export.export_name.cmp(&b.export.export_name))
1390        });
1391
1392        self.private_type_leaks.sort_by(|a, b| {
1393            a.leak
1394                .path
1395                .cmp(&b.leak.path)
1396                .then(a.leak.line.cmp(&b.leak.line))
1397                .then(a.leak.export_name.cmp(&b.leak.export_name))
1398                .then(a.leak.type_name.cmp(&b.leak.type_name))
1399        });
1400
1401        self.deprecated_exports_in_use.sort_by(|a, b| {
1402            a.export
1403                .path
1404                .cmp(&b.export.path)
1405                .then(a.export.line.cmp(&b.export.line))
1406                .then(a.export.export_name.cmp(&b.export.export_name))
1407        });
1408
1409        self.unused_dependencies.sort_by(|a, b| {
1410            a.dep
1411                .path
1412                .cmp(&b.dep.path)
1413                .then(a.dep.line.cmp(&b.dep.line))
1414                .then(a.dep.package_name.cmp(&b.dep.package_name))
1415        });
1416
1417        self.unused_dev_dependencies.sort_by(|a, b| {
1418            a.dep
1419                .path
1420                .cmp(&b.dep.path)
1421                .then(a.dep.line.cmp(&b.dep.line))
1422                .then(a.dep.package_name.cmp(&b.dep.package_name))
1423        });
1424
1425        self.unused_optional_dependencies.sort_by(|a, b| {
1426            a.dep
1427                .path
1428                .cmp(&b.dep.path)
1429                .then(a.dep.line.cmp(&b.dep.line))
1430                .then(a.dep.package_name.cmp(&b.dep.package_name))
1431        });
1432    }
1433
1434    fn sort_core_member_findings(&mut self) {
1435        self.unused_enum_members.sort_by(|a, b| {
1436            a.member
1437                .path
1438                .cmp(&b.member.path)
1439                .then(a.member.line.cmp(&b.member.line))
1440                .then(a.member.parent_name.cmp(&b.member.parent_name))
1441                .then(a.member.member_name.cmp(&b.member.member_name))
1442        });
1443
1444        self.unused_class_members.sort_by(|a, b| {
1445            a.member
1446                .path
1447                .cmp(&b.member.path)
1448                .then(a.member.line.cmp(&b.member.line))
1449                .then(a.member.parent_name.cmp(&b.member.parent_name))
1450                .then(a.member.member_name.cmp(&b.member.member_name))
1451        });
1452
1453        self.unused_namespace_members.sort_by(|a, b| {
1454            a.member
1455                .path
1456                .cmp(&b.member.path)
1457                .then(a.member.line.cmp(&b.member.line))
1458                .then(a.member.parent_name.cmp(&b.member.parent_name))
1459                .then(a.member.member_name.cmp(&b.member.member_name))
1460        });
1461
1462        self.unused_store_members.sort_by(|a, b| {
1463            a.member
1464                .path
1465                .cmp(&b.member.path)
1466                .then(a.member.line.cmp(&b.member.line))
1467                .then(a.member.parent_name.cmp(&b.member.parent_name))
1468                .then(a.member.member_name.cmp(&b.member.member_name))
1469        });
1470
1471        self.unresolved_imports.sort_by(|a, b| {
1472            a.import
1473                .path
1474                .cmp(&b.import.path)
1475                .then(a.import.line.cmp(&b.import.line))
1476                .then(a.import.col.cmp(&b.import.col))
1477                .then(a.import.specifier.cmp(&b.import.specifier))
1478        });
1479    }
1480
1481    fn sort_core_framework_findings(&mut self) {
1482        self.invalid_client_exports.sort_by(|a, b| {
1483            a.export
1484                .path
1485                .cmp(&b.export.path)
1486                .then(a.export.line.cmp(&b.export.line))
1487                .then(a.export.export_name.cmp(&b.export.export_name))
1488        });
1489
1490        self.mixed_client_server_barrels.sort_by(|a, b| {
1491            a.barrel
1492                .path
1493                .cmp(&b.barrel.path)
1494                .then(a.barrel.line.cmp(&b.barrel.line))
1495                .then(a.barrel.client_origin.cmp(&b.barrel.client_origin))
1496                .then(a.barrel.server_origin.cmp(&b.barrel.server_origin))
1497        });
1498
1499        self.misplaced_directives.sort_by(|a, b| {
1500            a.directive_site
1501                .path
1502                .cmp(&b.directive_site.path)
1503                .then(a.directive_site.line.cmp(&b.directive_site.line))
1504                .then(a.directive_site.col.cmp(&b.directive_site.col))
1505                .then(a.directive_site.directive.cmp(&b.directive_site.directive))
1506        });
1507
1508        self.unprovided_injects.sort_by(|a, b| {
1509            a.inject
1510                .path
1511                .cmp(&b.inject.path)
1512                .then(a.inject.line.cmp(&b.inject.line))
1513                .then(a.inject.col.cmp(&b.inject.col))
1514                .then(a.inject.key_name.cmp(&b.inject.key_name))
1515        });
1516
1517        self.unrendered_components.sort_by(|a, b| {
1518            a.component
1519                .path
1520                .cmp(&b.component.path)
1521                .then(a.component.line.cmp(&b.component.line))
1522                .then(a.component.col.cmp(&b.component.col))
1523                .then(a.component.component_name.cmp(&b.component.component_name))
1524        });
1525    }
1526
1527    fn sort_core_route_and_load_findings(&mut self) {
1528        self.sort_core_route_findings();
1529        self.sort_core_component_prop_and_emit_findings();
1530        self.sort_core_component_io_findings();
1531        self.sort_core_server_load_findings();
1532    }
1533
1534    fn sort_core_route_findings(&mut self) {
1535        self.route_collisions.sort_by(|a, b| {
1536            a.collision
1537                .path
1538                .cmp(&b.collision.path)
1539                .then(a.collision.url.cmp(&b.collision.url))
1540        });
1541
1542        self.dynamic_segment_name_conflicts.sort_by(|a, b| {
1543            a.conflict
1544                .path
1545                .cmp(&b.conflict.path)
1546                .then(a.conflict.position.cmp(&b.conflict.position))
1547        });
1548    }
1549
1550    fn sort_core_component_prop_and_emit_findings(&mut self) {
1551        self.absent_component_props.sort_by(|a, b| {
1552            a.prop
1553                .path
1554                .cmp(&b.prop.path)
1555                .then(a.prop.line.cmp(&b.prop.line))
1556                .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1557        });
1558        self.unused_component_props.sort_by(|a, b| {
1559            a.prop
1560                .path
1561                .cmp(&b.prop.path)
1562                .then(a.prop.line.cmp(&b.prop.line))
1563                .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1564        });
1565
1566        self.unused_component_emits.sort_by(|a, b| {
1567            a.emit
1568                .path
1569                .cmp(&b.emit.path)
1570                .then(a.emit.line.cmp(&b.emit.line))
1571                .then(a.emit.emit_name.cmp(&b.emit.emit_name))
1572        });
1573
1574        self.unused_svelte_events.sort_by(|a, b| {
1575            a.event
1576                .path
1577                .cmp(&b.event.path)
1578                .then(a.event.line.cmp(&b.event.line))
1579                .then(a.event.event_name.cmp(&b.event.event_name))
1580        });
1581        self.sort_effect_findings();
1582    }
1583
1584    fn sort_effect_findings(&mut self) {
1585        self.unused_effect_layers.sort_by(|a, b| {
1586            a.layer
1587                .path
1588                .cmp(&b.layer.path)
1589                .then(a.layer.line.cmp(&b.layer.line))
1590                .then(a.layer.name.cmp(&b.layer.name))
1591        });
1592        self.unused_tagged_errors.sort_by(|a, b| {
1593            a.error
1594                .path
1595                .cmp(&b.error.path)
1596                .then(a.error.line.cmp(&b.error.line))
1597                .then(a.error.name.cmp(&b.error.name))
1598        });
1599        self.unproduced_catch_tags.sort_by(|a, b| {
1600            a.catch_tag
1601                .path
1602                .cmp(&b.catch_tag.path)
1603                .then(a.catch_tag.line.cmp(&b.catch_tag.line))
1604                .then(a.catch_tag.col.cmp(&b.catch_tag.col))
1605                .then(a.catch_tag.tag.cmp(&b.catch_tag.tag))
1606        });
1607    }
1608
1609    fn sort_core_component_io_findings(&mut self) {
1610        self.unused_component_inputs.sort_by(|a, b| {
1611            a.input
1612                .path
1613                .cmp(&b.input.path)
1614                .then(a.input.line.cmp(&b.input.line))
1615                .then(a.input.input_name.cmp(&b.input.input_name))
1616        });
1617
1618        self.unused_component_outputs.sort_by(|a, b| {
1619            a.output
1620                .path
1621                .cmp(&b.output.path)
1622                .then(a.output.line.cmp(&b.output.line))
1623                .then(a.output.output_name.cmp(&b.output.output_name))
1624        });
1625    }
1626
1627    fn sort_core_server_load_findings(&mut self) {
1628        self.unused_server_actions.sort_by(|a, b| {
1629            a.action
1630                .path
1631                .cmp(&b.action.path)
1632                .then(a.action.line.cmp(&b.action.line))
1633                .then(a.action.col.cmp(&b.action.col))
1634                .then(a.action.action_name.cmp(&b.action.action_name))
1635        });
1636
1637        self.unused_load_data_keys.sort_by(|a, b| {
1638            a.key
1639                .path
1640                .cmp(&b.key.path)
1641                .then(a.key.line.cmp(&b.key.line))
1642                .then(a.key.col.cmp(&b.key.col))
1643                .then(a.key.key_name.cmp(&b.key.key_name))
1644        });
1645    }
1646
1647    /// Sort prop-drilling chains by their source hop (first hop): file, line,
1648    /// prop, depth, for deterministic output. Split out of `sort_core_findings`
1649    /// to keep that function under the unit-size ceiling.
1650    fn sort_prop_drilling_chains(&mut self) {
1651        self.prop_drilling_chains.sort_by(|a, b| {
1652            let a_src = a.chain.hops.first();
1653            let b_src = b.chain.hops.first();
1654            let a_file = a_src.map(|h| &h.file);
1655            let b_file = b_src.map(|h| &h.file);
1656            a_file
1657                .cmp(&b_file)
1658                .then_with(|| a_src.map(|h| h.line).cmp(&b_src.map(|h| h.line)))
1659                .then(a.chain.prop.cmp(&b.chain.prop))
1660                .then(a.chain.depth.cmp(&b.chain.depth))
1661        });
1662    }
1663
1664    /// Sort thin-wrapper findings by file, line, then component for
1665    /// deterministic output.
1666    fn sort_thin_wrappers(&mut self) {
1667        self.thin_wrappers.sort_by(|a, b| {
1668            a.wrapper
1669                .file
1670                .cmp(&b.wrapper.file)
1671                .then(a.wrapper.line.cmp(&b.wrapper.line))
1672                .then(a.wrapper.component.cmp(&b.wrapper.component))
1673        });
1674    }
1675
1676    /// Sort duplicate-prop-shape findings by the shared shape first (so a
1677    /// group's members stay adjacent), then file, line, and component, for
1678    /// deterministic output.
1679    fn sort_duplicate_prop_shapes(&mut self) {
1680        self.duplicate_prop_shapes.sort_by(|a, b| {
1681            a.shape
1682                .shape
1683                .cmp(&b.shape.shape)
1684                .then(a.shape.file.cmp(&b.shape.file))
1685                .then(a.shape.line.cmp(&b.shape.line))
1686                .then(a.shape.component.cmp(&b.shape.component))
1687        });
1688    }
1689
1690    fn sort_dependency_findings(&mut self) {
1691        self.unlisted_dependencies
1692            .sort_by(|a, b| a.dep.package_name.cmp(&b.dep.package_name));
1693        for dep in &mut self.unlisted_dependencies {
1694            dep.dep
1695                .imported_from
1696                .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1697        }
1698
1699        self.unlisted_binaries
1700            .sort_by(|a, b| a.binary.binary_name.cmp(&b.binary.binary_name));
1701        for binary in &mut self.unlisted_binaries {
1702            binary.binary.used_in.sort_by(|a, b| {
1703                a.path
1704                    .cmp(&b.path)
1705                    .then(a.line.cmp(&b.line))
1706                    .then(a.col.cmp(&b.col))
1707            });
1708        }
1709
1710        self.duplicate_exports
1711            .sort_by(|a, b| a.export.export_name.cmp(&b.export.export_name));
1712        for dup in &mut self.duplicate_exports {
1713            dup.export
1714                .locations
1715                .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1716        }
1717        self.duplicate_export_aliases.sort_by(|a, b| {
1718            a.alias
1719                .path
1720                .cmp(&b.alias.path)
1721                .then(a.alias.line.cmp(&b.alias.line))
1722                .then(a.alias.col.cmp(&b.alias.col))
1723                .then_with(|| a.alias.export_names.cmp(&b.alias.export_names))
1724        });
1725
1726        self.type_only_dependencies.sort_by(|a, b| {
1727            a.dep
1728                .path
1729                .cmp(&b.dep.path)
1730                .then(a.dep.line.cmp(&b.dep.line))
1731                .then(a.dep.package_name.cmp(&b.dep.package_name))
1732        });
1733
1734        self.test_only_dependencies.sort_by(|a, b| {
1735            a.dep
1736                .path
1737                .cmp(&b.dep.path)
1738                .then(a.dep.line.cmp(&b.dep.line))
1739                .then(a.dep.package_name.cmp(&b.dep.package_name))
1740        });
1741
1742        self.dev_dependencies_in_production.sort_by(|a, b| {
1743            a.dep
1744                .path
1745                .cmp(&b.dep.path)
1746                .then(a.dep.line.cmp(&b.dep.line))
1747                .then(a.dep.package_name.cmp(&b.dep.package_name))
1748        });
1749    }
1750
1751    fn sort_graph_findings(&mut self) {
1752        self.circular_dependencies.sort_by(|a, b| {
1753            a.cycle
1754                .files
1755                .cmp(&b.cycle.files)
1756                .then(a.cycle.length.cmp(&b.cycle.length))
1757        });
1758
1759        self.re_export_cycles
1760            .sort_by(|a, b| a.cycle.files.cmp(&b.cycle.files));
1761
1762        self.package_cycles.sort_by(|a, b| {
1763            a.cycle
1764                .length
1765                .cmp(&b.cycle.length)
1766                .then_with(|| a.cycle.packages.cmp(&b.cycle.packages))
1767        });
1768
1769        self.boundary_violations.sort_by(|a, b| {
1770            a.violation
1771                .from_path
1772                .cmp(&b.violation.from_path)
1773                .then(a.violation.line.cmp(&b.violation.line))
1774                .then(a.violation.col.cmp(&b.violation.col))
1775                .then(a.violation.to_path.cmp(&b.violation.to_path))
1776        });
1777
1778        self.boundary_coverage_violations.sort_by(|a, b| {
1779            a.violation
1780                .path
1781                .cmp(&b.violation.path)
1782                .then(a.violation.line.cmp(&b.violation.line))
1783                .then(a.violation.col.cmp(&b.violation.col))
1784        });
1785
1786        self.boundary_call_violations.sort_by(|a, b| {
1787            a.violation
1788                .path
1789                .cmp(&b.violation.path)
1790                .then(a.violation.line.cmp(&b.violation.line))
1791                .then(a.violation.col.cmp(&b.violation.col))
1792                .then(a.violation.callee.cmp(&b.violation.callee))
1793        });
1794
1795        self.policy_violations.sort_by(|a, b| {
1796            a.violation
1797                .path
1798                .cmp(&b.violation.path)
1799                .then(a.violation.line.cmp(&b.violation.line))
1800                .then(a.violation.col.cmp(&b.violation.col))
1801                .then(a.violation.rule_id.cmp(&b.violation.rule_id))
1802        });
1803    }
1804
1805    fn sort_catalog_findings(&mut self) {
1806        self.sort_stale_suppressions();
1807        self.sort_unused_catalog_entries();
1808        self.sort_empty_catalog_groups();
1809        self.sort_unresolved_catalog_references();
1810        self.sort_unused_dependency_overrides();
1811    }
1812
1813    fn sort_stale_suppressions(&mut self) {
1814        self.stale_suppressions.sort_by(|a, b| {
1815            a.path
1816                .cmp(&b.path)
1817                .then(a.line.cmp(&b.line))
1818                .then(a.col.cmp(&b.col))
1819        });
1820    }
1821
1822    fn sort_unused_catalog_entries(&mut self) {
1823        self.unused_catalog_entries.sort_by(|a, b| {
1824            a.entry
1825                .path
1826                .cmp(&b.entry.path)
1827                .then_with(|| {
1828                    catalog_sort_key(&a.entry.catalog_name)
1829                        .cmp(&catalog_sort_key(&b.entry.catalog_name))
1830                })
1831                .then(a.entry.catalog_name.cmp(&b.entry.catalog_name))
1832                .then(a.entry.entry_name.cmp(&b.entry.entry_name))
1833        });
1834        for finding in &mut self.unused_catalog_entries {
1835            finding.entry.hardcoded_consumers.sort();
1836            finding.entry.hardcoded_consumers.dedup();
1837        }
1838    }
1839
1840    fn sort_empty_catalog_groups(&mut self) {
1841        self.empty_catalog_groups.sort_by(|a, b| {
1842            a.group
1843                .path
1844                .cmp(&b.group.path)
1845                .then_with(|| {
1846                    catalog_sort_key(&a.group.catalog_name)
1847                        .cmp(&catalog_sort_key(&b.group.catalog_name))
1848                })
1849                .then(a.group.catalog_name.cmp(&b.group.catalog_name))
1850                .then(a.group.line.cmp(&b.group.line))
1851        });
1852    }
1853
1854    fn sort_unresolved_catalog_references(&mut self) {
1855        self.unresolved_catalog_references.sort_by(|a, b| {
1856            a.reference
1857                .path
1858                .cmp(&b.reference.path)
1859                .then(a.reference.line.cmp(&b.reference.line))
1860                .then_with(|| {
1861                    catalog_sort_key(&a.reference.catalog_name)
1862                        .cmp(&catalog_sort_key(&b.reference.catalog_name))
1863                })
1864                .then(a.reference.catalog_name.cmp(&b.reference.catalog_name))
1865                .then(a.reference.entry_name.cmp(&b.reference.entry_name))
1866        });
1867        for finding in &mut self.unresolved_catalog_references {
1868            finding.reference.available_in_catalogs.sort();
1869            finding.reference.available_in_catalogs.dedup();
1870        }
1871    }
1872
1873    fn sort_unused_dependency_overrides(&mut self) {
1874        self.unused_dependency_overrides.sort_by(|a, b| {
1875            a.entry
1876                .path
1877                .cmp(&b.entry.path)
1878                .then(a.entry.line.cmp(&b.entry.line))
1879                .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1880        });
1881    }
1882
1883    fn sort_metadata_findings(&mut self) {
1884        self.sort_prop_drilling_chains();
1885        self.sort_thin_wrappers();
1886        self.sort_duplicate_prop_shapes();
1887
1888        self.misconfigured_dependency_overrides.sort_by(|a, b| {
1889            a.entry
1890                .path
1891                .cmp(&b.entry.path)
1892                .then(a.entry.line.cmp(&b.entry.line))
1893                .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1894        });
1895
1896        self.feature_flags.sort_by(|a, b| {
1897            a.path
1898                .cmp(&b.path)
1899                .then(a.line.cmp(&b.line))
1900                .then(a.flag_name.cmp(&b.flag_name))
1901        });
1902
1903        self.security_unresolved_callee_diagnostics.sort_by(|a, b| {
1904            a.path
1905                .cmp(&b.path)
1906                .then(a.line.cmp(&b.line))
1907                .then(a.col.cmp(&b.col))
1908                .then(a.reason.cmp(&b.reason))
1909                .then(a.expression_kind.cmp(&b.expression_kind))
1910        });
1911    }
1912
1913    fn sort_export_usages(&mut self) {
1914        for usage in &mut self.export_usages {
1915            usage.reference_locations.sort_by(|a, b| {
1916                a.path
1917                    .cmp(&b.path)
1918                    .then(a.line.cmp(&b.line))
1919                    .then(a.col.cmp(&b.col))
1920            });
1921        }
1922        self.export_usages.sort_by(|a, b| {
1923            a.path
1924                .cmp(&b.path)
1925                .then(a.line.cmp(&b.line))
1926                .then(a.export_name.cmp(&b.export_name))
1927        });
1928    }
1929}
1930
1931/// Sort key for catalog names: the default catalog ("default") sorts before any named catalog.
1932fn catalog_sort_key(name: &str) -> (u8, &str) {
1933    if name == "default" {
1934        (0, name)
1935    } else {
1936        (1, name)
1937    }
1938}
1939
1940/// A file that is not reachable from any entry point.
1941#[derive(Debug, Clone, Serialize, Deserialize)]
1942#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1943pub struct UnusedFile {
1944    /// Absolute path to the unused file.
1945    #[serde(serialize_with = "serde_path::serialize")]
1946    pub path: PathBuf,
1947}
1948
1949/// An export that is never imported by other modules.
1950#[derive(Debug, Clone, Serialize, Deserialize)]
1951#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1952pub struct UnusedExport {
1953    /// File containing the unused export.
1954    #[serde(serialize_with = "serde_path::serialize")]
1955    pub path: PathBuf,
1956    /// Name of the unused export.
1957    pub export_name: String,
1958    /// Whether this is a type-only export.
1959    pub is_type_only: bool,
1960    /// 1-based line number of the export.
1961    pub line: u32,
1962    /// 0-based byte column offset.
1963    pub col: u32,
1964    /// Byte offset into the source file (used by the fix command).
1965    pub span_start: u32,
1966    /// Whether this finding comes from a barrel/index re-export rather than the source definition.
1967    pub is_re_export: bool,
1968    /// Whether the export's leading JSDoc carries `@deprecated`. Absent from
1969    /// the wire when false.
1970    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1971    pub deprecated: bool,
1972    /// Plain-text message of the `@deprecated` tag, capped at
1973    /// [`DEPRECATED_REASON_MAX_CHARS`] characters. Absent when the export is
1974    /// not deprecated or the tag carries no text.
1975    #[serde(default, skip_serializing_if = "Option::is_none")]
1976    pub deprecated_reason: Option<String>,
1977}
1978
1979/// Maximum number of consumers a [`DeprecatedExportInUse`] finding carries in
1980/// its `consumers` sample. The exact total is in `consumer_count`; the full
1981/// list is available through `fallow dead-code --trace <file>:<export>`.
1982pub const DEPRECATED_CONSUMER_SAMPLE_CAP: usize = 10;
1983
1984/// Maximum number of characters kept from a `@deprecated` tag message. A
1985/// longer message is cut at a character boundary and ends with an ellipsis.
1986pub const DEPRECATED_REASON_MAX_CHARS: usize = 200;
1987
1988/// How a consumer references a deprecated export.
1989#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1990#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1991#[serde(rename_all = "kebab-case")]
1992pub enum DeprecatedConsumerKind {
1993    /// A named import (`import { foo }`).
1994    NamedImport,
1995    /// A default import (`import Foo`).
1996    DefaultImport,
1997    /// A namespace import (`import * as ns`): a member access, or a use of
1998    /// the whole namespace object.
1999    NamespaceImport,
2000    /// A re-export (`export { foo } from './bar'`).
2001    ReExport,
2002    /// A dynamic import (`import('./foo')`).
2003    DynamicImport,
2004    /// A side-effect import (`import './foo'`).
2005    SideEffectImport,
2006}
2007
2008/// One file location that references a deprecated export.
2009#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2010#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2011pub struct DeprecatedExportConsumer {
2012    /// File that references the deprecated export.
2013    #[serde(serialize_with = "serde_path::serialize")]
2014    pub path: PathBuf,
2015    /// 1-based line number of the import or re-export statement.
2016    pub line: u32,
2017    /// 0-based byte column offset of the import or re-export statement.
2018    pub col: u32,
2019    /// How the file references the export.
2020    pub kind: DeprecatedConsumerKind,
2021}
2022
2023/// An export whose leading JSDoc carries `@deprecated` and that still has at
2024/// least one consumer in a reachable file.
2025#[derive(Debug, Clone, Serialize, Deserialize)]
2026#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2027pub struct DeprecatedExportInUse {
2028    /// File that declares the deprecated export.
2029    #[serde(serialize_with = "serde_path::serialize")]
2030    pub path: PathBuf,
2031    /// Name of the deprecated export.
2032    pub export_name: String,
2033    /// Whether this is a type-only export.
2034    pub is_type_only: bool,
2035    /// 1-based line number of the export.
2036    pub line: u32,
2037    /// 0-based byte column offset of the export.
2038    pub col: u32,
2039    /// Byte offset of the export in the source file.
2040    pub span_start: u32,
2041    /// Plain-text message of the `@deprecated` tag, capped at
2042    /// [`DEPRECATED_REASON_MAX_CHARS`] characters. Absent when the tag
2043    /// carries no text.
2044    #[serde(default, skip_serializing_if = "Option::is_none")]
2045    pub deprecated_reason: Option<String>,
2046    /// Exact number of distinct consumers: reference sites in reachable
2047    /// files, one per path, line, column and kind. `consumers` holds the
2048    /// first [`DEPRECATED_CONSUMER_SAMPLE_CAP`] of them, so the sample is
2049    /// complete when this count is at most the cap.
2050    pub consumer_count: usize,
2051    /// Consumer sample sorted by path, line, column and kind, capped at
2052    /// [`DEPRECATED_CONSUMER_SAMPLE_CAP`] entries.
2053    pub consumers: Vec<DeprecatedExportConsumer>,
2054    /// True when the export is part of the public API: it lives in an entry
2055    /// point, or a re-export chain reaches an entry point. External consumers
2056    /// are not visible, so the finding makes no removal claim.
2057    pub public_api: bool,
2058}
2059
2060impl DeprecatedExportInUse {
2061    /// One-line plain-text description shared by the SARIF and CodeClimate
2062    /// formats.
2063    #[must_use]
2064    pub fn description(&self) -> String {
2065        let count = self.consumer_count;
2066        let noun = if count == 1 { "consumer" } else { "consumers" };
2067        let reason = self
2068            .deprecated_reason
2069            .as_deref()
2070            .map_or_else(String::new, |reason| format!(": {reason}"));
2071        format!(
2072            "Deprecated export '{}' is still used by {count} {noun}{reason}",
2073            self.export_name
2074        )
2075    }
2076}
2077
2078/// A public export signature that references a same-file private type.
2079#[derive(Debug, Clone, Serialize, Deserialize)]
2080#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2081pub struct PrivateTypeLeak {
2082    /// File containing the exported symbol.
2083    #[serde(serialize_with = "serde_path::serialize")]
2084    pub path: PathBuf,
2085    /// Export whose public signature leaks the private type.
2086    pub export_name: String,
2087    /// Private type referenced by the public signature.
2088    pub type_name: String,
2089    /// 1-based line number of the leaking type reference.
2090    pub line: u32,
2091    /// 0-based byte column offset.
2092    pub col: u32,
2093    /// Byte offset of the type reference.
2094    pub span_start: u32,
2095    /// Exact checker-backed provenance when type-aware analysis confirmed the
2096    /// package-public leak across files or re-exports.
2097    #[serde(default, skip_serializing_if = "Option::is_none")]
2098    pub semantic: Option<crate::semantic::SemanticPrivateTypeLeak>,
2099}
2100
2101/// A `"use client"` file that exports a Next.js server-only / route-segment
2102/// config name. Next.js rejects this combination at build time; fallow catches
2103/// it statically before the build runs.
2104#[derive(Debug, Clone, Serialize, Deserialize)]
2105#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2106pub struct InvalidClientExport {
2107    /// File carrying the `"use client"` directive and the illegal export.
2108    #[serde(serialize_with = "serde_path::serialize")]
2109    pub path: PathBuf,
2110    /// Name of the server-only / route-config export that is illegal in a
2111    /// client file (e.g. `metadata`, `generateMetadata`, `revalidate`, `GET`).
2112    pub export_name: String,
2113    /// The file-level directive that makes the export illegal. Always
2114    /// `"use client"` today; carried so the message can name it verbatim.
2115    pub directive: String,
2116    /// 1-based line number of the export.
2117    pub line: u32,
2118    /// 0-based byte column offset of the export.
2119    pub col: u32,
2120}
2121
2122/// A barrel file that re-exports BOTH a `"use client"` origin module AND a
2123/// server-only origin module. Importing one name from such a barrel drags the
2124/// other's directive context across the React Server Components boundary (the
2125/// Next.js App Router footgun); fallow catches it statically.
2126#[derive(Debug, Clone, Serialize, Deserialize)]
2127#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2128pub struct MixedClientServerBarrel {
2129    /// The barrel file re-exporting both a client and a server-only origin.
2130    #[serde(serialize_with = "serde_path::serialize")]
2131    pub path: PathBuf,
2132    /// The `"use client"` origin's relative path or specifier as written in the
2133    /// barrel's offending re-export.
2134    pub client_origin: String,
2135    /// The server-only origin's relative path or specifier as written in the
2136    /// barrel's offending re-export.
2137    pub server_origin: String,
2138    /// 1-based line number of the barrel's first offending re-export.
2139    pub line: u32,
2140    /// 0-based byte column offset of the barrel's first offending re-export.
2141    pub col: u32,
2142}
2143
2144/// A `"use client"` / `"use server"` directive written as an expression
2145/// statement after a non-directive statement (an import, a const). The RSC
2146/// bundler only honors a directive in the leading prologue, so once any
2147/// statement precedes it the string is parsed as an ordinary expression and
2148/// silently ignored: the intended client/server boundary never takes effect.
2149/// The fix is to move the directive to the very top of the file.
2150#[derive(Debug, Clone, Serialize, Deserialize)]
2151#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2152pub struct MisplacedDirective {
2153    /// The file carrying the misplaced directive.
2154    #[serde(serialize_with = "serde_path::serialize")]
2155    pub path: PathBuf,
2156    /// The directive string as written, either `"use client"` or
2157    /// `"use server"` (without the surrounding quotes).
2158    pub directive: String,
2159    /// 1-based line number of the misplaced directive statement.
2160    pub line: u32,
2161    /// 0-based byte column offset of the misplaced directive statement.
2162    pub col: u32,
2163}
2164
2165/// A Vue `inject(KEY)` or Svelte `getContext(KEY)` whose symbol KEY is
2166/// `provide`/`setContext`'d nowhere in the analyzed project. The key is a
2167/// symbol with cross-file identity, so an unmatched key is a real dead-half DI
2168/// link: at runtime the inject returns `undefined`, surfaced only at render.
2169/// The fix is binary: provide the key somewhere, or remove the dead inject.
2170#[derive(Debug, Clone, Serialize, Deserialize)]
2171#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2172pub struct UnprovidedInject {
2173    /// The file carrying the orphan inject / getContext call.
2174    #[serde(serialize_with = "serde_path::serialize")]
2175    pub path: PathBuf,
2176    /// The injected key identifier as written at the call site.
2177    pub key_name: String,
2178    /// Which framework's DI API this came from: `"vue"` or `"svelte"`.
2179    pub framework: String,
2180    /// 1-based line number of the inject / getContext call.
2181    pub line: u32,
2182    /// 0-based byte column offset of the inject / getContext call.
2183    pub col: u32,
2184}
2185
2186/// A Next.js Server Action (an export of a `"use server"` file) that no code in
2187/// the analyzed project references: no import-and-call, no `action={fn}` JSX
2188/// binding, no `<form action={fn}>`. This is the cross-graph "declared but zero
2189/// consumers" direction, reclassified out of `unused-export` for `"use server"`
2190/// files so the finding carries the action-specific signal. It does NOT mean the
2191/// endpoint is unreachable: Next still registers the action id, so it stays
2192/// POST-able. It means no project code calls it (likely forgotten / dead, and a
2193/// candidate for removal to shrink surface area).
2194#[derive(Debug, Clone, Serialize, Deserialize)]
2195#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2196pub struct UnusedServerAction {
2197    /// The `"use server"` file that exports the unreferenced action.
2198    #[serde(serialize_with = "serde_path::serialize")]
2199    pub path: PathBuf,
2200    /// The exported action name as written, or `"default"` for a default export.
2201    pub action_name: String,
2202    /// 1-based line number of the export.
2203    pub line: u32,
2204    /// 0-based byte column offset of the export.
2205    pub col: u32,
2206}
2207
2208/// A SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object key
2209/// read by no consumer: not off the sibling `+page.svelte`'s `data.<key>`, nor
2210/// project-wide via `page.data.<key>` / `$page.data.<key>`. A dead load key runs
2211/// a real server/DB fetch cost on every request for data nothing renders. The
2212/// fix is a human call (delete the key, or wire a consumer): a load fetch may
2213/// have side effects, so there is no safe auto-fix.
2214#[derive(Debug, Clone, Serialize, Deserialize)]
2215#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2216pub struct UnusedLoadDataKey {
2217    /// The producer `+page.{ts,server.ts,js,server.js}` file declaring the key.
2218    #[serde(serialize_with = "serde_path::serialize")]
2219    pub path: PathBuf,
2220    /// The returned-object key name read by no consumer.
2221    pub key_name: String,
2222    /// 1-based line number of the key in the return object.
2223    pub line: u32,
2224    /// 0-based byte column offset of the key.
2225    pub col: u32,
2226    /// The route directory relative to the project root (`src/routes/blog`), for
2227    /// agent remediation and per-route trend aggregation. `None` when not
2228    /// determinable.
2229    #[serde(default, skip_serializing_if = "Option::is_none")]
2230    pub route_dir: Option<String>,
2231}
2232
2233/// A Vue/Svelte single-file component (the default export of a `.vue`/`.svelte`
2234/// file) that is reachable in the module graph but rendered NOWHERE in the
2235/// project: no `<Tag>`, no `:is`/`this=` binding, no `components`/`app.component`
2236/// registration, no `h()`/auto-import use, and no script value-read. It survives
2237/// `unused-file` (a barrel re-export keeps it reachable) and `unused-export`
2238/// (the re-export counts as a use), yet no file actually instantiates it.
2239#[derive(Debug, Clone, Serialize, Deserialize)]
2240#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2241pub struct UnrenderedComponent {
2242    /// The component file that is reachable but rendered nowhere.
2243    #[serde(serialize_with = "serde_path::serialize")]
2244    pub path: PathBuf,
2245    /// The component name. For `"vue"` / `"svelte"` / `"astro"` this is the SFC
2246    /// file stem (PascalCase); for `"angular"` it is the component class name; for
2247    /// `"lit"` it is the registered custom-element TAG (e.g. `x-foo`), not a file
2248    /// stem. Use `path` to anchor the file across all frameworks.
2249    pub component_name: String,
2250    /// Which framework this component belongs to: `"vue"`, `"svelte"`, `"astro"`,
2251    /// `"angular"`, or `"lit"`.
2252    pub framework: String,
2253    /// A barrel/file that re-exports this component, kept for the remediation
2254    /// trace ("reachable via X, rendered nowhere"). Absolute in memory,
2255    /// serialized workspace-relative (like `path`); `None` when not determinable.
2256    #[serde(
2257        serialize_with = "serde_path::serialize_option",
2258        skip_serializing_if = "Option::is_none"
2259    )]
2260    pub reachable_via: Option<PathBuf>,
2261    /// 1-based line number of the component (the file head; SFCs have no explicit
2262    /// default-export statement).
2263    pub line: u32,
2264    /// 0-based byte column offset.
2265    pub col: u32,
2266}
2267
2268/// A Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, or React declared
2269/// prop that is referenced NOWHERE inside its own component. Single-component
2270/// finding, zero-FP doctrine: the component abstains on any opaque public or
2271/// fallthrough signal.
2272#[derive(Debug, Clone, Serialize, Deserialize)]
2273#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2274pub struct UnusedComponentProp {
2275    /// The component file declaring the unused prop.
2276    #[serde(serialize_with = "serde_path::serialize")]
2277    pub path: PathBuf,
2278    /// The component name.
2279    pub component_name: String,
2280    /// The declared prop name that is never referenced.
2281    pub prop_name: String,
2282    /// 1-based line number of the prop declaration.
2283    pub line: u32,
2284    /// 0-based byte column offset of the prop declaration.
2285    pub col: u32,
2286}
2287
2288/// One inspected reachable component invocation.
2289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2290#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2291pub struct ComponentPropCallSite {
2292    /// Caller source path.
2293    #[serde(serialize_with = "serde_path::serialize")]
2294    pub path: PathBuf,
2295    /// 1-based opening-tag line.
2296    pub line: u32,
2297    /// 0-based original-source byte column.
2298    pub col: u32,
2299}
2300
2301/// A used optional input that no inspected reachable caller supplies.
2302#[derive(Debug, Clone, Serialize, Deserialize)]
2303#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2304pub struct AbsentComponentProp {
2305    /// Source path of the input declaration.
2306    #[serde(serialize_with = "serde_path::serialize")]
2307    pub path: PathBuf,
2308    /// Semantic declaration name, or SFC filename stem.
2309    pub component_name: String,
2310    /// Public framework token.
2311    pub framework: String,
2312    /// Public optional input name.
2313    pub prop_name: String,
2314    /// 1-based declaration line.
2315    pub line: u32,
2316    /// 0-based declaration byte column.
2317    pub col: u32,
2318    /// Whether omission has a declared default.
2319    pub has_default: bool,
2320    /// Every inspected reachable caller, deterministically ordered.
2321    pub inspected_call_sites: Vec<ComponentPropCallSite>,
2322    /// Manual-review meaning and limits of static evidence.
2323    pub explanation: String,
2324}
2325
2326/// A Vue `<script setup>` `defineEmits` declared event that is EMITTED nowhere
2327/// inside its own single-file component (no `emit('<name>')` call). Single-file
2328/// finding, zero-FP doctrine: the whole file abstains on any
2329/// unharvestable / dynamic-emit / whole-object-use / `defineModel` signal.
2330#[derive(Debug, Clone, Serialize, Deserialize)]
2331#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2332pub struct UnusedComponentEmit {
2333    /// The `.vue` SFC declaring the unused emit.
2334    #[serde(serialize_with = "serde_path::serialize")]
2335    pub path: PathBuf,
2336    /// The component name (the `.vue` file stem).
2337    pub component_name: String,
2338    /// The declared emit event name that is never emitted.
2339    pub emit_name: String,
2340    /// 1-based line number of the emit declaration.
2341    pub line: u32,
2342    /// 0-based byte column offset of the emit declaration.
2343    pub col: u32,
2344}
2345
2346/// A Svelte component dispatching a custom event via `createEventDispatcher()`
2347/// whose event name is listened to NOWHERE in the analyzed project. Cross-file
2348/// dead-output direction: the component fires an event nothing handles.
2349/// Zero-FP doctrine: the whole component abstains on any dynamic-dispatch or
2350/// whole-`dispatch`-value signal, and a listener on ANY component anywhere
2351/// credits the event name (the liberal over-credit direction).
2352#[derive(Debug, Clone, Serialize, Deserialize)]
2353#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2354pub struct UnusedSvelteEvent {
2355    /// The `.svelte` component dispatching the unlistened event.
2356    #[serde(serialize_with = "serde_path::serialize")]
2357    pub path: PathBuf,
2358    /// The component name (the `.svelte` file stem).
2359    pub component_name: String,
2360    /// The dispatched event name that is listened to nowhere.
2361    pub event_name: String,
2362    /// 1-based line number of the `dispatch('<name>')` call.
2363    pub line: u32,
2364    /// 0-based byte column offset of the `dispatch('<name>')` call.
2365    pub col: u32,
2366}
2367
2368/// Kind of an Effect layer definition.
2369#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2370#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2371#[serde(rename_all = "snake_case")]
2372pub enum EffectLayerKind {
2373    /// A module-scope `const` whose initializer is a layer.
2374    TopLevel,
2375    /// A class static property whose initializer is a layer.
2376    StaticMember,
2377}
2378
2379/// An Effect layer whose every reference sits inside other layers that
2380/// nothing in the project uses. The layer is reachable only through a dead
2381/// composition, so it never reaches a runtime. A layer with zero references
2382/// is not reported here: `unused-export` or `unused-class-member` owns it.
2383#[derive(Debug, Clone, Serialize, Deserialize)]
2384#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2385pub struct UnusedEffectLayer {
2386    /// The module that defines the layer.
2387    #[serde(serialize_with = "serde_path::serialize")]
2388    pub path: PathBuf,
2389    /// `FooLive`, or `FooService.layer` for a static member.
2390    pub name: String,
2391    /// Whether the layer is a module-scope const or a class static member.
2392    pub kind: EffectLayerKind,
2393    /// 1-based line number of the layer name.
2394    pub line: u32,
2395    /// 0-based byte column offset of the layer name.
2396    pub col: u32,
2397    /// The unused layers that compose this layer, sorted by name.
2398    pub dead_consumers: Vec<String>,
2399}
2400
2401/// A source location of a `catchTag` or `catchTags` handler.
2402#[derive(Debug, Clone, Serialize, Deserialize)]
2403#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2404pub struct EffectCatchSite {
2405    /// The module that contains the handler.
2406    #[serde(serialize_with = "serde_path::serialize")]
2407    pub path: PathBuf,
2408    /// 1-based line number of the handled tag.
2409    pub line: u32,
2410    /// 0-based byte column offset of the handled tag.
2411    pub col: u32,
2412}
2413
2414/// An Effect tagged error class that type positions or `catchTag` handlers
2415/// reference, but that no code constructs, fails with, or reads as a value.
2416/// Any value reference counts as a producer, including a schema union or an
2417/// API error declaration that decodes the error at a boundary.
2418#[derive(Debug, Clone, Serialize, Deserialize)]
2419#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2420pub struct UnusedTaggedError {
2421    /// The module that declares the class.
2422    #[serde(serialize_with = "serde_path::serialize")]
2423    pub path: PathBuf,
2424    /// The class name.
2425    pub name: String,
2426    /// The `_tag` value of the class.
2427    pub tag: String,
2428    /// 1-based line number of the class name.
2429    pub line: u32,
2430    /// 0-based byte column offset of the class name.
2431    pub col: u32,
2432    /// The `catchTag` / `catchTags` handlers that name the tag.
2433    pub catch_sites: Vec<EffectCatchSite>,
2434}
2435
2436/// A `catchTag("X")` / `catchTags({ X })` handler whose tag `X` belongs to
2437/// project classes that no code produces. Reported only when no
2438/// `unused-tagged-error` finding covers those classes (the rule is off, or
2439/// the class finding is suppressed).
2440#[derive(Debug, Clone, Serialize, Deserialize)]
2441#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2442pub struct UnproducedCatchTag {
2443    /// The module that contains the handler.
2444    #[serde(serialize_with = "serde_path::serialize")]
2445    pub path: PathBuf,
2446    /// The handled tag.
2447    pub tag: String,
2448    /// 1-based line number of the handled tag.
2449    pub line: u32,
2450    /// 0-based byte column offset of the handled tag.
2451    pub col: u32,
2452    /// The project classes that declare the tag, sorted by name.
2453    pub candidate_classes: Vec<String>,
2454}
2455
2456/// One hop in a prop-drilling chain: a component that received the prop and
2457/// passed it along (or, at the chain ends, the source that owns it and the
2458/// consumer that substantively reads it).
2459#[derive(Debug, Clone, Serialize, Deserialize)]
2460#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2461pub struct PropDrillHop {
2462    /// The file containing this hop's component.
2463    #[serde(serialize_with = "serde_path::serialize")]
2464    pub file: PathBuf,
2465    /// 1-based line of the component definition (or the prop declaration at the
2466    /// source hop). Anchors a jump-to-source for the agent.
2467    pub line: u32,
2468    /// The component name at this hop.
2469    pub component: String,
2470}
2471
2472/// A located prop-drilling chain: a received prop forwarded unchanged through
2473/// `>= N` intermediate pass-through components, each of which only re-passes it,
2474/// until a component that substantively consumes it. The high-confidence signal
2475/// is "the received identifier is used ONLY as the root of forwarded child-JSX
2476/// attribute values", not the attribute name matching. Health signal (rule
2477/// defaults to `off`, opt-in): a small capped penalty plus a `health --hotspots`
2478/// surface, and located per-chain records so CI / an agent can act ("colocate or
2479/// lift to context at hop B"). Zero-FP doctrine: any spread / `cloneElement` /
2480/// element-as-prop / render-prop / context-provider / dynamic shape in the path
2481/// abstains the whole chain.
2482#[derive(Debug, Clone, Serialize, Deserialize)]
2483#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2484pub struct PropDrillingChain {
2485    /// The drilled prop name as declared at the chain SOURCE.
2486    pub prop: String,
2487    /// The chain depth = the number of components the prop is forwarded THROUGH
2488    /// (source + intermediates + consumer = `hops.len()`). Always `>= N`.
2489    pub depth: u32,
2490    /// The ordered hop trail from source to consumer. The first hop owns the
2491    /// prop, the middle hops are pass-throughs, the last hop consumes it. The
2492    /// finding anchor is the first hop (`path` / `line` for suppression + CI).
2493    pub hops: Vec<PropDrillHop>,
2494}
2495
2496/// A located thin-wrapper / passthrough component: a React/Preact component
2497/// whose entire body is `return <Child {...props}/>` (a single spread-forwarded
2498/// child render, no host wrapper, no own value-add). It is pure structural
2499/// indirection, a CANDIDATE for inlining at call sites or deleting. Health
2500/// signal (rule defaults to `off`, opt-in): never a correctness error. Zero-FP
2501/// doctrine: `forwardRef` / `memo` / exported / context-provider /
2502/// `cloneElement` / render-prop / named-attr / unresolved-child wrappers all
2503/// abstain (each is an intentional indirection or unprovable shape).
2504#[derive(Debug, Clone, Serialize, Deserialize)]
2505#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2506pub struct ThinWrapper {
2507    /// The file containing the wrapper component.
2508    #[serde(serialize_with = "serde_path::serialize")]
2509    pub file: PathBuf,
2510    /// 1-based line of the wrapper component definition (the finding anchor for
2511    /// jump-to-source and line-level suppression).
2512    pub line: u32,
2513    /// The wrapper component name.
2514    pub component: String,
2515    /// The single child component the wrapper forwards its props to (as written
2516    /// at the render site).
2517    pub child_component: String,
2518}
2519
2520/// One member of a duplicate-prop-shape group: the OTHER components that share
2521/// the same significant prop-name set, listed in each member's
2522/// `sharing_components`. Path-sorted for stable output. A located reference (no
2523/// `shape`, which is carried once on the owning [`DuplicatePropShape`]).
2524#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2525#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2526pub struct DuplicatePropShapeMember {
2527    /// The file containing the sibling component.
2528    #[serde(serialize_with = "serde_path::serialize")]
2529    pub file: PathBuf,
2530    /// 1-based line of the sibling component definition.
2531    pub line: u32,
2532    /// The sibling component name.
2533    pub component: String,
2534}
2535
2536/// A React/Preact component that participates in a duplicate-prop-shape GROUP:
2537/// three or more distinct components across two or more files whose
2538/// statically-harvested, fully-known prop NAME set is byte-for-byte IDENTICAL
2539/// after excluding a fixed denylist of ubiquitous DOM / render-passthrough prop
2540/// names, with the REMAINING significant set holding four or more members. This
2541/// is a structural-refactor health signal (extract a shared `Props` type or a
2542/// base component), never a correctness error and never an auto-fix. One finding
2543/// is emitted per participating component; `sharing_components` lists the other
2544/// members of the same group. Health signal: the rule defaults to `off`
2545/// (opt-in), so this is dormant until enabled. Exact full-set identity only: a
2546/// superset / subset relationship does NOT group (so the finding always fits one
2547/// extracted shared type).
2548#[derive(Debug, Clone, Serialize, Deserialize)]
2549#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2550pub struct DuplicatePropShape {
2551    /// The file containing this component.
2552    #[serde(serialize_with = "serde_path::serialize")]
2553    pub file: PathBuf,
2554    /// 1-based line of this component definition (the finding anchor for
2555    /// jump-to-source and line-level suppression).
2556    pub line: u32,
2557    /// This component name.
2558    pub component: String,
2559    /// The shared SIGNIFICANT prop-name set (sorted, denylist-stripped). The
2560    /// unit being grouped; identical across every member of the group.
2561    pub shape: Vec<String>,
2562    /// The total number of components in this group (this one plus every
2563    /// sibling).
2564    pub group_size: u32,
2565    /// The OTHER components sharing this exact prop shape (path-sorted). A
2566    /// file-level-suppressed member drops from its own finding but still appears
2567    /// here, because the group is real regardless of suppression.
2568    pub sharing_components: Vec<DuplicatePropShapeMember>,
2569}
2570
2571/// An Angular `@Input()` / signal `input()` / `model()` declared input that is
2572/// read NOWHERE inside its own component (neither the inline/external template
2573/// nor the class body). Single-file dead-input direction; the Angular analogue
2574/// of [`UnusedComponentProp`]. The whole component abstains on an unresolved
2575/// `extends` heritage clause (a base class in another file may read `this.foo`).
2576#[derive(Debug, Clone, Serialize, Deserialize)]
2577#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2578pub struct UnusedComponentInput {
2579    /// The Angular component/directive `.ts` file declaring the unused input.
2580    #[serde(serialize_with = "serde_path::serialize")]
2581    pub path: PathBuf,
2582    /// The component name (the `.ts` file stem).
2583    pub component_name: String,
2584    /// The declared input name that is never read.
2585    pub input_name: String,
2586    /// 1-based line number of the input declaration.
2587    pub line: u32,
2588    /// 0-based byte column offset of the input declaration.
2589    pub col: u32,
2590}
2591
2592/// An Angular `@Output()` / signal `output()` declared output that is EMITTED
2593/// nowhere inside its own component (no `this.<output>.emit(...)`). Single-file
2594/// dead-output direction; the Angular analogue of [`UnusedComponentEmit`]. A
2595/// `model()` is recorded as an input only, so its framework-driven `update:`
2596/// emit is never flagged here. The whole component abstains on an unresolved
2597/// `extends` heritage clause.
2598#[derive(Debug, Clone, Serialize, Deserialize)]
2599#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2600pub struct UnusedComponentOutput {
2601    /// The Angular component/directive `.ts` file declaring the unused output.
2602    #[serde(serialize_with = "serde_path::serialize")]
2603    pub path: PathBuf,
2604    /// The component name (the `.ts` file stem).
2605    pub component_name: String,
2606    /// The declared output name that is never emitted.
2607    pub output_name: String,
2608    /// 1-based line number of the output declaration.
2609    pub line: u32,
2610    /// 0-based byte column offset of the output declaration.
2611    pub col: u32,
2612}
2613
2614/// Two or more Next.js App Router route files that resolve to the SAME URL
2615/// within one app-root. Next.js fails the build ("You cannot have two parallel
2616/// pages that resolve to the same path"); fallow catches it statically and
2617/// names every colliding file at once. One finding is emitted per colliding
2618/// file; `conflicting_paths` lists the sibling files that share the URL.
2619#[derive(Debug, Clone, Serialize, Deserialize)]
2620#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2621pub struct RouteCollision {
2622    /// This colliding route file (a `page` or `route` leaf).
2623    #[serde(serialize_with = "serde_path::serialize")]
2624    pub path: PathBuf,
2625    /// The URL pathname this file resolves to within its app-root, after
2626    /// stripping route groups `(x)` and parallel-slot `@slot` prefixes (e.g.
2627    /// `/about`, `/api/health`, `/blog/:slug`).
2628    pub url: String,
2629    /// The other route files that resolve to the same URL within the same
2630    /// app-root. Path-sorted for stable output / fingerprints.
2631    #[serde(serialize_with = "serde_path::serialize_vec")]
2632    pub conflicting_paths: Vec<PathBuf>,
2633    /// 1-based line number (file-level finding, always 1).
2634    pub line: u32,
2635    /// 0-based byte column offset (file-level finding, always 0).
2636    pub col: u32,
2637}
2638
2639/// Two or more sibling dynamic route segments at the SAME App Router tree
2640/// position using different param spellings (`[id]` vs `[slug]`, or `[...x]`
2641/// vs `[[...x]]`). Next.js throws "You cannot use different slug names for the
2642/// same dynamic path" at dev / production RUNTIME when the position is hit;
2643/// `next build` does NOT catch it, so fallow's static catch surfaces a route
2644/// that would otherwise pass CI and crash at request time. One finding is
2645/// emitted per involved file.
2646#[derive(Debug, Clone, Serialize, Deserialize)]
2647#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2648pub struct DynamicSegmentNameConflict {
2649    /// This route file living under one of the conflicting dynamic segments.
2650    #[serde(serialize_with = "serde_path::serialize")]
2651    pub path: PathBuf,
2652    /// The tree position (parent URL after group/slot normalization) where the
2653    /// dynamic segments conflict, e.g. `/shop` for `/shop/[id]` vs
2654    /// `/shop/[slug]`. The app-root prefix is stripped.
2655    pub position: String,
2656    /// The distinct conflicting dynamic-segment spellings at this position, as
2657    /// written (e.g. `["[id]", "[slug]"]`). Sorted for stable output.
2658    pub conflicting_segments: Vec<String>,
2659    /// The other route files at the same position under a conflicting dynamic
2660    /// segment. Path-sorted for stable output / fingerprints.
2661    #[serde(serialize_with = "serde_path::serialize_vec")]
2662    pub conflicting_paths: Vec<PathBuf>,
2663    /// 1-based line number (file-level finding, always 1).
2664    pub line: u32,
2665    /// 0-based byte column offset (file-level finding, always 0).
2666    pub col: u32,
2667}
2668
2669/// A dependency that is listed in package.json but never imported.
2670#[derive(Debug, Clone, Serialize, Deserialize)]
2671#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2672pub struct UnusedDependency {
2673    /// Package name, including internal workspace package names.
2674    pub package_name: String,
2675    /// Whether this is in `dependencies`, `devDependencies`, or `optionalDependencies`.
2676    pub location: DependencyLocation,
2677    /// Path to the package.json where this dependency is listed.
2678    /// For root deps this is `<root>/package.json`, for workspace deps it is `<ws>/package.json`.
2679    #[serde(serialize_with = "serde_path::serialize")]
2680    pub path: PathBuf,
2681    /// 1-based line number of the dependency entry in package.json.
2682    pub line: u32,
2683    /// Workspace roots that import this package even though the declaring workspace does not.
2684    #[serde(
2685        default,
2686        serialize_with = "serde_path::serialize_vec",
2687        skip_serializing_if = "Vec::is_empty"
2688    )]
2689    #[cfg_attr(feature = "schema", schemars(default))]
2690    pub used_in_workspaces: Vec<PathBuf>,
2691    /// Workspace roots whose package.json declares this package for the files
2692    /// that import it. Only a root finding fills this field: these imports use
2693    /// the nearer workspace declaration, so the root declaration stays unused.
2694    #[serde(
2695        default,
2696        serialize_with = "serde_path::serialize_vec",
2697        skip_serializing_if = "Vec::is_empty"
2698    )]
2699    #[cfg_attr(feature = "schema", schemars(default))]
2700    pub declared_and_imported_in: Vec<PathBuf>,
2701}
2702
2703/// Where in package.json a dependency is listed.
2704///
2705/// # Examples
2706///
2707/// ```
2708/// use fallow_types::results::DependencyLocation;
2709///
2710/// // All three variants are constructible
2711/// let loc = DependencyLocation::Dependencies;
2712/// let dev = DependencyLocation::DevDependencies;
2713/// let opt = DependencyLocation::OptionalDependencies;
2714/// // Debug output includes the variant name
2715/// assert!(format!("{loc:?}").contains("Dependencies"));
2716/// assert!(format!("{dev:?}").contains("DevDependencies"));
2717/// assert!(format!("{opt:?}").contains("OptionalDependencies"));
2718/// ```
2719#[derive(Debug, Clone, Serialize, Deserialize)]
2720#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2721#[serde(rename_all = "camelCase")]
2722pub enum DependencyLocation {
2723    /// Listed in `dependencies`.
2724    Dependencies,
2725    /// Listed in `devDependencies`.
2726    DevDependencies,
2727    /// Listed in `optionalDependencies`.
2728    OptionalDependencies,
2729}
2730
2731/// An unused enum, class, store, or namespace member.
2732#[derive(Debug, Clone, Serialize, Deserialize)]
2733#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2734pub struct UnusedMember {
2735    /// File containing the unused member.
2736    #[serde(serialize_with = "serde_path::serialize")]
2737    pub path: PathBuf,
2738    /// Name of the parent enum, class, store, or exported namespace.
2739    pub parent_name: String,
2740    /// Name of the unused member. A member of a nested namespace has the dotted
2741    /// path from the exported namespace (`Inner.x`).
2742    pub member_name: String,
2743    /// The kind of member: enum member, class method, class property, store
2744    /// member, or namespace member.
2745    pub kind: MemberKind,
2746    /// 1-based line number.
2747    pub line: u32,
2748    /// 0-based byte column offset.
2749    pub col: u32,
2750}
2751
2752/// An import that could not be resolved.
2753#[derive(Debug, Clone, Serialize, Deserialize)]
2754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2755pub struct UnresolvedImport {
2756    /// File containing the unresolved import.
2757    #[serde(serialize_with = "serde_path::serialize")]
2758    pub path: PathBuf,
2759    /// The import specifier that could not be resolved.
2760    pub specifier: String,
2761    /// 1-based line number.
2762    pub line: u32,
2763    /// 0-based byte column offset of the import statement.
2764    pub col: u32,
2765    /// 0-based byte column offset of the source string literal (the specifier in quotes).
2766    /// Used by the LSP to underline just the specifier, not the entire import line.
2767    pub specifier_col: u32,
2768}
2769
2770/// A dependency used in code but not listed in package.json.
2771#[derive(Debug, Clone, Serialize, Deserialize)]
2772#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2773pub struct UnlistedDependency {
2774    /// Package name, including internal workspace package names, that is
2775    /// imported but not listed in package.json.
2776    pub package_name: String,
2777    /// Import sites where this unlisted dependency is used (file path, line, column).
2778    pub imported_from: Vec<ImportSite>,
2779}
2780
2781/// A binary that a package.json script or a process call runs, but that no
2782/// installed or listed package provides.
2783#[derive(Debug, Clone, Serialize, Deserialize)]
2784#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2785pub struct UnlistedBinary {
2786    /// The binary name as the command runs it (for example `ffmpeg`).
2787    pub binary_name: String,
2788    /// The sites that run this binary.
2789    pub used_in: Vec<BinaryUseSite>,
2790}
2791
2792/// A location that runs a binary.
2793#[derive(Debug, Clone, Serialize, Deserialize)]
2794#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2795pub struct BinaryUseSite {
2796    /// The `package.json` that declares the script, or the source file that
2797    /// makes the process call.
2798    #[serde(serialize_with = "serde_path::serialize")]
2799    pub path: PathBuf,
2800    /// 1-based line number.
2801    pub line: u32,
2802    /// 0-based byte column offset.
2803    pub col: u32,
2804    /// The name of the package.json script that runs the binary. Absent for
2805    /// a process call in source.
2806    #[serde(default, skip_serializing_if = "Option::is_none")]
2807    pub script_name: Option<String>,
2808}
2809
2810/// A location where an import occurs.
2811#[derive(Debug, Clone, Serialize, Deserialize)]
2812#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2813pub struct ImportSite {
2814    /// File containing the import.
2815    #[serde(serialize_with = "serde_path::serialize")]
2816    pub path: PathBuf,
2817    /// 1-based line number.
2818    pub line: u32,
2819    /// 0-based byte column offset.
2820    pub col: u32,
2821}
2822
2823/// An export that appears multiple times across the project.
2824#[derive(Debug, Clone, Serialize, Deserialize)]
2825#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2826pub struct DuplicateExport {
2827    /// The duplicated export name.
2828    pub export_name: String,
2829    /// Locations where this export name appears.
2830    pub locations: Vec<DuplicateLocation>,
2831}
2832
2833/// A location where a duplicate export appears.
2834#[derive(Debug, Clone, Serialize, Deserialize)]
2835#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2836pub struct DuplicateLocation {
2837    /// File containing the duplicate export.
2838    #[serde(serialize_with = "serde_path::serialize")]
2839    pub path: PathBuf,
2840    /// 1-based line number.
2841    pub line: u32,
2842    /// 0-based byte column offset.
2843    pub col: u32,
2844}
2845
2846/// One module that exports one binding under two or more names, for example
2847/// `export const a = 1; export default a;` or `export { a, a as b }`. The
2848/// finding is about the export surface of one file, not about usage, so an
2849/// entry file can have it too. Value and type-only exports of one name are
2850/// separate bindings. Two bindings with the same initializer are not one
2851/// binding.
2852#[derive(Debug, Clone, Serialize, Deserialize)]
2853#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2854pub struct DuplicateExportAlias {
2855    /// The module that exports the binding.
2856    #[serde(serialize_with = "serde_path::serialize")]
2857    pub path: PathBuf,
2858    /// The local name of the binding. For a re-export, the name that the
2859    /// source module exports.
2860    pub local_name: String,
2861    /// The export names of the binding, in source order.
2862    pub export_names: Vec<String>,
2863    /// 1-based line number of the first export of the binding.
2864    pub line: u32,
2865    /// 0-based byte column offset of the first export of the binding.
2866    pub col: u32,
2867    /// One location for each export name, in source order.
2868    pub locations: Vec<DuplicateExportAliasLocation>,
2869}
2870
2871/// One export name of a [`DuplicateExportAlias`].
2872#[derive(Debug, Clone, Serialize, Deserialize)]
2873#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2874pub struct DuplicateExportAliasLocation {
2875    /// The export name at this location (`default` for a default export).
2876    pub export_name: String,
2877    /// 1-based line number.
2878    pub line: u32,
2879    /// 0-based byte column offset.
2880    pub col: u32,
2881}
2882
2883/// A production dependency that is only used via type-only imports.
2884/// In production builds, type imports are erased, so this dependency
2885/// is not needed at runtime and could be moved to devDependencies.
2886#[derive(Debug, Clone, Serialize, Deserialize)]
2887#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2888pub struct TypeOnlyDependency {
2889    /// Production dependency that is only used via type-only imports.
2890    pub package_name: String,
2891    /// Path to the package.json where the dependency is listed.
2892    #[serde(serialize_with = "serde_path::serialize")]
2893    pub path: PathBuf,
2894    /// 1-based line number of the dependency entry in package.json.
2895    pub line: u32,
2896}
2897
2898/// The kind of security candidate. Findings are CANDIDATES for downstream agent
2899/// verification, NOT verified vulnerabilities.
2900#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2901#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2902#[serde(rename_all = "kebab-case")]
2903pub enum SecurityFindingKind {
2904    /// A `"use client"` file transitively imports a module that reads a
2905    /// non-public `process.env` secret (graph-structural; bespoke, not catalogue).
2906    ClientServerLeak,
2907    /// A syntactic sink site matched against the data-driven catalogue
2908    /// (`security_matchers.toml`). Serializes `"tainted-sink"`; the CWE class is
2909    /// carried in `category` + `cwe`. ONE variant covers all catalogue categories.
2910    TaintedSink,
2911}
2912
2913/// The role a hop plays in a security finding's structural import trace.
2914#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2915#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2916#[serde(rename_all = "kebab-case")]
2917pub enum TraceHopRole {
2918    /// The `"use client"` boundary file the finding is anchored on.
2919    ClientBoundary,
2920    /// A module that reads an untrusted input source such as request data,
2921    /// where the candidate's sink argument actually traces back to that read in
2922    /// the same statement (arg-level, the strong intra-module association).
2923    UntrustedSource,
2924    /// A module that merely CONTAINS an untrusted-input source somewhere and is
2925    /// import-reachable to the sink module (module-level, issue #885). This is a
2926    /// reachability signal, NOT a proven value path: the specific source value
2927    /// is not shown to reach the sink argument. Labeled distinctly from
2928    /// `UntrustedSource` so a consumer never reads a module-level hop as a
2929    /// value-flow proof.
2930    ModuleSource,
2931    /// An intermediate module on the transitive import path.
2932    Intermediate,
2933    /// The module that reads the secret.
2934    SecretSource,
2935    /// The syntactic sink site of a catalogue-driven `tainted-sink` candidate
2936    /// (the single hop the `tainted_sink` detector emits). Distinct from
2937    /// `SecretSource`, which is specific to the `client-server-leak` rule.
2938    Sink,
2939}
2940
2941/// One hop in a security finding's structural trace. Stored as an absolute path
2942/// internally; JSON serialization strips the project root via
2943/// `serde_path::serialize`.
2944#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2945#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2946pub struct TraceHop {
2947    /// File on this hop of the import chain.
2948    #[serde(serialize_with = "serde_path::serialize")]
2949    pub path: PathBuf,
2950    /// 1-based line number. Import-chain hops point at the import site; the
2951    /// terminal secret-source hop points at the source module when extraction
2952    /// does not carry a more precise member-access span.
2953    pub line: u32,
2954    /// 0-based byte column offset.
2955    pub col: u32,
2956    /// Role of this hop in the chain.
2957    pub role: TraceHopRole,
2958}
2959
2960/// How strongly the untrusted-source signal is associated with the sink, a
2961/// structured discriminator so a consumer can tier candidates without parsing
2962/// the human `evidence` prose. Present only when
2963/// [`SecurityReachability::reachable_from_untrusted_source`] is true. Neither
2964/// value proves exploitability; both are ranking signals (issue #885 doctrine:
2965/// rank, never gate).
2966#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2967#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2968#[serde(rename_all = "kebab-case")]
2969pub enum TaintConfidence {
2970    /// The sink's argument traces back to a known untrusted-source read in the
2971    /// SAME statement / module (the intra-module back-trace, issue #859). The
2972    /// strong, high-value candidate: a specific source expression is implicated.
2973    ArgLevel,
2974    /// The sink merely lives in a module that is import-reachable from a module
2975    /// containing an untrusted source (issue #885). The weak candidate: only the
2976    /// module is implicated, not a specific value path to the sink argument.
2977    ModuleLevel,
2978}
2979
2980/// Graph-derived reachability ranking signal for a security candidate. Computed
2981/// from the existing module graph after detection, never proven exploitable.
2982/// Used to surface candidates that sit on a request/runtime-reachable surface,
2983/// receive same-module source evidence, or are import-reachable from an
2984/// untrusted-source module above isolated helpers or scripts.
2985///
2986/// This is a relative-ordering signal, NOT a `confidence` or `signal_strength`
2987/// score: fallow does not prove the path is exploitable.
2988#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2989#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2990pub struct SecurityReachability {
2991    /// Whether the anchor module is reachable from a runtime/application entry
2992    /// point (route handlers, server entry, framework runtime roots), the
2993    /// closest graph proxy for an external/request input surface. Code reachable
2994    /// only from test entry points does not count.
2995    pub reachable_from_entry: bool,
2996    /// Whether the anchor module is reachable over value imports from a module
2997    /// that reads a known untrusted input source. Module-level only: this does
2998    /// not prove a specific source value reaches the sink argument.
2999    #[serde(default)]
3000    pub reachable_from_untrusted_source: bool,
3001    /// Structured tier of the untrusted-source association: `arg-level` when the
3002    /// sink argument traces to a same-module source read (strong), `module-level`
3003    /// when only the module is import-reachable from a source (weak). Present
3004    /// exactly when `reachable_from_untrusted_source` is true, so a consumer can
3005    /// separate strong from weak candidates from this field alone without parsing
3006    /// the `evidence` string. Not an exploitability proof.
3007    #[serde(default, skip_serializing_if = "Option::is_none")]
3008    pub taint_confidence: Option<TaintConfidence>,
3009    /// Number of value-import hops from the untrusted-source module to the sink
3010    /// module when `reachable_from_untrusted_source` is true.
3011    #[serde(default, skip_serializing_if = "Option::is_none")]
3012    pub untrusted_source_hop_count: Option<u32>,
3013    /// Module-level import path from the untrusted-source module to the sink
3014    /// anchor. Empty when no source module reaches this candidate. The path is a
3015    /// ranking explanation, not a value-flow proof.
3016    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3017    pub untrusted_source_trace: Vec<TraceHop>,
3018    /// Number of distinct modules that transitively depend on the anchor module
3019    /// (fan-in via the graph's reverse-dependency index). A higher value means a
3020    /// wider surface: more call sites could route untrusted input into the sink.
3021    pub blast_radius: u32,
3022    /// Whether the anchor module participates in an architecture-boundary
3023    /// violation found in the same run (as the importing or imported file).
3024    /// Optional pairing: a candidate that also crosses a declared boundary is a
3025    /// stronger review target.
3026    pub crosses_boundary: bool,
3027}
3028
3029/// Dead-code cross-link attached to a security candidate when fallow's dead-code
3030/// pass reports the same anchor as removable code.
3031#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3032#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3033pub struct SecurityDeadCodeContext {
3034    /// Dead-code issue kind that matched the security candidate.
3035    pub kind: SecurityDeadCodeKind,
3036    /// Unused export name when `kind` is `unused-export`.
3037    #[serde(default, skip_serializing_if = "Option::is_none")]
3038    pub export_name: Option<String>,
3039    /// Dead-code finding line when available.
3040    #[serde(default, skip_serializing_if = "Option::is_none")]
3041    pub line: Option<u32>,
3042    /// Agent-facing guidance for deciding between deletion and hardening.
3043    pub guidance: String,
3044}
3045
3046/// Dead-code issue kind linked to a security candidate.
3047#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3048#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3049#[serde(rename_all = "kebab-case")]
3050pub enum SecurityDeadCodeKind {
3051    /// The candidate's anchor file is also reported as an unused file.
3052    UnusedFile,
3053    /// The candidate's anchor sits on an unused export declaration.
3054    UnusedExport,
3055}
3056
3057/// Internal row for a security sink-shaped callee that extraction could not
3058/// flatten to a static catalogue path.
3059#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3060#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3061pub struct SecurityUnresolvedCalleeDiagnostic {
3062    /// File containing the skipped callee. Absolute internally.
3063    #[serde(serialize_with = "serde_path::serialize")]
3064    pub path: PathBuf,
3065    /// 1-based line of the skipped callee.
3066    pub line: u32,
3067    /// 0-based byte column of the skipped callee.
3068    pub col: u32,
3069    /// Why the callee could not be flattened.
3070    pub reason: SkippedSecurityCalleeReason,
3071    /// Compact syntax shape of the skipped callee.
3072    pub expression_kind: SkippedSecurityCalleeExpressionKind,
3073}
3074
3075/// The sink slot of a [`SecurityCandidate`]: a self-contained description of the
3076/// matched sink site. Echoes the finding's own span (`path`/`line`/`col`) plus
3077/// the catalogue `category`/`cwe` and the captured `callee`, so an agent can act
3078/// on `candidate.sink` in isolation (e.g. after fanning a finding out to a
3079/// sub-agent) without reading the parent finding.
3080#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3081#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3082pub struct SecurityCandidateSink {
3083    /// File of the sink site. Absolute internally; JSON strips the project root
3084    /// via `serde_path::serialize`.
3085    #[serde(serialize_with = "serde_path::serialize")]
3086    pub path: PathBuf,
3087    /// 1-based line of the sink site.
3088    pub line: u32,
3089    /// 0-based byte column of the sink site.
3090    pub col: u32,
3091    /// Catalogue category id of the sink (e.g. `"dangerous-html"`). For
3092    /// `client-server-leak` this is `"client-server-leak"` for the secret-leak
3093    /// finding, and `"server-only-import"` when a `"use client"` cone reaches
3094    /// server-only code. Older releases left it absent for the secret leak.
3095    #[serde(default, skip_serializing_if = "Option::is_none")]
3096    pub category: Option<String>,
3097    /// CWE number declared by the catalogue entry. `None` for
3098    /// `client-server-leak`; never fabricated beyond the catalogue's value.
3099    #[serde(default, skip_serializing_if = "Option::is_none")]
3100    pub cwe: Option<u32>,
3101    /// The sink callee (the dangerous function or member path, e.g.
3102    /// `"el.innerHTML"`, `"child_process.exec"`) captured by the catalogue match.
3103    /// `None` for `client-server-leak` and matches that name no callee.
3104    #[serde(default, skip_serializing_if = "Option::is_none")]
3105    pub callee: Option<String>,
3106    /// URL construction shape for SSRF and open-redirect style candidates when
3107    /// fallow can classify whether the origin is fixed or dynamic. Absent for
3108    /// non-URL sinks and unclassified URL expressions.
3109    #[serde(default, skip_serializing_if = "Option::is_none")]
3110    pub url_shape: Option<SecurityUrlShape>,
3111}
3112
3113/// A declared architecture-zone crossing, recovered by correlating a finding's
3114/// anchor against the run's architecture-boundary violations.
3115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3116#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3117pub struct SecurityZoneCrossing {
3118    /// Zone the importing side belongs to.
3119    pub from: String,
3120    /// Zone the imported side belongs to.
3121    pub to: String,
3122}
3123
3124/// The boundary slot of a [`SecurityCandidate`]: which structural boundaries the
3125/// candidate's flow crosses. A flow that crosses a client/server or module
3126/// boundary is a stronger review target than a self-contained one; the boundary
3127/// is fallow's structural signal over a pure source-sink match.
3128///
3129/// Two further boundary kinds are RESERVED for a follow-up and are deliberately
3130/// absent here rather than emitted as always-false: `export_visibility` (is the
3131/// sink on a publicly-exported symbol?) and a package boundary (does the flow
3132/// cross an npm-package edge?). Both need new graph derivation that does not
3133/// exist today; emitting them as `false` would misreport "we checked and it does
3134/// not cross" when fallow has not checked at all.
3135#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3136#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3137pub struct SecurityCandidateBoundary {
3138    /// Whether the finding crosses a client/server boundary (a `"use client"`
3139    /// file appears in the trace). True only for `client-server-leak` today;
3140    /// `tainted-sink` candidates carry no client/server marker.
3141    pub client_server: bool,
3142    /// Whether an untrusted source reaches the sink across one or more
3143    /// value-import (module) hops. Derived from the reachability hop count.
3144    pub cross_module: bool,
3145    /// The architecture-zone crossing when the anchor participates in a declared
3146    /// boundary-rule violation in the same run. `None` when it crosses no
3147    /// declared zone boundary.
3148    #[serde(default, skip_serializing_if = "Option::is_none")]
3149    pub architecture_zone: Option<SecurityZoneCrossing>,
3150}
3151
3152/// Network-destination context for a `secret-to-network` candidate (#890): where
3153/// the secret-bearing network call sends its data. Present only on
3154/// network-category candidates. A consuming agent uses it to triage exfil
3155/// (dynamic / untrusted destination) from intended auth (a literal provider
3156/// host) without re-reading source.
3157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3158#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3159pub struct SecurityNetworkContext {
3160    /// The network call's destination as a static URL string literal, or absent
3161    /// when the destination is DYNAMIC (not a literal). A dynamic destination is
3162    /// the higher-signal exfil case; a literal provider host is usually intended
3163    /// auth.
3164    #[serde(default, skip_serializing_if = "Option::is_none")]
3165    pub destination: Option<String>,
3166}
3167
3168/// An agent-actionable candidate record on a [`SecurityFinding`]. fallow fills
3169/// `source_kind`, `sink`, and `boundary`. The exploitability IMPACT is
3170/// deliberately NOT a field: `severity` on the parent finding is only a
3171/// review-priority tier, while deciding exploitability remains the consuming
3172/// agent's job. A perpetually-null `impact` key would only train consumers to
3173/// ignore it. The agent reads this record, then writes its own impact verdict
3174/// downstream.
3175#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3176#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3177pub struct SecurityCandidate {
3178    /// The kind of untrusted input that reaches the sink, as a stable catalogue
3179    /// source id (`"http-request-input"`, `"process-env"`, `"process-argv"`,
3180    /// `"message-event-data"`, `"location-input"`, ...). `None`/absent when no
3181    /// untrusted source was matched (always `None` for `client-server-leak`).
3182    /// This is an OPEN string set, driven by the data-driven source catalogue; a
3183    /// consumer should treat an unknown id as "untrusted source of unknown kind"
3184    /// and never drop the candidate on that basis.
3185    #[serde(default, skip_serializing_if = "Option::is_none")]
3186    pub source_kind: Option<String>,
3187    /// The sink the candidate fires on, self-contained so the record is
3188    /// actionable without reading the parent finding.
3189    pub sink: SecurityCandidateSink,
3190    /// The structural boundary the flow crosses.
3191    pub boundary: SecurityCandidateBoundary,
3192    /// Network-destination context, present only on `secret-to-network` (#890)
3193    /// candidates: the host the secret-bearing call targets, so an agent can
3194    /// triage exfil from intended auth. Absent for every other category.
3195    #[serde(default, skip_serializing_if = "Option::is_none")]
3196    pub network: Option<SecurityNetworkContext>,
3197}
3198
3199/// One endpoint (source or sink node) of a [`SecurityTaintFlow`].
3200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3201#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3202pub struct TaintEndpoint {
3203    /// File of the endpoint. Absolute internally; JSON strips the project root.
3204    #[serde(serialize_with = "serde_path::serialize")]
3205    pub path: PathBuf,
3206    /// 1-based line of the endpoint.
3207    pub line: u32,
3208    /// 0-based byte column of the endpoint.
3209    pub col: u32,
3210}
3211
3212/// Compact taint-flow path shape. The ordered per-hop trace is NOT duplicated
3213/// here: it lives on [`SecurityReachability::untrusted_source_trace`]. This
3214/// carries only the flow's structural summary (intra-module flow plus the
3215/// cross-module hop count) so consumers do not parse two copies of the hops.
3216#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3217#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3218pub struct TaintPath {
3219    /// Whether the source and sink sit in the same module (no import hop between
3220    /// them); the source-to-sink association is intra-module.
3221    pub intra_module: bool,
3222    /// Number of value-import hops from the untrusted-source module to the sink
3223    /// module. Zero for an intra-module flow.
3224    pub cross_module_hops: u32,
3225}
3226
3227/// A source-to-sink taint-flow triple, emitted only when an untrusted source is
3228/// import-reachable to the sink (`reachability.reachable_from_untrusted_source`).
3229/// The `{ source, sink, path }` shape matches the model agent SAST tooling
3230/// expects (cf. Semgrep `taint_source` / `taint_sink`, SARIF `threadFlows`).
3231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3232#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3233pub struct SecurityTaintFlow {
3234    /// The untrusted-source endpoint (first hop of the reachability trace).
3235    pub source: TaintEndpoint,
3236    /// The sink endpoint (terminal hop of the reachability trace / the anchor).
3237    pub sink: TaintEndpoint,
3238    /// Compact flow shape: same-module flag plus module hop count. The full
3239    /// ordered path is `reachability.untrusted_source_trace`.
3240    pub path: TaintPath,
3241}
3242
3243/// Runtime coverage state for the function enclosing a security sink.
3244/// This is production-observation evidence, not an exploitability verdict.
3245#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3246#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3247#[serde(rename_all = "kebab-case")]
3248pub enum SecurityRuntimeState {
3249    /// The sink sits inside a runtime hot path.
3250    RuntimeHot,
3251    /// The sink sits inside a tracked function with zero production invocations.
3252    RuntimeCold,
3253    /// The sink sits inside a tracked function the runtime layer marked as safe
3254    /// to delete because it was never executed.
3255    NeverExecuted,
3256    /// The sink sits inside a function that executed, but below the low-traffic
3257    /// threshold.
3258    LowTraffic,
3259    /// Runtime coverage could not classify the enclosing function.
3260    CoverageUnavailable,
3261    /// A static enclosing function was found, but the runtime report carried no
3262    /// matching evidence for it.
3263    RuntimeUnknown,
3264}
3265
3266/// Runtime coverage context attached to a security candidate when
3267/// `fallow security --runtime-coverage` is supplied.
3268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3269#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3270pub struct SecurityRuntimeContext {
3271    /// Runtime state for the enclosing function.
3272    pub state: SecurityRuntimeState,
3273    /// Enclosing function name from static extraction.
3274    pub function: String,
3275    /// 1-based line where the enclosing function starts.
3276    pub line: u32,
3277    /// Observed invocation count when the runtime report provides it.
3278    #[serde(default, skip_serializing_if = "Option::is_none")]
3279    pub invocations: Option<u64>,
3280    /// Runtime coverage stable function id, when available.
3281    #[serde(default, skip_serializing_if = "Option::is_none")]
3282    pub stable_id: Option<String>,
3283    /// Short candidate-framed explanation of the runtime evidence.
3284    #[serde(default, skip_serializing_if = "Option::is_none")]
3285    pub evidence: Option<String>,
3286}
3287
3288/// Verification-priority tier for a security candidate. This is ranking, not an
3289/// exploitability verdict.
3290#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3291#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3292#[serde(rename_all = "lowercase")]
3293pub enum SecuritySeverity {
3294    /// Highest-priority candidate based on reachability, boundary, or runtime-hot signals.
3295    High,
3296    /// Candidate has source-reachability evidence but no high-priority signal.
3297    Medium,
3298    /// Candidate has no source-reachability or boundary signal.
3299    Low,
3300}
3301
3302/// Control pattern observed in a file on an attack-surface import trace.
3303/// Its presence does not prove that it executes before the sink or protects
3304/// the same input.
3305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3307pub struct SecurityDefensiveControl {
3308    /// Control family.
3309    pub kind: SecurityControlKind,
3310    /// File of the control site. Absolute internally; JSON strips the project root.
3311    #[serde(serialize_with = "serde_path::serialize")]
3312    pub path: PathBuf,
3313    /// 1-based line of the control site.
3314    pub line: u32,
3315    /// 0-based byte column of the control site.
3316    pub col: u32,
3317    /// Flattened callee path or a stable synthetic guard name.
3318    pub callee: String,
3319}
3320
3321/// Agent-facing defensive-boundary verification context for one surface path.
3322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3323#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3324pub struct SecurityDefensiveBoundary {
3325    /// Control patterns observed in files on this import trace. These are
3326    /// verification hints, not proof of sink protection or value-level data flow.
3327    pub controls: Vec<SecurityDefensiveControl>,
3328    /// Verification question for the consuming agent. It is a prompt, not a
3329    /// missing-guard verdict.
3330    pub verification_prompt: String,
3331}
3332
3333/// One untrusted entry to reachable sink path for `fallow security --surface`.
3334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3336pub struct SecurityAttackSurfaceEntry {
3337    /// The untrusted-source endpoint.
3338    pub source: TaintEndpoint,
3339    /// The reachable sink endpoint and catalogue metadata.
3340    pub sink: SecurityCandidateSink,
3341    /// Ordered source to sink path. Same shape as the reachability trace so
3342    /// consumers can reuse existing path handling.
3343    pub path: Vec<TraceHop>,
3344    /// Defensive-boundary context detected on this path.
3345    pub defensive_boundary: SecurityDefensiveBoundary,
3346}
3347
3348/// A local security CANDIDATE for downstream agent verification, NOT a verified
3349/// vulnerability. Emitted only by `fallow security`, never under bare `fallow`
3350/// or the `audit` gate. There is deliberately no `confidence` or
3351/// `signal_strength` field: fallow does not prove exploitability, so the trace
3352/// (its hops and length) is the only honest signal.
3353#[derive(Debug, Clone, Serialize, Deserialize)]
3354#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3355pub struct SecurityFinding {
3356    /// Stable per-finding correlation id, identical across runs for the same
3357    /// rule + anchor path + line + column. An autonomous agent that triaged this
3358    /// candidate on a prior run uses it to correlate the candidate after a
3359    /// rebase. Equal to the SARIF `partialFingerprints["fallowSecurity/v2"]`
3360    /// value for the same finding (one shared helper computes both).
3361    pub finding_id: String,
3362    /// The rule that produced this candidate.
3363    pub kind: SecurityFindingKind,
3364    /// The catalogue category id (e.g. `"dangerous-html"`). `Some` for
3365    /// `TaintedSink`. For `ClientServerLeak` it is `"client-server-leak"` for the
3366    /// secret leak (older releases omit it) or `"server-only-import"` when a
3367    /// `"use client"` cone reaches server-only code.
3368    #[serde(default, skip_serializing_if = "Option::is_none")]
3369    pub category: Option<String>,
3370    /// The CWE number declared by the matched catalogue entry. `None` for
3371    /// `ClientServerLeak`; never fabricated beyond the catalogue's value.
3372    #[serde(default, skip_serializing_if = "Option::is_none")]
3373    pub cwe: Option<u32>,
3374    /// File the finding is anchored on (the client boundary). Absolute
3375    /// internally; JSON strips the project root via `serde_path::serialize`.
3376    #[serde(serialize_with = "serde_path::serialize")]
3377    pub path: PathBuf,
3378    /// 1-based line number of the anchor.
3379    pub line: u32,
3380    /// 0-based byte column offset of the anchor.
3381    pub col: u32,
3382    /// Agent/human-readable evidence (e.g. the named env var the chain reaches).
3383    pub evidence: String,
3384    /// Whether the sink argument was associated with a known untrusted source by
3385    /// the intra-module source-to-sink back-trace (issue #859): a local binding
3386    /// referenced in the argument was sourced from a catalogue source path
3387    /// (`req.query`, `process.argv`, message-event `data`, etc.). `true` ranks
3388    /// the candidate higher and annotates the evidence; `false` does NOT
3389    /// suppress the finding (the association is conservative, never a proof, and
3390    /// fallow prefers false-negatives over false-positives). Always `false` for
3391    /// `ClientServerLeak`. Skipped from JSON when `false` for output stability.
3392    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3393    pub source_backed: bool,
3394    /// Internal cross-pass carrier (NEVER serialized): the (1-based line, 0-based
3395    /// col) of the arg-level source read, resolved by the detector when
3396    /// `source_backed` is true and a concrete read span was captured. The ranking
3397    /// pass uses it to anchor the taint trace's source node at the real read
3398    /// instead of the module import line. `None` for module-level findings and
3399    /// for arg-level findings with no concrete read span (synthetic
3400    /// framework-param / helper-return sources), where the trace falls back to
3401    /// the sink site.
3402    #[serde(skip)]
3403    pub source_read: Option<(u32, u32)>,
3404    /// Verification-priority tier derived from existing reachability, boundary,
3405    /// source-backed, and runtime signals. Candidate-only: this does not prove
3406    /// exploitability and does not change gates.
3407    pub severity: SecuritySeverity,
3408    /// Structural import-hop trace from the client boundary to the secret source.
3409    /// The hop count is the uncalibrated signal; fallow does not prove the path
3410    /// is exploitable.
3411    pub trace: Vec<TraceHop>,
3412    /// Machine-actionable next steps. Always emitted (possibly empty for
3413    /// forward-compat). For security candidates this is a single file-level
3414    /// suppress hint (`auto_fixable: false`); there is no auto-fix because
3415    /// verification is the agent's job, not fallow's.
3416    pub actions: Vec<IssueAction>,
3417    /// Dead-code cross-link when the same sink candidate sits in code fallow also
3418    /// reports as removable. Agents should verify the dead-code finding and delete
3419    /// the code instead of hardening the sink when deletion is safe.
3420    #[serde(default, skip_serializing_if = "Option::is_none")]
3421    pub dead_code: Option<SecurityDeadCodeContext>,
3422    /// Graph-derived reachability ranking signal (issues #860 and #885). `None`
3423    /// until the post-detection ranking pass fills it; additive on the wire
3424    /// (skipped when absent). Drives the order findings are emitted in:
3425    /// runtime-reachable candidates sort first, followed by source-backed and
3426    /// source-reachable candidates, then wider blast radius.
3427    #[serde(default, skip_serializing_if = "Option::is_none")]
3428    pub reachability: Option<SecurityReachability>,
3429    /// Agent-actionable candidate record: the untrusted input kind, the sink,
3430    /// and the boundary the flow crosses. fallow fills these three slots; the
3431    /// exploitability verdict is the agent's job and is not a field here. Always
3432    /// present.
3433    pub candidate: SecurityCandidate,
3434    /// Source-to-sink taint-flow triple, present only when an untrusted source
3435    /// is import-reachable to this sink. Absent (skipped) otherwise.
3436    #[serde(default, skip_serializing_if = "Option::is_none")]
3437    pub taint_flow: Option<SecurityTaintFlow>,
3438    /// Production runtime coverage context for the function enclosing this
3439    /// security sink. Present only when `fallow security --runtime-coverage`
3440    /// runs and the candidate is a `tainted-sink`.
3441    #[serde(default, skip_serializing_if = "Option::is_none")]
3442    pub runtime: Option<SecurityRuntimeContext>,
3443    /// Internal projection used by `fallow security --surface`. The CLI strips
3444    /// this from per-finding JSON and promotes it to the top-level
3445    /// `attack_surface` field only when requested.
3446    #[serde(default, skip_serializing_if = "Option::is_none")]
3447    pub attack_surface: Option<SecurityAttackSurfaceEntry>,
3448}
3449
3450/// A package manager catalog entry that no workspace package references via
3451/// the `catalog:` protocol.
3452///
3453/// The default catalog uses `catalog_name: "default"`. Named catalogs
3454/// (`catalogs.<name>`) use their declared name. The source file is the
3455/// `pnpm-workspace.yaml` of the root or of a nested pnpm project, or the
3456/// root `package.json` for Bun catalogs.
3457#[derive(Debug, Clone, Serialize, Deserialize)]
3458#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3459pub struct UnusedCatalogEntry {
3460    /// Package name declared in the catalog (e.g. `"react"`, `"@scope/lib"`).
3461    pub entry_name: String,
3462    /// Catalog group: `"default"` for the default catalog map, or the named
3463    /// catalog key for entries declared under `catalogs.<name>`.
3464    pub catalog_name: String,
3465    /// Path to the catalog source file, relative to the analyzed root.
3466    #[serde(serialize_with = "serde_path::serialize")]
3467    pub path: PathBuf,
3468    /// 1-based line number of the catalog entry within the source file.
3469    pub line: u32,
3470    /// Workspace `package.json` files that declare the same package with a
3471    /// hardcoded version range instead of `catalog:`. Empty when no consumer
3472    /// uses a hardcoded version. Sorted lexicographically for deterministic
3473    /// output.
3474    #[serde(
3475        default,
3476        serialize_with = "serde_path::serialize_vec",
3477        skip_serializing_if = "Vec::is_empty"
3478    )]
3479    pub hardcoded_consumers: Vec<PathBuf>,
3480}
3481
3482/// A named `catalogs.<name>` group with no package entries.
3483#[derive(Debug, Clone, Serialize, Deserialize)]
3484#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3485pub struct EmptyCatalogGroup {
3486    /// Catalog group name declared under the `catalogs` map.
3487    pub catalog_name: String,
3488    /// Path to the catalog source file, relative to the analyzed root.
3489    #[serde(serialize_with = "serde_path::serialize")]
3490    pub path: PathBuf,
3491    /// 1-based line number of the empty group header within the source file.
3492    pub line: u32,
3493}
3494
3495/// A workspace package.json reference (`catalog:` or `catalog:<name>`) that points
3496/// at a catalog which does not declare the consumed package.
3497///
3498/// Package manager installs error when this happens. fallow surfaces it
3499/// statically so the failure is caught at `fallow dead-code` time, before any
3500/// install.
3501///
3502/// The default catalog (bare `catalog:`) uses `catalog_name: "default"`.
3503/// Named catalogs (`catalog:react17`) use the declared catalog name.
3504#[derive(Debug, Clone, Serialize, Deserialize)]
3505#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3506pub struct UnresolvedCatalogReference {
3507    /// Package name being referenced via the catalog protocol (e.g. `"react"`).
3508    pub entry_name: String,
3509    /// Catalog group the reference points at: `"default"` for bare `catalog:` references,
3510    /// or the named catalog key for `catalog:<name>` references.
3511    pub catalog_name: String,
3512    /// Absolute path to the consumer `package.json`. Matches the storage
3513    /// convention used by every path-anchored finding type (`UnusedFile`,
3514    /// `UnresolvedImport`, `UnusedExport`, etc.) so the shared filtering
3515    /// pipelines (`filter_results_by_changed_files`, per-file overrides,
3516    /// audit attribution) work without a separate root-join pass. JSON
3517    /// output strips the project-root prefix via `serde_path::serialize`.
3518    #[serde(serialize_with = "serde_path::serialize")]
3519    pub path: PathBuf,
3520    /// 1-based line number of the dependency entry in the consumer `package.json`.
3521    pub line: u32,
3522    /// Other catalogs in the same catalog source that DO declare this package.
3523    /// Empty when no catalog has the package. Sorted lexicographically. Lets
3524    /// agents and humans decide whether to switch the reference to a different
3525    /// catalog or to add the entry to the named catalog.
3526    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3527    pub available_in_catalogs: Vec<String>,
3528}
3529
3530/// Where an override entry was declared. Serialized as the filename label
3531/// (`"pnpm-workspace.yaml"` or `"package.json"`) so the value in JSON output
3532/// matches the value users write in `ignoreDependencyOverrides[].source`.
3533#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3534#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3535pub enum DependencyOverrideSource {
3536    /// Top-level `overrides:` key in `pnpm-workspace.yaml`.
3537    #[serde(rename = "pnpm-workspace.yaml")]
3538    PnpmWorkspaceYaml,
3539    /// `pnpm.overrides`, the top-level npm `overrides` object, or (in a bun
3540    /// repository) the Yarn-style top-level `resolutions` object in a root
3541    /// `package.json`.
3542    #[serde(rename = "package.json")]
3543    PnpmPackageJson,
3544}
3545
3546impl DependencyOverrideSource {
3547    /// Stable string label matching the serde rename. Used in baseline keys,
3548    /// audit keys, jq comparisons, and `ignoreDependencyOverrides[].source`.
3549    #[must_use]
3550    pub const fn as_label(&self) -> &'static str {
3551        match self {
3552            Self::PnpmWorkspaceYaml => "pnpm-workspace.yaml",
3553            Self::PnpmPackageJson => "package.json",
3554        }
3555    }
3556}
3557
3558impl std::fmt::Display for DependencyOverrideSource {
3559    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3560        f.write_str(self.as_label())
3561    }
3562}
3563
3564/// An entry in pnpm's `overrides:` map (or the legacy `pnpm.overrides` in
3565/// `package.json`), in npm's top-level `overrides` object in `package.json`,
3566/// or (in a bun repository) in the Yarn-style top-level `resolutions` object
3567/// in `package.json`, whose target package is not declared in any workspace
3568/// `package.json` and is not present in `pnpm-lock.yaml`,
3569/// `package-lock.json`, or `bun.lock`. Projects without a readable lockfile
3570/// fall back to package manifest checks; the `hint` field flags that
3571/// conservative mode.
3572#[derive(Debug, Clone, Serialize, Deserialize)]
3573#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3574pub struct UnusedDependencyOverride {
3575    /// The full original override key as written in the source (e.g.
3576    /// `"react>react-dom"`, `"@types/react@<18"`). Preserved for round-trip
3577    /// reporting so agents see the unmodified spelling.
3578    pub raw_key: String,
3579    /// The target package the override rewrites (e.g. `"react-dom"` for
3580    /// `"react>react-dom"`, `"@types/react"` for `"@types/react@<18"`).
3581    pub target_package: String,
3582    /// Optional parent package (left side of `>`). `None` for bare-target keys.
3583    #[serde(default, skip_serializing_if = "Option::is_none")]
3584    pub parent_package: Option<String>,
3585    /// Optional version selector on the target (e.g. `Some("<18")` for
3586    /// `"@types/react@<18"`).
3587    #[serde(default, skip_serializing_if = "Option::is_none")]
3588    pub version_constraint: Option<String>,
3589    /// The right-hand side of the entry: the version the package manager should force.
3590    pub version_range: String,
3591    /// File the override was declared in. Matches the value users write in
3592    /// `ignoreDependencyOverrides[].source`.
3593    pub source: DependencyOverrideSource,
3594    /// Path to the source file. `pnpm-workspace.yaml` or a `package.json`,
3595    /// stored as an absolute filesystem path so `--changed-since` and
3596    /// per-file `overrides.rules` can compare directly against the analyzer's
3597    /// changed-set / per-path rule lookups. JSON serialization strips the
3598    /// project root via `serde_path::serialize`, matching the
3599    /// `UnresolvedCatalogReference` convention.
3600    #[serde(serialize_with = "serde_path::serialize")]
3601    pub path: PathBuf,
3602    /// 1-based line number of the entry within the source file.
3603    pub line: u32,
3604    /// Soft hint reminding consumers to verify the override before removal.
3605    /// Emitted on every unused-override finding (both bare-target and
3606    /// parent-chain shapes) because projects without a readable lockfile still
3607    /// use the conservative package-manifest fallback.
3608    #[serde(default, skip_serializing_if = "Option::is_none")]
3609    pub hint: Option<String>,
3610}
3611
3612/// Why a dependency-override entry is misconfigured. The active package
3613/// manager may fail at install time or silently no-op on these entries;
3614/// surfacing them statically catches the issue first.
3615#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3616#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3617#[serde(rename_all = "kebab-case")]
3618pub enum DependencyOverrideMisconfigReason {
3619    /// The override key could not be parsed into a recognised source shape
3620    /// (e.g. dangling `>`, missing target, garbage characters).
3621    UnparsableKey,
3622    /// The override value is missing, empty, or contains line breaks.
3623    EmptyValue,
3624}
3625
3626impl DependencyOverrideMisconfigReason {
3627    /// Human-readable summary of the reason.
3628    #[must_use]
3629    pub const fn describe(self) -> &'static str {
3630        match self {
3631            Self::UnparsableKey => "override key cannot be parsed",
3632            Self::EmptyValue => "override value is missing or empty",
3633        }
3634    }
3635}
3636
3637/// An override entry whose key or value is malformed. Default severity is
3638/// `error` because the active package manager may refuse to install or silently
3639/// produce a no-op override when it encounters these shapes.
3640#[derive(Debug, Clone, Serialize, Deserialize)]
3641#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3642pub struct MisconfiguredDependencyOverride {
3643    /// The full original override key as written in the source.
3644    pub raw_key: String,
3645    /// Parsed target package name when the key was syntactically valid (the
3646    /// `EmptyValue` reason path). `None` for `UnparsableKey` findings whose
3647    /// key could not be parsed at all. Used by JSON `add-to-config` actions to
3648    /// emit a paste-ready `ignoreDependencyOverrides` value that matches the
3649    /// suppression matcher (which also keys on `target_package`); avoids the
3650    /// pitfall where `raw_key` like `"react@<18"` would not match the rule
3651    /// that targets package `"react"`.
3652    #[serde(default, skip_serializing_if = "Option::is_none")]
3653    pub target_package: Option<String>,
3654    /// The right-hand side of the entry, exactly as written. Empty when the
3655    /// value was missing.
3656    pub raw_value: String,
3657    /// Classifier for the misconfiguration. 'unparsable-key' = the key is not a
3658    /// valid source shape; 'empty-value' = the value is missing, empty, or
3659    /// contains line breaks.
3660    pub reason: DependencyOverrideMisconfigReason,
3661    /// Where the override entry was declared.
3662    pub source: DependencyOverrideSource,
3663    /// Path to the source file. Stored as an absolute filesystem path so
3664    /// `--changed-since` and per-file `overrides.rules` can compare directly.
3665    /// JSON serialization strips the project root via `serde_path::serialize`.
3666    #[serde(serialize_with = "serde_path::serialize")]
3667    pub path: PathBuf,
3668    /// 1-based line number of the entry within the source file.
3669    pub line: u32,
3670}
3671
3672/// A production dependency that is only imported by test files.
3673/// Since it is never used in production code, it could be moved to devDependencies.
3674#[derive(Debug, Clone, Serialize, Deserialize)]
3675#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3676pub struct TestOnlyDependency {
3677    /// Production dependency that is only imported by test files, consider
3678    /// moving to devDependencies.
3679    pub package_name: String,
3680    /// Path to the package.json where the dependency is listed.
3681    #[serde(serialize_with = "serde_path::serialize")]
3682    pub path: PathBuf,
3683    /// 1-based line number of the dependency entry in package.json.
3684    pub line: u32,
3685}
3686
3687/// A `devDependencies` package imported by production (non-test, non-config)
3688/// source code via a runtime/value import. Because a production-only install
3689/// (`pnpm install --prod`) omits devDependencies, it would break at runtime, so
3690/// the package should be promoted to `dependencies`. The promote-side mirror of
3691/// [`TestOnlyDependency`] / [`TypeOnlyDependency`].
3692#[derive(Debug, Clone, Serialize, Deserialize)]
3693#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3694pub struct DevDependencyInProduction {
3695    /// devDependency imported at runtime from production code, consider moving
3696    /// to dependencies.
3697    pub package_name: String,
3698    /// Path to the package.json where the dependency is listed.
3699    #[serde(serialize_with = "serde_path::serialize")]
3700    pub path: PathBuf,
3701    /// 1-based line number of the dependency entry in package.json.
3702    pub line: u32,
3703}
3704
3705/// One import hop in a circular dependency: the file containing the import
3706/// and where that import statement sits.
3707///
3708/// `edges[i]` is the import IN `path` (the hop SOURCE, equal to the cycle's
3709/// `files[i]`) that points to the NEXT file in the cycle
3710/// (`files[(i + 1) % files.len()]`); the target is not repeated here to keep
3711/// the wire compact. Enables a per-file diagnostic squiggly anchored under
3712/// the offending import rather than a single squiggly on the first file.
3713///
3714/// `col` is a 0-based BYTE column, matching the cycle's top-level `col`;
3715/// converting it to a UTF-16 code-unit column for LSP clients is a tracked
3716/// follow-up shared with the existing field.
3717#[derive(Debug, Clone, Serialize, Deserialize)]
3718#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3719pub struct CircularDependencyEdge {
3720    /// The file containing the import (the hop SOURCE; equal to `files[i]`).
3721    #[serde(serialize_with = "serde_path::serialize")]
3722    pub path: PathBuf,
3723    /// 1-based line number of the import statement pointing to the next file.
3724    pub line: u32,
3725    /// 0-based byte column offset of the import statement.
3726    pub col: u32,
3727}
3728
3729/// A circular dependency chain detected in the module graph.
3730///
3731/// The `line` and `col` fields carry `#[serde(default)]` so callers reading
3732/// historical baseline JSON without these fields can still deserialize the
3733/// struct, but the JSON output layer always emits them (u32 always
3734/// serializes, never via `skip_serializing_if`). The schemars derive sees
3735/// the serde defaults and marks both fields optional in the generated
3736/// schema; the explicit `extend("required" = ...)` override here keeps the
3737/// schema's `required` array honest about what the JSON output actually
3738/// contains.
3739///
3740/// `edges` is deliberately kept OUT of the `required` extend: it is
3741/// `#[serde(default)]` (so historical baseline JSON without it still
3742/// deserializes) and the output layer always emits it, but listing it in
3743/// `required` would make pre-upgrade JSON fail validation against the new
3744/// schema. It is a normal additive field: always present in current output,
3745/// optional for backward compatibility.
3746#[derive(Debug, Clone, Serialize, Deserialize)]
3747#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3748#[cfg_attr(feature = "schema", schemars(extend("required" = ["files", "length", "line", "col"])))]
3749pub struct CircularDependency {
3750    /// Files forming the cycle, in import order.
3751    #[serde(serialize_with = "serde_path::serialize_vec")]
3752    pub files: Vec<PathBuf>,
3753    /// Number of files in the cycle.
3754    pub length: usize,
3755    /// 1-based line number of the import that starts the cycle (in the first file).
3756    #[serde(default)]
3757    pub line: u32,
3758    /// 0-based byte column offset of the import that starts the cycle.
3759    #[serde(default)]
3760    pub col: u32,
3761    /// Per-file import anchors, one entry per hop in cycle order: `edges[i]`
3762    /// is the import in `files[i]` pointing to `files[(i + 1) % len]`. Always
3763    /// the same length as `files`. Drives the per-file LSP diagnostic
3764    /// squiggly. `#[serde(default)]` so pre-`edges` baselines deserialize;
3765    /// always emitted on output but intentionally not in the schema's
3766    /// `required` set (see the struct doc).
3767    #[serde(default)]
3768    pub edges: Vec<CircularDependencyEdge>,
3769    /// Whether this cycle crosses workspace package boundaries.
3770    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3771    pub is_cross_package: bool,
3772}
3773
3774/// A cycle or self-loop in the re-export edge subgraph.
3775///
3776/// Detected by Tarjan SCC over `(barrel, source)` re-export edges in
3777/// `crates/graph/src/graph/re_exports/`. A multi-node cycle is a strongly
3778/// connected component of size >= 2; a self-loop is a barrel that re-exports
3779/// from itself (often a rename leftover or accidental `export * from './'`).
3780/// Both are structural bugs because chain propagation through the loop is a
3781/// no-op: any symbol consumers think they are re-exporting through the cycle
3782/// silently fails to resolve.
3783#[derive(Debug, Clone, Serialize, Deserialize)]
3784#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3785pub struct ReExportCycle {
3786    /// Files participating in the cycle, sorted lexicographically. For a
3787    /// self-loop, exactly one entry.
3788    #[serde(serialize_with = "serde_path::serialize_vec")]
3789    pub files: Vec<PathBuf>,
3790    /// Which structural shape this finding describes.
3791    pub kind: ReExportCycleKind,
3792}
3793
3794/// Discriminator for [`ReExportCycle`]: which structural shape was detected.
3795#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3796#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3797#[serde(rename_all = "kebab-case")]
3798pub enum ReExportCycleKind {
3799    /// Two or more barrel files re-export from each other in a loop
3800    /// (SCC of size >= 2).
3801    MultiNode,
3802    /// A single barrel file re-exports from itself.
3803    SelfLoop,
3804}
3805
3806/// One package hop in a [`PackageCycle`]: `from_package` imports
3807/// `to_package`, and `path` holds one example import for that hop.
3808///
3809/// The example import is the first runtime import by `(path, line)`. When
3810/// every import on the hop is type-only, it is the first type-only import.
3811#[derive(Debug, Clone, Serialize, Deserialize)]
3812#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3813pub struct PackageCycleEdge {
3814    /// Label of the importing workspace package, as in
3815    /// [`PackageCycle::packages`].
3816    pub from_package: String,
3817    /// Label of the imported workspace package, as in
3818    /// [`PackageCycle::packages`].
3819    pub to_package: String,
3820    /// File in `from_package` that holds the example import.
3821    #[serde(serialize_with = "serde_path::serialize")]
3822    pub path: PathBuf,
3823    /// File in `to_package` that the example import resolves to.
3824    #[serde(serialize_with = "serde_path::serialize")]
3825    pub target_path: PathBuf,
3826    /// 1-based line number of the example import.
3827    pub line: u32,
3828    /// 0-based byte column offset of the example import.
3829    pub col: u32,
3830    /// True when every import from `from_package` to `to_package` is
3831    /// type-only. A type-only hop has no runtime effect, but it can still
3832    /// force a build order (for example with declaration builds).
3833    pub type_only: bool,
3834}
3835
3836/// A dependency cycle between workspace packages.
3837///
3838/// Each workspace package is a node. A resolved import from a file in one
3839/// package to a file in another package is an edge. Declared `package.json`
3840/// dependencies are not edges, and imports from test, spec, story, fixture
3841/// and tooling config files are not edges. A package cycle can exist when no
3842/// file-level cycle exists.
3843#[derive(Debug, Clone, Serialize, Deserialize)]
3844#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3845pub struct PackageCycle {
3846    /// Workspace package labels in cycle order. The first entry is the
3847    /// lexicographically smallest label; the last entry imports the first.
3848    /// A label is the package name. When two or more workspace packages
3849    /// share a name, the label is `name (root)` with the project-relative
3850    /// package root, so that each label names one package.
3851    pub packages: Vec<String>,
3852    /// Package root directories in cycle order: `package_roots[i]` is the
3853    /// root of `packages[i]`.
3854    #[serde(serialize_with = "serde_path::serialize_vec")]
3855    pub package_roots: Vec<PathBuf>,
3856    /// Number of packages in the cycle.
3857    pub length: usize,
3858    /// One example import per hop, in cycle order: `edges[i]` goes from
3859    /// `packages[i]` to `packages[(i + 1) % length]`.
3860    pub edges: Vec<PackageCycleEdge>,
3861    /// True when the group of packages that holds this cycle has more
3862    /// cycles than fallow lists. The listing stops at 20 cycles per group,
3863    /// or earlier on a very dense package graph. Break a listed cycle and
3864    /// run again to see the rest.
3865    pub group_truncated: bool,
3866}
3867
3868impl PackageCycle {
3869    /// The note that every output format shows for a cycle with
3870    /// [`PackageCycle::group_truncated`] set.
3871    pub const GROUP_TRUNCATED_NOTE: &'static str = "this package group has more cycles than listed";
3872
3873    /// The package labels in cycle order, with the first label repeated at
3874    /// the end, joined with `separator`.
3875    #[must_use]
3876    pub fn chain(&self, separator: &str) -> String {
3877        let mut chain: Vec<&str> = self.packages.iter().map(String::as_str).collect();
3878        if let Some(first) = chain.first().copied() {
3879            chain.push(first);
3880        }
3881        chain.join(separator)
3882    }
3883}
3884
3885/// An import that crosses an architecture boundary rule.
3886#[derive(Debug, Clone, Serialize, Deserialize)]
3887#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3888pub struct BoundaryViolation {
3889    /// The file making the disallowed import.
3890    #[serde(serialize_with = "serde_path::serialize")]
3891    pub from_path: PathBuf,
3892    /// The file being imported that violates the boundary. When the import
3893    /// goes through a re-export chain, this is the origin module that
3894    /// declares the imported symbol, not the barrel.
3895    #[serde(serialize_with = "serde_path::serialize")]
3896    pub to_path: PathBuf,
3897    /// The zone the importing file belongs to.
3898    pub from_zone: String,
3899    /// The zone the imported file belongs to.
3900    pub to_zone: String,
3901    /// The raw import specifier from the source file.
3902    pub import_specifier: String,
3903    /// 1-based line number of the import statement in the source file.
3904    pub line: u32,
3905    /// 0-based byte column offset of the import statement.
3906    pub col: u32,
3907    /// The barrel file that the source file imports directly, when the
3908    /// violation comes from a re-export chain. Absent for a direct import.
3909    #[serde(
3910        default,
3911        serialize_with = "serde_path::serialize_option",
3912        skip_serializing_if = "Option::is_none"
3913    )]
3914    pub via_path: Option<PathBuf>,
3915}
3916
3917/// A source file that does not match any configured architecture boundary zone.
3918#[derive(Debug, Clone, Serialize, Deserialize)]
3919#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3920pub struct BoundaryCoverageViolation {
3921    /// The unmatched source file.
3922    #[serde(serialize_with = "serde_path::serialize")]
3923    pub path: PathBuf,
3924    /// 1-based line number used for diagnostics.
3925    pub line: u32,
3926    /// 0-based byte column offset used for diagnostics.
3927    pub col: u32,
3928}
3929
3930/// A call from a zoned file to a callee forbidden for that zone via
3931/// `boundaries.calls.forbidden`. One finding is reported per call or `new`
3932/// site.
3933#[derive(Debug, Clone, Serialize, Deserialize)]
3934#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3935pub struct BoundaryCallViolation {
3936    /// The zoned source file making the forbidden call.
3937    #[serde(serialize_with = "serde_path::serialize")]
3938    pub path: PathBuf,
3939    /// 1-based line number of the call site.
3940    pub line: u32,
3941    /// 0-based byte column offset of the call site.
3942    pub col: u32,
3943    /// The zone the calling file is classified into.
3944    pub zone: String,
3945    /// The callee path as written (e.g. `cp.exec`), with the prefix `new ` for a `new` expression.
3946    pub callee: String,
3947    /// The configured pattern that matched (e.g. `child_process.*`), so
3948    /// consumers can see both the written path and the rule that fired.
3949    pub pattern: String,
3950}
3951
3952/// Which rule-pack rule kind produced a [`PolicyViolation`].
3953#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3954#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3955#[serde(rename_all = "kebab-case")]
3956pub enum PolicyRuleKind {
3957    /// A call or `new` expression matched a `banned-call` rule's callee patterns.
3958    BannedCall,
3959    /// An import or re-export specifier matched a `banned-import` rule.
3960    BannedImport,
3961    /// A call site matched a catalogue-derived `banned-effect` rule.
3962    BannedEffect,
3963    /// An exported name matched a `banned-export` rule.
3964    BannedExport,
3965    /// A resolved gdp-ts proof factory call occurred outside allowed modules.
3966    GdpProofProducer,
3967}
3968
3969/// Effective severity of a single [`PolicyViolation`]. Per-rule `severity`
3970/// overrides the `rules."policy-violation"` master; `off` rules emit nothing,
3971/// so only `error` and `warn` appear on the wire. The exit-code gate inspects
3972/// this per-finding value, not the master severity.
3973#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3974#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3975#[serde(rename_all = "lowercase")]
3976pub enum PolicyViolationSeverity {
3977    /// Sets a non-zero exit code.
3978    Error,
3979    /// Reported without an effect on the exit code. The dead-code count gate
3980    /// of the GitHub Action counts it unless `fail-on-issues` is `false`.
3981    Warn,
3982}
3983
3984/// A banned call, banned import, banned effect, or banned export matched by a
3985/// declarative rule pack (`rulePacks` config). Banned-call and banned-effect
3986/// findings report one entry per call site (`new` sites count for banned-call
3987/// only), matching `boundary_call_violations`; banned-import findings anchor
3988/// at each matching import or re-export declaration; banned-export findings
3989/// anchor at matching export declarations.
3990#[derive(Debug, Clone, Serialize, Deserialize)]
3991#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3992pub struct PolicyViolation {
3993    /// The source file containing the banned call, import, or effectful usage.
3994    #[serde(serialize_with = "serde_path::serialize")]
3995    pub path: PathBuf,
3996    /// 1-based line number of the call site or import declaration.
3997    pub line: u32,
3998    /// 0-based byte column offset of the call site or import declaration.
3999    pub col: u32,
4000    /// Name of the rule pack that declared the matching rule.
4001    pub pack: String,
4002    /// Id of the matching rule inside the pack. `pack` plus `rule_id` is the
4003    /// finding's policy identity.
4004    pub rule_id: String,
4005    /// Which rule kind matched.
4006    pub kind: PolicyRuleKind,
4007    /// What matched: the written callee path for `banned-call` (e.g. `cp.exec`, or `new Date` for a `new` expression), `<effect>: <callee>` for `banned-effect`,
4008    /// or the exported name for `banned-export`. For `gdp-proof-producer`, the canonical factory with its JSON-quoted literal label or `...` for a dynamic label.
4009    /// For `banned-import`: the raw import specifier (e.g. `moment/locale/nl`), or `<specifier>: <binding>` when the rule sets `allowNames`.
4010    /// `<binding>` is the source-side imported name, `default`, `*` for a namespace or star form,
4011    /// or `side-effect`.
4012    pub matched: String,
4013    /// Effective severity for this finding (per-rule `severity`, else the
4014    /// `rules."policy-violation"` master).
4015    pub severity: PolicyViolationSeverity,
4016    /// The rule's author-provided message, when set.
4017    #[serde(default, skip_serializing_if = "Option::is_none")]
4018    pub message: Option<String>,
4019}
4020
4021/// The origin of a stale suppression: inline comment or JSDoc tag.
4022#[derive(Debug, Clone, Serialize, Deserialize)]
4023#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4024#[serde(rename_all = "snake_case", tag = "type")]
4025pub enum SuppressionOrigin {
4026    /// A `// fallow-ignore-next-line` or `// fallow-ignore-file` comment.
4027    Comment {
4028        /// The issue kind token from the comment (e.g., "unused-exports"), or None for blanket.
4029        #[serde(default, skip_serializing_if = "Option::is_none")]
4030        issue_kind: Option<String>,
4031        /// Human-authored reason after `--`, when present.
4032        #[serde(default, skip_serializing_if = "Option::is_none")]
4033        reason: Option<String>,
4034        /// Whether this was a file-level suppression.
4035        is_file_level: bool,
4036        /// Whether `issue_kind` parses to a known `IssueKind`. False when the
4037        /// token is a typo or refers to a kind that was renamed or removed in
4038        /// a newer fallow release. JSON consumers (CI annotations, MCP agents,
4039        /// VS Code) branch on this to choose the right next-step text.
4040        /// Omitted from the wire when `true` so producers that have not yet
4041        /// adopted the field stay byte-compatible. See issue #449.
4042        #[serde(default = "default_true", skip_serializing_if = "is_true")]
4043        kind_known: bool,
4044    },
4045    /// An `@expected-unused` JSDoc tag on an export.
4046    JsdocTag {
4047        /// The name of the export that was tagged.
4048        export_name: String,
4049        /// Human-authored reason after `--`, when present.
4050        #[serde(default, skip_serializing_if = "Option::is_none")]
4051        reason: Option<String>,
4052    },
4053}
4054
4055#[expect(
4056    clippy::trivially_copy_pass_by_ref,
4057    reason = "serde skip_serializing_if takes a reference by contract"
4058)]
4059const fn is_true(b: &bool) -> bool {
4060    *b
4061}
4062
4063/// Default for `SuppressionOrigin::Comment.kind_known` when the field is
4064/// absent from a deserialized payload, paired with `skip_serializing_if = is_true`
4065/// so schemars marks the field non-required in the generated JSON Schema AND
4066/// the absent case round-trips to the recognized-kind interpretation.
4067/// Referenced by the always-emitted `#[serde(default = "default_true")]`
4068/// attribute. Serde uses it when saved reports deserialize the output back
4069/// into the typed findings, while schemars uses it to keep `kind_known`
4070/// optional in the generated schema.
4071const fn default_true() -> bool {
4072    true
4073}
4074
4075/// A suppression comment or JSDoc tag that no longer matches any issue.
4076#[derive(Debug, Clone, Serialize, Deserialize)]
4077#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4078pub struct StaleSuppression {
4079    /// File containing the stale suppression.
4080    #[serde(serialize_with = "serde_path::serialize")]
4081    pub path: PathBuf,
4082    /// 1-based line number of the suppression comment or tag.
4083    pub line: u32,
4084    /// 0-based byte column offset.
4085    pub col: u32,
4086    /// The origin and details of the stale suppression.
4087    pub origin: SuppressionOrigin,
4088    /// True when `rules.require-suppression-reason` reported a suppression
4089    /// comment or tag that has no reason.
4090    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
4091    pub missing_reason: bool,
4092    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4093    /// `~<k>` suffix when several findings of one type share an identity.
4094    /// Line and column are not inputs, so the id survives line shifts,
4095    /// reformats and reorders. A rename of the file or the symbol gives a
4096    /// new id. Absent in output from older versions.
4097    #[serde(default, skip_serializing_if = "Option::is_none")]
4098    pub finding_id: Option<String>,
4099    /// Suggested next steps. Always emitted.
4100    pub actions: Vec<IssueAction>,
4101    /// Gate severity of this finding after `rules` and `overrides[].rules`
4102    /// resolve for its path. CI formats read it for the annotation, SARIF
4103    /// and CodeClimate level. Absent in output from older versions. Not
4104    /// part of the finding identity, baseline keys or fingerprints.
4105    #[serde(
4106        default,
4107        skip_serializing_if = "Option::is_none",
4108        deserialize_with = "crate::output_dead_code::deserialize_effective_severity"
4109    )]
4110    pub effective_severity: Option<crate::output_dead_code::EffectiveSeverity>,
4111}
4112
4113impl StaleSuppression {
4114    /// Build the typed action list for this suppression finding.
4115    #[must_use]
4116    pub fn actions_for(missing_reason: bool) -> Vec<IssueAction> {
4117        let (kind, description) = if missing_reason {
4118            (
4119                FixActionType::AddSuppressionReason,
4120                "Add a human-authored reason after `--` on the suppression",
4121            )
4122        } else {
4123            (
4124                FixActionType::RemoveStaleSuppression,
4125                "Remove or update the stale suppression",
4126            )
4127        };
4128        let mut actions = vec![IssueAction::Fix(FixAction {
4129            kind,
4130            auto_fixable: false,
4131            description: description.to_string(),
4132            note: None,
4133            available_in_catalogs: None,
4134            suggested_target: None,
4135        })];
4136        if !missing_reason {
4137            actions.push(IssueAction::SuppressLine(SuppressLineAction {
4138                kind: SuppressLineKind::SuppressLine,
4139                auto_fixable: false,
4140                description:
4141                    "Suppress this stale suppression finding with a comment above the suppression"
4142                        .to_string(),
4143                comment: "// fallow-ignore-next-line stale-suppression".to_string(),
4144                scope: Some(SuppressLineScope::PerLocation),
4145            }));
4146        }
4147        actions
4148    }
4149
4150    /// Produce a human-readable description of this stale suppression.
4151    #[must_use]
4152    pub fn description(&self) -> String {
4153        match &self.origin {
4154            SuppressionOrigin::Comment {
4155                issue_kind,
4156                reason,
4157                is_file_level,
4158                ..
4159            } => {
4160                let directive = if *is_file_level {
4161                    "fallow-ignore-file"
4162                } else {
4163                    "fallow-ignore-next-line"
4164                };
4165                match issue_kind {
4166                    Some(kind) => match reason {
4167                        Some(reason) => format!("// {directive} {kind} -- {reason}"),
4168                        None => format!("// {directive} {kind}"),
4169                    },
4170                    None => match reason {
4171                        Some(reason) => format!("// {directive} -- {reason}"),
4172                        None => format!("// {directive}"),
4173                    },
4174                }
4175            }
4176            SuppressionOrigin::JsdocTag {
4177                export_name,
4178                reason,
4179            } => match reason {
4180                Some(reason) => format!("@expected-unused on {export_name} -- {reason}"),
4181                None => format!("@expected-unused on {export_name}"),
4182            },
4183        }
4184    }
4185
4186    /// Produce an explanation of why this suppression is stale.
4187    ///
4188    /// For comment suppressions where `kind_known == false`, surfaces the
4189    /// unknown token plus a Levenshtein "did you mean?" hint when one is
4190    /// within edit distance 2. Other tokens on the same comment line still
4191    /// apply normally (see issue #449).
4192    #[must_use]
4193    pub fn explanation(&self) -> String {
4194        match &self.origin {
4195            SuppressionOrigin::Comment {
4196                issue_kind,
4197                is_file_level,
4198                kind_known,
4199                ..
4200            } => {
4201                if self.missing_reason {
4202                    return "suppression is missing a reason".to_string();
4203                }
4204                let scope = if *is_file_level {
4205                    "in this file"
4206                } else {
4207                    "on the next line"
4208                };
4209                match issue_kind {
4210                    Some(kind) if !*kind_known => match closest_known_kind_name(kind) {
4211                        Some(suggestion) => format!(
4212                            "'{kind}' is not a recognized fallow issue kind. Did you mean '{suggestion}'? Other tokens on this line still apply."
4213                        ),
4214                        None => format!(
4215                            "'{kind}' is not a recognized fallow issue kind. Other tokens on this line still apply."
4216                        ),
4217                    },
4218                    Some(kind) => format!("no {kind} issue found {scope}"),
4219                    None => format!("no issues found {scope}"),
4220                }
4221            }
4222            SuppressionOrigin::JsdocTag { export_name, .. } => {
4223                if self.missing_reason {
4224                    return "suppression is missing a reason".to_string();
4225                }
4226                format!("{export_name} is now used")
4227            }
4228        }
4229    }
4230
4231    /// Per-format display message combining `description()` and `explanation()`
4232    /// for the unknown-kind case so SARIF, CodeClimate, and compact consumers
4233    /// surface the typo-fix copy and Levenshtein hint without needing to
4234    /// branch on `origin.kind_known` themselves. Stale-but-known and JSDoc
4235    /// origins keep the bare `description()` so existing wire bytes stay
4236    /// unchanged. See issue #449.
4237    #[must_use]
4238    pub fn display_message(&self) -> String {
4239        match &self.origin {
4240            SuppressionOrigin::Comment {
4241                kind_known: false, ..
4242            } => format!("{} ({})", self.description(), self.explanation()),
4243            SuppressionOrigin::Comment { .. } | SuppressionOrigin::JsdocTag { .. }
4244                if self.missing_reason =>
4245            {
4246                format!("{} ({})", self.description(), self.explanation())
4247            }
4248            SuppressionOrigin::Comment { .. } | SuppressionOrigin::JsdocTag { .. } => {
4249                self.description()
4250            }
4251        }
4252    }
4253}
4254
4255/// A suppression comment present in an analyzed file this run.
4256///
4257/// This is the "active-suppression state" the Fallow Impact value report needs
4258/// to tell a genuinely resolved finding (the code was fixed) from one merely
4259/// silenced by a newly-added `fallow-ignore`. It captures every PRESENT marker,
4260/// not only the ones a detector consumed: complexity and code-duplication
4261/// suppressions are consumed in the CLI layer rather than the core suppression
4262/// context, so presence is the single uniform signal that covers all impact
4263/// categories. A present-but-stale marker is harmless because impact keys on a
4264/// suppression that newly appeared between two recorded runs. It is internal:
4265/// never serialized into the public JSON output schema (the field on
4266/// [`AnalysisResults`] is `#[serde(skip)]`), only read in-process by
4267/// `fallow impact`.
4268#[derive(Debug, Clone)]
4269pub struct ActiveSuppression {
4270    /// Absolute path to the file carrying the suppression comment.
4271    pub path: PathBuf,
4272    /// The suppressed issue kind in kebab-case (e.g. `"unused-export"`), or
4273    /// `None` for a blanket marker that suppresses every kind on its target.
4274    pub kind: Option<String>,
4275    /// Whether this is a `fallow-ignore-file` (file-level) marker rather than a
4276    /// `fallow-ignore-next-line` marker.
4277    pub is_file_level: bool,
4278    /// Human-authored reason after `--`, when present.
4279    pub reason: Option<String>,
4280    /// 1-based line of the suppression comment itself; 0 only if unknown.
4281    pub comment_line: u32,
4282}
4283
4284/// The detection method used to identify a feature flag.
4285#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4286#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4287#[serde(rename_all = "snake_case")]
4288pub enum FlagKind {
4289    /// Environment variable check (e.g., `process.env.FEATURE_X`).
4290    EnvironmentVariable,
4291    /// Feature flag SDK call (e.g., `useFlag('name')`, `variation('name', false)`).
4292    SdkCall,
4293    /// Config object property access (e.g., `config.features.newCheckout`).
4294    ConfigObject,
4295}
4296
4297/// Detection confidence for a feature flag finding.
4298#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
4299#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4300#[serde(rename_all = "snake_case")]
4301pub enum FlagConfidence {
4302    /// Low confidence: heuristic match (config object patterns).
4303    Low,
4304    /// Medium confidence: a generic SDK name, such as `isEnabled`, in a file
4305    /// that imports no flag SDK or flag module.
4306    Medium,
4307    /// High confidence: unambiguous pattern (env vars, specific SDK calls,
4308    /// generic SDK calls in a file that imports a flag SDK or flag module).
4309    High,
4310}
4311
4312/// A detected feature flag use site.
4313#[derive(Debug, Clone, Serialize, Deserialize)]
4314#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4315pub struct FeatureFlag {
4316    /// File containing the feature flag usage.
4317    #[serde(serialize_with = "serde_path::serialize")]
4318    pub path: PathBuf,
4319    /// Name or identifier of the flag (e.g., `ENABLE_NEW_CHECKOUT`, `new-checkout`).
4320    pub flag_name: String,
4321    /// How the flag was detected.
4322    pub kind: FlagKind,
4323    /// Detection confidence level.
4324    pub confidence: FlagConfidence,
4325    /// 1-based line number.
4326    pub line: u32,
4327    /// 0-based byte column offset.
4328    pub col: u32,
4329    /// Start byte offset of the guarded code block (if-branch span), if detected.
4330    #[serde(skip)]
4331    pub guard_span_start: Option<u32>,
4332    /// End byte offset of the guarded code block (if-branch span), if detected.
4333    #[serde(skip)]
4334    pub guard_span_end: Option<u32>,
4335    /// SDK or provider name (e.g., "LaunchDarkly", "Statsig"), if detected from SDK call.
4336    #[serde(default, skip_serializing_if = "Option::is_none")]
4337    pub sdk_name: Option<String>,
4338    /// Line range of the guarded code block (derived from guard_span + line_offsets).
4339    /// Used for cross-reference with dead code findings.
4340    #[serde(skip)]
4341    pub guard_line_start: Option<u32>,
4342    /// End line of the guarded code block.
4343    #[serde(skip)]
4344    pub guard_line_end: Option<u32>,
4345    /// Unused exports found within the guarded code block.
4346    /// Populated by cross-reference with dead code analysis.
4347    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4348    pub guarded_dead_exports: Vec<String>,
4349}
4350
4351// Size assertion: FeatureFlag is stored in a Vec per analysis run.
4352const _: () = assert!(std::mem::size_of::<FeatureFlag>() <= 160);
4353
4354/// Usage count for an export symbol. Used by the LSP Code Lens to show
4355/// the number of importing files above each export declaration.
4356#[derive(Debug, Clone, Serialize, Deserialize)]
4357#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4358pub struct ExportUsage {
4359    /// File containing the export.
4360    #[serde(serialize_with = "serde_path::serialize")]
4361    pub path: PathBuf,
4362    /// Name of the exported symbol.
4363    pub export_name: String,
4364    /// 1-based line number.
4365    pub line: u32,
4366    /// 0-based byte column offset.
4367    pub col: u32,
4368    /// Number of distinct files that import this export. Two imports in one
4369    /// file count as one file.
4370    pub reference_count: usize,
4371    /// Import sites that reference this export, one entry per physical import.
4372    /// A file with two imports gives two entries, so this list can be longer
4373    /// than `reference_count`. An import without a source span has no entry.
4374    /// Used by the LSP Code Lens to enable click-to-navigate via
4375    /// `editor.action.showReferences`.
4376    pub reference_locations: Vec<ReferenceLocation>,
4377}
4378
4379/// A location where an export is referenced (import site in another file).
4380#[derive(Debug, Clone, Serialize, Deserialize)]
4381#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4382pub struct ReferenceLocation {
4383    /// File containing the import that references the export.
4384    #[serde(serialize_with = "serde_path::serialize")]
4385    pub path: PathBuf,
4386    /// 1-based line number.
4387    pub line: u32,
4388    /// 0-based byte column offset.
4389    pub col: u32,
4390}
4391
4392#[cfg(test)]
4393#[path = "results_tests.rs"]
4394mod tests;