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