Skip to main content

fallow_types/
output_dead_code.rs

1//! Typed envelope wrappers for the simple 1:1 dead-code findings whose
2//! actions are entirely determined by the wrapper type (no per-instance
3//! discriminants beyond what the bare finding already exposes).
4//!
5//! Each wrapper flattens the bare finding via `#[serde(flatten)]` so the
6//! wire shape matches the previous `actions`-grafted output byte-for-byte.
7//! `actions` is populated at construction time via each wrapper's
8//! `with_actions` constructor and replaces the per-finding `inject_actions`
9//! post-pass in `crates/cli/src/report/json.rs`. `introduced` carries the optional audit
10//! breadcrumb that `crates/cli/src/audit.rs::annotate_issue_array` inserts
11//! into the JSON object via `map.insert`; the wrapper-level field stays
12//! `None` when serialized directly from Rust and is set by the audit pass
13//! only when the issue was introduced relative to the merge-base.
14//!
15//! All nine wrappers ship with `IssueAction` arrays today; they pay the
16//! `serde_json` dependency cost because `IssueAction` transitively
17//! references `AddToConfigValue::RuleObject(serde_json::Map<...>)`. The
18//! variants the wrappers actually emit (`Fix`, `SuppressLine`,
19//! `SuppressFile`, `AddToConfig`) are small, but reusing the existing enum
20//! keeps the wire-shape contract identical to the legacy post-pass.
21//!
22//! `introduced` is typed as `Option<AuditIntroduced>` (transparent newtype
23//! over `bool`) so the regenerated schema renders the field via
24//! `$ref: #/definitions/AuditIntroduced`, matching the reference the prior
25//! post-pass augmentation graft used. The audit pass continues to inject a
26//! bare bool via `map.insert("introduced", ...)`; serde reads it back into
27//! `AuditIntroduced` transparently. The field stays absent at the wire when
28//! `None` (`skip_serializing_if`).
29
30use serde::{Deserialize, Serialize};
31
32use crate::catalog_source::is_pnpm_catalog_source;
33use crate::envelope::AuditIntroduced;
34use crate::output::{
35    AddToConfigAction, AddToConfigKind, AddToConfigValue, FixAction, FixActionType,
36    IgnoreExportsRule, IssueAction, SuppressFileAction, SuppressFileKind, SuppressLineAction,
37    SuppressLineKind, SuppressLineScope,
38};
39pub use crate::results::AbsentComponentPropFinding;
40use crate::results::{
41    BoundaryCallViolation, BoundaryCoverageViolation, BoundaryViolation, CircularDependency,
42    DependencyOverrideSource, DeprecatedExportInUse, DevDependencyInProduction, DuplicateExport,
43    DuplicateExportAlias, DuplicatePropShape, DynamicSegmentNameConflict, EmptyCatalogGroup,
44    InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
45    MixedClientServerBarrel, PackageCycle, PolicyViolation, PrivateTypeLeak, PropDrillingChain,
46    ReExportCycle, ReExportCycleKind, RouteCollision, TestOnlyDependency, ThinWrapper,
47    TypeOnlyDependency, UnlistedBinary, UnlistedDependency, UnproducedCatchTag, UnprovidedInject,
48    UnrenderedComponent, UnresolvedCatalogReference, UnresolvedImport, UnusedCatalogEntry,
49    UnusedComponentEmit, UnusedComponentInput, UnusedComponentOutput, UnusedComponentProp,
50    UnusedDependency, UnusedDependencyOverride, UnusedEffectLayer, UnusedExport, UnusedFile,
51    UnusedLoadDataKey, UnusedMember, UnusedServerAction, UnusedSvelteEvent, UnusedTaggedError,
52};
53use crate::semantic::{
54    SemanticCandidateDecision, SemanticCandidateDecisionKind, SemanticCompleteness,
55};
56
57/// Shared note for the `duplicate-exports` fix action. This const is the
58/// single source of truth: `crates/cli/src/report/shared.rs` aliases it for
59/// the human report.
60pub const NAMESPACE_BARREL_HINT: &str = "If every location is the sole `index.*` of its directory, this is likely an intentional namespace-barrel API. Prefer adding these files to `ignoreExports` over removing exports.";
61
62/// JSON Schema fragment URL for the `add-to-config` `ignoreExports` action's
63/// `value` payload. Pinned to the main branch so users browsing the action
64/// value can navigate directly to the rule shape.
65const IGNORE_EXPORTS_VALUE_SCHEMA: &str =
66    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreExports";
67
68/// JSON Schema fragment URL for the `ignoreCatalogReferences` rule items
69/// referenced by `add-to-config` actions on `unresolved-catalog-references`.
70const IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreCatalogReferences/items";
71
72/// JSON Schema fragment URL for the `ignoreDependencyOverrides` rule items
73/// referenced by `add-to-config` actions on both the unused- and
74/// misconfigured-override findings.
75const IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencyOverrides/items";
76
77pub(crate) fn manual_framework_fix(
78    kind: FixActionType,
79    description: &str,
80    note: &str,
81) -> IssueAction {
82    IssueAction::Fix(FixAction {
83        kind,
84        auto_fixable: false,
85        description: description.to_string(),
86        note: Some(note.to_string()),
87        available_in_catalogs: None,
88        suggested_target: None,
89    })
90}
91
92pub(crate) fn suppress_line(comment: &str) -> IssueAction {
93    IssueAction::SuppressLine(SuppressLineAction {
94        kind: SuppressLineKind::SuppressLine,
95        auto_fixable: false,
96        description: "Suppress with an inline comment above the line".to_string(),
97        comment: comment.to_string(),
98        scope: None,
99    })
100}
101
102/// A per-finding caveat on a dead-code verdict that a file this run never
103/// fully analyzed can distort.
104///
105/// Advisory provenance, in the same spirit as the fix path's
106/// `low_confidence_off_graph` / `low_confidence_unresolved_imports` skip
107/// reasons: a caveat never withholds, reorders, downgrades, or re-severities
108/// the finding, and never changes an exit code. It records that the verdict
109/// was computed over an import graph fallow already knows is incomplete, so a
110/// reader who sees the finding also sees the caveat instead of having to
111/// notice a diagnostic at the other end of the envelope.
112///
113/// Deliberately NOT named `confidence`: `health --targets` already emits a
114/// `confidence` key holding an enum string, and a shared consumer helper that
115/// met both would see the same key change type. Emitted on every finding type
116/// that registers it: the reachability arrays (`unused_files[]`,
117/// `unused_exports[]`, `unused_types[]`), the member arrays
118/// (`unused_enum_members[]`, `unused_class_members[]`, `unused_store_members[]`),
119/// and the three dependency arrays. Sorted and deduplicated, absent from the
120/// wire when empty. The set is open in the same sense
121/// `workspace_diagnostics[].kind` is: treat an unrecognised value as "some
122/// caveat" rather than as an error.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
125#[serde(rename_all = "kebab-case")]
126pub enum ReachabilityCaveat {
127    /// This finding's own file is one the run did not fully analyze, so the
128    /// export and import lists extracted from it may stop short of the real
129    /// ones. That reaches an `unused-file` verdict directly, because the
130    /// "is any export of this file referenced from a reachable module" test
131    /// reads exactly that truncated export list.
132    ///
133    /// Three workspace diagnostics put a file in this state: a partial parse
134    /// (`source-parse-degraded`), no parse (`source-nesting-too-deep`), or no
135    /// read (`source-read-failure`). The token names the consequence rather than
136    /// either cause, so a future kind that leaves a discovered file partially
137    /// extracted carries the same value.
138    ///
139    /// Dependency findings never carry this value: the file they name is a
140    /// `package.json`, not a parsed source module.
141    IncompleteFileAnalysis,
142    /// A module whose import list feeds this verdict was not analyzed, so the
143    /// import that would have credited this finding may never have been seen.
144    ///
145    /// The cause is any workspace diagnostic that leaves a source file's
146    /// imports unseen: a partial parse (`source-parse-degraded`), no parse
147    /// (`source-nesting-too-deep`), no read (`source-read-failure`), or a skip
148    /// by discovery before the read (`skipped-large-file`,
149    /// `skipped-minified-file`, `skipped-source-dotdir`). The token names the
150    /// class rather than any one cause.
151    ///
152    /// Which modules feed the verdict differs by array, and the caveat is
153    /// emitted only when a degraded module is actually one of them:
154    ///
155    /// - `unused_files[]`, `unused_exports[]`, and `unused_types[]` rest on
156    ///   reachability, so only a degraded module that is itself observed
157    ///   reachable can change the verdict. When every degraded module is
158    ///   unreachable the caveat is absent, and soundly: the first missing edge
159    ///   on any entry-point path leaves from a module whose every predecessor
160    ///   edge was observed, so that module is observed reachable. A file the
161    ///   run never read has no module and no graph node, so its reachability
162    ///   is not observable at all and that narrowing cannot be applied: any
163    ///   skipped or unreadable source caveats every reachability verdict in
164    ///   the run.
165    /// - the member arrays (`unused_enum_members[]`, `unused_class_members[]`,
166    ///   `unused_store_members[]`) do not rest on reachability at all: member
167    ///   usage is collected by walking every module the run resolved,
168    ///   reachable or not, so this narrowing does not apply to them either.
169    ///   Same unnarrowed condition as the dependency arrays below, plus the
170    ///   per-finding value above when the member's own file is the one that
171    ///   was incompletely analyzed.
172    /// - the dependency arrays rest on whether ANY module in the project
173    ///   imports the package specifier, reachable or not, so any degraded
174    ///   parse anywhere can hide the import that would have credited the
175    ///   package. Reachability does not narrow that one.
176    ///
177    /// The limit, stated because an approximation presented as exact is worse
178    /// than nothing: this is a RUN-level condition, not proof that a degraded
179    /// module imports this path or package. An import the parser never saw
180    /// cannot be attributed to a target, so the link cannot be narrowed
181    /// further without re-reading the source. Read `workspace_diagnostics[]`
182    /// for which files degraded.
183    IncompleteImportGraph,
184}
185
186impl ReachabilityCaveat {
187    /// The wire token.
188    #[must_use]
189    pub const fn token(self) -> &'static str {
190        match self {
191            Self::IncompleteFileAnalysis => "incomplete-file-analysis",
192            Self::IncompleteImportGraph => "incomplete-import-graph",
193        }
194    }
195
196    /// A one-line explanation for human and agent-facing renderers.
197    ///
198    /// Neither sentence names a single cause. A degraded parse is only one of
199    /// the ways a file goes unread: it may also have been unreadable, or
200    /// skipped before it was ever opened (oversized, minified, in a dotdir).
201    /// Naming the parse case alone sent a reader whose run was degraded by the
202    /// size guard hunting for parse errors that do not exist, so both messages
203    /// point at `workspace_diagnostics[]`, which names the actual files.
204    #[must_use]
205    pub const fn message(self) -> &'static str {
206        match self {
207            Self::IncompleteFileAnalysis => {
208                "low: this file was not fully analyzed, so its extracted exports and imports may be incomplete; see workspace_diagnostics[]"
209            }
210            Self::IncompleteImportGraph => {
211                "low: a module this run did not fully read may hold an import that would credit this; see workspace_diagnostics[]"
212            }
213        }
214    }
215
216    /// A compact label for a one-line human renderer, where the full
217    /// [`Self::message`] would not fit next to the finding.
218    #[must_use]
219    pub const fn short_label(self) -> &'static str {
220        match self {
221            Self::IncompleteFileAnalysis => "incomplete file analysis",
222            Self::IncompleteImportGraph => "incomplete import graph",
223        }
224    }
225}
226
227/// The compact labels of `caveats`, joined for a one-line renderer, or `None`
228/// when there is nothing to say.
229#[must_use]
230pub fn caveat_labels(caveats: &[ReachabilityCaveat]) -> Option<String> {
231    if caveats.is_empty() {
232        return None;
233    }
234    let labels: Vec<&str> = caveats
235        .iter()
236        .map(|caveat| ReachabilityCaveat::short_label(*caveat))
237        .collect();
238    Some(labels.join(", "))
239}
240
241/// The compact parenthetical a one-line human renderer appends to a finding
242/// carrying `caveats`, or `None` when there is nothing to say. Shared by every
243/// dead-code section so the suffix reads the same everywhere.
244#[must_use]
245pub fn caveat_suffix(caveats: &[ReachabilityCaveat]) -> Option<String> {
246    caveat_labels(caveats).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
247}
248
249/// The opening of the parenthetical [`caveat_suffix`] renders. Public because
250/// one consumer can only see the rendered description: the CI review formats
251/// build their comments from CodeClimate issues, whose `description` is the
252/// only place the caveat survives (the CodeClimate wire is a published
253/// contract with no field for it). Recognising the marker is what lets those
254/// formats withhold a one-click mutation.
255pub const CAVEAT_SUFFIX_MARKER: &str = " (caveat: ";
256
257/// Whether a rendered finding description already carries a caveat
258/// parenthetical, for a surface holding the string rather than the typed
259/// finding.
260///
261/// Lives here, next to the renderer, so the producer and the recogniser cannot
262/// drift; `a_rendered_suffix_is_recognised_by_the_marker` pins the pair.
263#[must_use]
264pub fn description_carries_caveat(description: &str) -> bool {
265    description.contains(CAVEAT_SUFFIX_MARKER)
266}
267
268/// The compact label for one wire token, for a renderer that reads
269/// `reachability_caveats[]` back off a serialized envelope instead of holding
270/// the typed findings.
271///
272/// The value set is OPEN, exactly as the wire documentation says: a token this
273/// build does not recognise is still a caveat, so it is rendered as itself with
274/// its separators relaxed into spaces rather than dropped. Dropping it would
275/// turn a finding whose evidence is incomplete back into a confident one,
276/// which is the failure this whole mechanism exists to prevent.
277#[must_use]
278pub fn caveat_label_for_token(token: &str) -> String {
279    match token {
280        "incomplete-file-analysis" => {
281            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteFileAnalysis).to_owned()
282        }
283        "incomplete-import-graph" => {
284            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteImportGraph).to_owned()
285        }
286        other => other.replace('-', " "),
287    }
288}
289
290/// The joined compact labels for wire tokens, or `None` when there are none.
291/// The token-side twin of [`caveat_labels`], for renderers driven by a
292/// serialized envelope rather than by typed findings.
293#[must_use]
294pub fn caveat_labels_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
295    let labels: Vec<String> = tokens.into_iter().map(caveat_label_for_token).collect();
296    if labels.is_empty() {
297        return None;
298    }
299    Some(labels.join(", "))
300}
301
302/// The token-side twin of [`caveat_suffix`], so an envelope-driven renderer
303/// appends the same parenthetical as a findings-driven one.
304#[must_use]
305pub fn caveat_suffix_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
306    caveat_labels_for_tokens(tokens).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
307}
308
309/// The note every mutating action carries once [`MutationEvidence`] withholds
310/// it. One string, so the CLI action array, the LSP diagnostic, and the MCP
311/// tool contract all say the same thing about the same finding.
312pub const INCOMPLETE_EVIDENCE_NOTE: &str = "Evidence is incomplete: a file this run did not fully analyze may hold the reference that \
313     credits this finding, so this mutation is not applied automatically. Resolve the files named \
314     in workspace_diagnostics[] and re-run, or confirm and remove it by hand.";
315
316/// The one question every mutation surface asks before it offers, plans, or
317/// performs a dead-code finding's removal.
318///
319/// A finding whose reachability verdict rests on a file the run never fully
320/// read is still REPORTED, always: a caveat withholds no finding, changes no
321/// severity, and moves no exit code. What it withholds is the automation. The
322/// predicate lives here, next to the findings, rather than in any one consumer,
323/// because it was re-derived per surface three times and a fourth door opened
324/// every time: `fallow fix`, the LSP quick fix, and the `auto_fixable` flag an
325/// agent plans against each answered it differently. Every one of those now
326/// calls [`Self::may_auto_apply_mutation`], so a sixth finding type or a fourth
327/// mutation surface cannot silently opt out.
328///
329/// Implemented only by the findings that can carry a caveat. A finding type
330/// that exposes an auto-fixable mutation and does NOT implement this trait is
331/// the bug this trait exists to make visible; `every_auto_fixable_dead_code_
332/// mutation_is_gated` in this module's tests pins that.
333pub trait MutationEvidence {
334    /// The advisory caveats recorded on the reachability verdict behind this
335    /// finding. Empty when the run analyzed every file it discovered.
336    fn reachability_caveats(&self) -> &[ReachabilityCaveat];
337
338    /// Whether this finding's mutation may be applied without a human first
339    /// being told the evidence is incomplete. THE gate: never re-derive it,
340    /// never widen it per surface.
341    fn may_auto_apply_mutation(&self) -> bool {
342        self.reachability_caveats().is_empty()
343    }
344}
345
346/// Record a run's caveats on a finding, enforcing [`MutationEvidence`] on its
347/// typed `actions` in the same step.
348///
349/// Separate from [`MutationEvidence`] so a read-only consumer (the fixer, the
350/// LSP, a renderer) depends only on the question and never on the answer's
351/// setter. `annotate` in the analysis layer is the single writer.
352pub trait CaveatedFinding: MutationEvidence {
353    /// Store `caveats` and downgrade every mutating action the gate now
354    /// withholds. The field itself stays `pub` (a renderer test builds an
355    /// already-caveated fixture directly, without running the annotation
356    /// pass); every non-test writer goes through this setter instead of the
357    /// field so the downgrade travels with the write.
358    fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>);
359}
360
361/// Downgrade every `Fix` action in `actions` when `caveats` is non-empty, so
362/// the `auto_fixable` flag an agent plans against matches what `fallow fix`
363/// will actually do. Only ever downgrades: a surface that has already decided
364/// a mutation is unsafe for its own reasons keeps that decision.
365fn withhold_caveated_mutations(actions: &mut [IssueAction], caveats: &[ReachabilityCaveat]) {
366    if caveats.is_empty() {
367        return;
368    }
369    for action in actions {
370        let IssueAction::Fix(fix) = action else {
371            continue;
372        };
373        fix.auto_fixable = false;
374        fix.note = Some(match fix.note.take() {
375            Some(existing) => format!("{existing}. {INCOMPLETE_EVIDENCE_NOTE}"),
376            None => INCOMPLETE_EVIDENCE_NOTE.to_string(),
377        });
378    }
379}
380
381/// Implement the gate for a finding wrapper carrying a `reachability_caveats`
382/// field alongside a typed `actions` array. A new caveated finding type adds
383/// one line here rather than a new per-surface branch.
384macro_rules! impl_caveated_finding {
385    ($($finding:ty),+ $(,)?) => {
386        $(
387            impl MutationEvidence for $finding {
388                fn reachability_caveats(&self) -> &[ReachabilityCaveat] {
389                    &self.reachability_caveats
390                }
391            }
392
393            impl CaveatedFinding for $finding {
394                fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>) {
395                    withhold_caveated_mutations(&mut self.actions, &caveats);
396                    self.reachability_caveats = caveats;
397                }
398            }
399        )+
400    };
401}
402
403/// Wire-shape envelope for an [`UnusedFile`] finding. The bare finding
404/// flattens in via `#[serde(flatten)]`, with a typed `actions` array
405/// populated at construction time and the audit-pass `introduced` flag
406/// attached as an optional sibling.
407#[derive(Debug, Clone, Serialize, Deserialize)]
408#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
409pub struct UnusedFileFinding {
410    /// The underlying dead-code entry.
411    #[serde(flatten)]
412    pub file: UnusedFile,
413    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
414    /// `~<k>` suffix when several findings of one type share an identity.
415    /// Line and column are not inputs, so the id survives line shifts,
416    /// reformats and reorders. A rename of the file or the symbol gives a
417    /// new id. Absent in output from older versions.
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub finding_id: Option<String>,
420    /// Suggested next steps: a `delete-file` primary and a `suppress-file`
421    /// secondary. Always emitted (possibly empty for forward-compat).
422    pub actions: Vec<IssueAction>,
423    /// Set by the audit pass when this finding is introduced relative to
424    /// the merge-base. `None` when serialized directly from Rust.
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub introduced: Option<AuditIntroduced>,
427    /// Gate severity of this finding after `rules` and `overrides[].rules`
428    /// resolve for its path. CI formats read it for the annotation, SARIF
429    /// and CodeClimate level. Absent in output from older versions. Not
430    /// part of the finding identity, baseline keys or fingerprints.
431    #[serde(
432        default,
433        skip_serializing_if = "Option::is_none",
434        deserialize_with = "deserialize_effective_severity"
435    )]
436    pub effective_severity: Option<EffectiveSeverity>,
437    /// Advisory caveats on the reachability verdict behind this finding.
438    /// Sorted, deduplicated, and omitted from the wire when empty, so a run
439    /// that analyzed every discovered file is byte-identical. Never gates the
440    /// finding or the `delete-file` action, though `fallow fix` does withhold
441    /// the removal of a caveated finding as low confidence.
442    #[serde(default, skip_serializing_if = "Vec::is_empty")]
443    pub reachability_caveats: Vec<ReachabilityCaveat>,
444}
445
446impl UnusedFileFinding {
447    /// Build the wrapper from a raw [`UnusedFile`], computing the typed
448    /// `actions` array inline. `introduced` stays `None` and is set later
449    /// by `annotate_dead_code_json` if the audit pass runs.
450    #[must_use]
451    pub fn with_actions(file: UnusedFile) -> Self {
452        let actions = vec![
453            IssueAction::Fix(FixAction {
454                kind: FixActionType::DeleteFile,
455                auto_fixable: false,
456                description: "Delete this file".to_string(),
457                note: Some(
458                    "File deletion may remove runtime functionality not visible to static analysis"
459                        .to_string(),
460                ),
461                available_in_catalogs: None,
462                suggested_target: None,
463            }),
464            IssueAction::SuppressFile(SuppressFileAction {
465                kind: SuppressFileKind::SuppressFile,
466                auto_fixable: false,
467                description: "Suppress with a file-level comment at the top of the file"
468                    .to_string(),
469                comment: "// fallow-ignore-file unused-file".to_string(),
470            }),
471        ];
472        Self {
473            finding_id: None,
474            file,
475            actions,
476            introduced: None,
477            effective_severity: None,
478            reachability_caveats: Vec::new(),
479        }
480    }
481}
482
483/// Wire-shape envelope for a [`PrivateTypeLeak`] finding. Mirrors
484/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
485/// `actions` array (`export-type` primary plus `suppress-line` secondary).
486#[derive(Debug, Clone, Serialize, Deserialize)]
487#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
488pub struct PrivateTypeLeakFinding {
489    /// The underlying dead-code entry.
490    #[serde(flatten)]
491    pub leak: PrivateTypeLeak,
492    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
493    /// `~<k>` suffix when several findings of one type share an identity.
494    /// Line and column are not inputs, so the id survives line shifts,
495    /// reformats and reorders. A rename of the file or the symbol gives a
496    /// new id. Absent in output from older versions.
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub finding_id: Option<String>,
499    /// Suggested next steps. Always emitted (possibly empty for
500    /// forward-compat).
501    pub actions: Vec<IssueAction>,
502    /// Set by the audit pass when this finding is introduced relative to
503    /// the merge-base.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub introduced: Option<AuditIntroduced>,
506    /// Gate severity of this finding after `rules` and `overrides[].rules`
507    /// resolve for its path. CI formats read it for the annotation, SARIF
508    /// and CodeClimate level. Absent in output from older versions. Not
509    /// part of the finding identity, baseline keys or fingerprints.
510    #[serde(
511        default,
512        skip_serializing_if = "Option::is_none",
513        deserialize_with = "deserialize_effective_severity"
514    )]
515    pub effective_severity: Option<EffectiveSeverity>,
516}
517
518impl PrivateTypeLeakFinding {
519    /// Build the wrapper from a raw [`PrivateTypeLeak`].
520    #[must_use]
521    pub fn with_actions(leak: PrivateTypeLeak) -> Self {
522        let actions = vec![
523            IssueAction::Fix(FixAction {
524                kind: FixActionType::ExportType,
525                auto_fixable: false,
526                description: "Export the referenced private type by name".to_string(),
527                note: Some(
528                    "Keep the type exported while it is part of a public signature".to_string(),
529                ),
530                available_in_catalogs: None,
531                suggested_target: None,
532            }),
533            IssueAction::SuppressLine(SuppressLineAction {
534                kind: SuppressLineKind::SuppressLine,
535                auto_fixable: false,
536                description: "Suppress with an inline comment above the line".to_string(),
537                comment: "// fallow-ignore-next-line private-type-leak".to_string(),
538                scope: None,
539            }),
540        ];
541        Self {
542            finding_id: None,
543            leak,
544            actions,
545            introduced: None,
546            effective_severity: None,
547        }
548    }
549}
550
551/// Wire-shape envelope for a [`DeprecatedExportInUse`] finding. Carries a
552/// manual `migrate-deprecated-export` primary action plus a `suppress-line`
553/// secondary. Never auto-fixable: fallow does not rewrite consumers.
554#[derive(Debug, Clone, Serialize, Deserialize)]
555#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
556pub struct DeprecatedExportInUseFinding {
557    /// The underlying dead-code entry.
558    #[serde(flatten)]
559    pub export: DeprecatedExportInUse,
560    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
561    /// `~<k>` suffix when several findings of one type share an identity.
562    /// Line and column are not inputs, so the id survives line shifts,
563    /// reformats and reorders. A rename of the file or the symbol gives a
564    /// new id. Absent in output from older versions.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub finding_id: Option<String>,
567    /// Suggested next steps. Always emitted (possibly empty for
568    /// forward-compat).
569    pub actions: Vec<IssueAction>,
570    /// Set by the audit pass when this finding is introduced relative to
571    /// the merge-base.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub introduced: Option<AuditIntroduced>,
574    /// Gate severity of this finding after `rules` and `overrides[].rules`
575    /// resolve for its path. CI formats read it for the annotation, SARIF
576    /// and CodeClimate level. Absent in output from older versions. Not
577    /// part of the finding identity, baseline keys or fingerprints.
578    #[serde(
579        default,
580        skip_serializing_if = "Option::is_none",
581        deserialize_with = "deserialize_effective_severity"
582    )]
583    pub effective_severity: Option<EffectiveSeverity>,
584}
585
586impl DeprecatedExportInUseFinding {
587    /// Build the wrapper from a raw [`DeprecatedExportInUse`].
588    #[must_use]
589    pub fn with_actions(export: DeprecatedExportInUse) -> Self {
590        let trace_hint = format!(
591            "For the full consumer list, run `fallow dead-code --trace <path>:{}` with the `path` of this finding.",
592            export.export_name
593        );
594        let note = if export.public_api {
595            format!(
596                "This export is public API. External consumers are not visible, so do not remove it on this evidence alone. {trace_hint}"
597            )
598        } else {
599            format!(
600                "Move each consumer to the replacement that the deprecation message names, then remove the export. {trace_hint}"
601            )
602        };
603        let actions = vec![
604            IssueAction::Fix(FixAction {
605                kind: FixActionType::MigrateDeprecatedExport,
606                auto_fixable: false,
607                description: "Move the consumers off the deprecated export".to_string(),
608                note: Some(note),
609                available_in_catalogs: None,
610                suggested_target: None,
611            }),
612            suppress_line("// fallow-ignore-next-line deprecated-export-in-use"),
613        ];
614        Self {
615            finding_id: None,
616            export,
617            actions,
618            introduced: None,
619            effective_severity: None,
620        }
621    }
622}
623
624/// Wire-shape envelope for an [`UnresolvedImport`] finding. Mirrors
625/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
626/// `actions` array (`resolve-import` primary plus config and inline
627/// suppression actions).
628#[derive(Debug, Clone, Serialize, Deserialize)]
629#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
630pub struct UnresolvedImportFinding {
631    /// The underlying dead-code entry.
632    #[serde(flatten)]
633    pub import: UnresolvedImport,
634    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
635    /// `~<k>` suffix when several findings of one type share an identity.
636    /// Line and column are not inputs, so the id survives line shifts,
637    /// reformats and reorders. A rename of the file or the symbol gives a
638    /// new id. Absent in output from older versions.
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub finding_id: Option<String>,
641    /// Suggested next steps. Always emitted (possibly empty for
642    /// forward-compat).
643    pub actions: Vec<IssueAction>,
644    /// Set by the audit pass when this finding is introduced relative to
645    /// the merge-base.
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub introduced: Option<AuditIntroduced>,
648    /// Gate severity of this finding after `rules` and `overrides[].rules`
649    /// resolve for its path. CI formats read it for the annotation, SARIF
650    /// and CodeClimate level. Absent in output from older versions. Not
651    /// part of the finding identity, baseline keys or fingerprints.
652    #[serde(
653        default,
654        skip_serializing_if = "Option::is_none",
655        deserialize_with = "deserialize_effective_severity"
656    )]
657    pub effective_severity: Option<EffectiveSeverity>,
658}
659
660impl UnresolvedImportFinding {
661    /// Build the wrapper from a raw [`UnresolvedImport`].
662    #[must_use]
663    pub fn with_actions(import: UnresolvedImport) -> Self {
664        let actions = vec![
665            IssueAction::Fix(FixAction {
666                kind: FixActionType::ResolveImport,
667                auto_fixable: false,
668                description: "Fix the import specifier or install the missing module".to_string(),
669                note: Some(
670                    "Verify the module path and check tsconfig paths configuration".to_string(),
671                ),
672                available_in_catalogs: None,
673                suggested_target: None,
674            }),
675            IssueAction::AddToConfig(AddToConfigAction {
676                kind: AddToConfigKind::AddToConfig,
677                auto_fixable: false,
678                description: format!(
679                    "Add \"{}\" to ignoreUnresolvedImports in fallow config",
680                    import.specifier
681                ),
682                config_key: "ignoreUnresolvedImports".to_string(),
683                value: AddToConfigValue::Scalar(import.specifier.clone()),
684                value_schema: Some(
685                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreUnresolvedImports/items"
686                        .to_string(),
687                ),
688            }),
689            IssueAction::SuppressLine(SuppressLineAction {
690                kind: SuppressLineKind::SuppressLine,
691                auto_fixable: false,
692                description: "Suppress with an inline comment above the line".to_string(),
693                comment: "// fallow-ignore-next-line unresolved-import".to_string(),
694                scope: None,
695            }),
696        ];
697        Self {
698            finding_id: None,
699            import,
700            actions,
701            introduced: None,
702            effective_severity: None,
703        }
704    }
705}
706
707/// Wire-shape envelope for a [`CircularDependency`] finding. Mirrors
708/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
709/// `actions` array (`refactor-cycle` primary plus `suppress-line`
710/// secondary).
711#[derive(Debug, Clone, Serialize, Deserialize)]
712#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
713pub struct CircularDependencyFinding {
714    /// The underlying dead-code entry.
715    #[serde(flatten)]
716    pub cycle: CircularDependency,
717    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
718    /// `~<k>` suffix when several findings of one type share an identity.
719    /// Line and column are not inputs, so the id survives line shifts,
720    /// reformats and reorders. A rename of the file or the symbol gives a
721    /// new id. Absent in output from older versions.
722    #[serde(default, skip_serializing_if = "Option::is_none")]
723    pub finding_id: Option<String>,
724    /// Suggested next steps. Always emitted (possibly empty for
725    /// forward-compat).
726    pub actions: Vec<IssueAction>,
727    /// Set by the audit pass when this finding is introduced relative to
728    /// the merge-base.
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub introduced: Option<AuditIntroduced>,
731    /// Gate severity of this finding after `rules` and `overrides[].rules`
732    /// resolve for its path. CI formats read it for the annotation, SARIF
733    /// and CodeClimate level. Absent in output from older versions. Not
734    /// part of the finding identity, baseline keys or fingerprints.
735    #[serde(
736        default,
737        skip_serializing_if = "Option::is_none",
738        deserialize_with = "deserialize_effective_severity"
739    )]
740    pub effective_severity: Option<EffectiveSeverity>,
741}
742
743impl CircularDependencyFinding {
744    /// Build the wrapper from a raw [`CircularDependency`].
745    #[must_use]
746    pub fn with_actions(cycle: CircularDependency) -> Self {
747        let actions = vec![
748            IssueAction::Fix(FixAction {
749                kind: FixActionType::RefactorCycle,
750                auto_fixable: false,
751                description: "Extract shared logic into a separate module to break the cycle"
752                    .to_string(),
753                note: Some(
754                    "Circular imports can cause initialization issues and make code harder to reason about"
755                        .to_string(),
756                ),
757                available_in_catalogs: None,
758                suggested_target: None,
759            }),
760            IssueAction::SuppressLine(SuppressLineAction {
761                kind: SuppressLineKind::SuppressLine,
762                auto_fixable: false,
763                description: "Suppress with an inline comment above the line".to_string(),
764                comment: "// fallow-ignore-next-line circular-dependency".to_string(),
765                scope: None,
766            }),
767        ];
768        Self {
769            finding_id: None,
770            cycle,
771            actions,
772            introduced: None,
773            effective_severity: None,
774        }
775    }
776}
777
778/// Wire-shape envelope for a [`ReExportCycle`] finding. Mirrors
779/// [`CircularDependencyFinding`]: flattens the bare finding and carries a
780/// typed `actions` array (`refactor-re-export-cycle` informational primary
781/// plus `suppress-file` secondary; cycles are file-scoped so a single
782/// file-level suppression on the alphabetically-first member breaks the
783/// cycle, and no `// fallow-ignore-next-line` form makes sense because the
784/// diagnostic is anchored at line 1 col 0 of each member).
785#[derive(Debug, Clone, Serialize, Deserialize)]
786#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
787pub struct ReExportCycleFinding {
788    /// The underlying dead-code entry.
789    #[serde(flatten)]
790    pub cycle: ReExportCycle,
791    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
792    /// `~<k>` suffix when several findings of one type share an identity.
793    /// Line and column are not inputs, so the id survives line shifts,
794    /// reformats and reorders. A rename of the file or the symbol gives a
795    /// new id. Absent in output from older versions.
796    #[serde(default, skip_serializing_if = "Option::is_none")]
797    pub finding_id: Option<String>,
798    /// Suggested next steps. Always emitted (possibly empty for
799    /// forward-compat).
800    pub actions: Vec<IssueAction>,
801    /// Set by the audit pass when this finding is introduced relative to
802    /// the merge-base.
803    #[serde(default, skip_serializing_if = "Option::is_none")]
804    pub introduced: Option<AuditIntroduced>,
805    /// Gate severity of this finding after `rules` and `overrides[].rules`
806    /// resolve for its path. CI formats read it for the annotation, SARIF
807    /// and CodeClimate level. Absent in output from older versions. Not
808    /// part of the finding identity, baseline keys or fingerprints.
809    #[serde(
810        default,
811        skip_serializing_if = "Option::is_none",
812        deserialize_with = "deserialize_effective_severity"
813    )]
814    pub effective_severity: Option<EffectiveSeverity>,
815}
816
817impl ReExportCycleFinding {
818    /// Build the wrapper from a raw [`ReExportCycle`].
819    ///
820    /// The `SuppressFile` action targets the alphabetically-first member
821    /// (`cycle.files[0]`; the `files` Vec is already sorted at graph layer);
822    /// for multi-node cycles the description names the other members so
823    /// consumers see context for why one file-level suppression suffices.
824    #[must_use]
825    pub fn with_actions(cycle: ReExportCycle) -> Self {
826        // The description is a path-free hint about the suppression's
827        // structural effect; the cycle's member list already ships in the
828        // sibling `files` field, so consumers can correlate without
829        // re-reading the description (and absolute paths cannot leak in
830        // here, which the wrapper has no root-prefix context to strip).
831        let suppress_description = match cycle.kind {
832            ReExportCycleKind::SelfLoop => {
833                "Suppress with a file-level comment at the top of this file. \
834                 The cycle is a self-loop, so the suppression covers the entire finding."
835                    .to_string()
836            }
837            ReExportCycleKind::MultiNode => {
838                "Suppress with a file-level comment at the top of this file. \
839                 One suppression on any member breaks the cycle for every member \
840                 (see the sibling `files` array)."
841                    .to_string()
842            }
843        };
844        let actions = vec![
845            IssueAction::Fix(FixAction {
846                kind: FixActionType::RefactorReExportCycle,
847                auto_fixable: false,
848                description: "Remove one `export * from` (or `export { ... } from`) \
849                              statement on any one member to break the cycle"
850                    .to_string(),
851                note: Some(
852                    "Re-export cycles are structurally a no-op: chain propagation through \
853                     the loop never reaches a terminating module, so imports from any member \
854                     may silently come up empty."
855                        .to_string(),
856                ),
857                available_in_catalogs: None,
858                suggested_target: None,
859            }),
860            IssueAction::SuppressFile(SuppressFileAction {
861                kind: SuppressFileKind::SuppressFile,
862                auto_fixable: false,
863                description: suppress_description,
864                comment: "// fallow-ignore-file re-export-cycle".to_string(),
865            }),
866        ];
867        Self {
868            finding_id: None,
869            cycle,
870            actions,
871            introduced: None,
872            effective_severity: None,
873        }
874    }
875}
876
877/// Wire-shape envelope for a [`PackageCycle`] finding. Mirrors
878/// [`CircularDependencyFinding`]: flattens the bare finding and carries a
879/// typed `actions` array (`refactor-cycle` primary plus `suppress-line`
880/// secondary).
881#[derive(Debug, Clone, Serialize, Deserialize)]
882#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
883pub struct PackageCycleFinding {
884    /// The underlying dead-code entry.
885    #[serde(flatten)]
886    pub cycle: PackageCycle,
887    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
888    /// `~<k>` suffix when several findings of one type share an identity.
889    /// Line and column are not inputs, so the id survives line shifts,
890    /// reformats and reorders. A rename of the file or the symbol gives a
891    /// new id. Absent in output from older versions.
892    #[serde(default, skip_serializing_if = "Option::is_none")]
893    pub finding_id: Option<String>,
894    /// Suggested next steps. Always emitted (possibly empty for
895    /// forward-compat).
896    pub actions: Vec<IssueAction>,
897    /// Set by the audit pass when this finding is introduced relative to
898    /// the merge-base.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub introduced: Option<AuditIntroduced>,
901    /// Gate severity of this finding after `rules` and `overrides[].rules`
902    /// resolve for its path. CI formats read it for the annotation, SARIF
903    /// and CodeClimate level. Absent in output from older versions. Not
904    /// part of the finding identity, baseline keys or fingerprints.
905    #[serde(
906        default,
907        skip_serializing_if = "Option::is_none",
908        deserialize_with = "deserialize_effective_severity"
909    )]
910    pub effective_severity: Option<EffectiveSeverity>,
911}
912
913impl PackageCycleFinding {
914    /// Build the wrapper from a raw [`PackageCycle`].
915    #[must_use]
916    pub fn with_actions(cycle: PackageCycle) -> Self {
917        let actions = vec![
918            IssueAction::Fix(FixAction {
919                kind: FixActionType::RefactorCycle,
920                auto_fixable: false,
921                description: "Remove the imports on one hop of the cycle, for example by \
922                              moving the shared code to a package that both packages import"
923                    .to_string(),
924                note: Some(
925                    "Packages that import each other cannot be built in dependency order"
926                        .to_string(),
927                ),
928                available_in_catalogs: None,
929                suggested_target: None,
930            }),
931            IssueAction::SuppressLine(SuppressLineAction {
932                kind: SuppressLineKind::SuppressLine,
933                auto_fixable: false,
934                description: "Suppress with an inline comment above the import. The cycle \
935                              is gone when every import on one hop is suppressed"
936                    .to_string(),
937                comment: "// fallow-ignore-next-line package-cycle".to_string(),
938                scope: None,
939            }),
940        ];
941        Self {
942            cycle,
943            finding_id: None,
944            actions,
945            introduced: None,
946            effective_severity: None,
947        }
948    }
949}
950
951/// Wire-shape envelope for a [`BoundaryViolation`] finding. Mirrors
952/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
953/// `actions` array (`refactor-boundary` primary plus `suppress-line`
954/// secondary).
955#[derive(Debug, Clone, Serialize, Deserialize)]
956#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
957pub struct BoundaryViolationFinding {
958    /// The underlying dead-code entry.
959    #[serde(flatten)]
960    pub violation: BoundaryViolation,
961    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
962    /// `~<k>` suffix when several findings of one type share an identity.
963    /// Line and column are not inputs, so the id survives line shifts,
964    /// reformats and reorders. A rename of the file or the symbol gives a
965    /// new id. Absent in output from older versions.
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub finding_id: Option<String>,
968    /// Suggested next steps. Always emitted (possibly empty for
969    /// forward-compat).
970    pub actions: Vec<IssueAction>,
971    /// Set by the audit pass when this finding is introduced relative to
972    /// the merge-base.
973    #[serde(default, skip_serializing_if = "Option::is_none")]
974    pub introduced: Option<AuditIntroduced>,
975    /// Gate severity of this finding after `rules` and `overrides[].rules`
976    /// resolve for its path. CI formats read it for the annotation, SARIF
977    /// and CodeClimate level. Absent in output from older versions. Not
978    /// part of the finding identity, baseline keys or fingerprints.
979    #[serde(
980        default,
981        skip_serializing_if = "Option::is_none",
982        deserialize_with = "deserialize_effective_severity"
983    )]
984    pub effective_severity: Option<EffectiveSeverity>,
985}
986
987impl BoundaryViolationFinding {
988    /// Build the wrapper from a raw [`BoundaryViolation`].
989    #[must_use]
990    pub fn with_actions(violation: BoundaryViolation) -> Self {
991        let (description, note) = violation.refactor_action_text();
992        let actions = vec![
993            IssueAction::Fix(FixAction {
994                kind: FixActionType::RefactorBoundary,
995                auto_fixable: false,
996                description: description.to_string(),
997                note: Some(note.to_string()),
998                available_in_catalogs: None,
999                suggested_target: None,
1000            }),
1001            IssueAction::SuppressLine(SuppressLineAction {
1002                kind: SuppressLineKind::SuppressLine,
1003                auto_fixable: false,
1004                description: "Suppress with an inline comment above the line".to_string(),
1005                comment: "// fallow-ignore-next-line boundary-violation".to_string(),
1006                scope: None,
1007            }),
1008        ];
1009        Self {
1010            finding_id: None,
1011            violation,
1012            actions,
1013            introduced: None,
1014            effective_severity: None,
1015        }
1016    }
1017}
1018
1019/// Wire-shape envelope for a [`BoundaryCoverageViolation`] finding. Carries
1020/// actions for assigning the file to a zone or explicitly allowing it to stay
1021/// unmatched.
1022#[derive(Debug, Clone, Serialize, Deserialize)]
1023#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1024pub struct BoundaryCoverageViolationFinding {
1025    /// The underlying coverage entry.
1026    #[serde(flatten)]
1027    pub violation: BoundaryCoverageViolation,
1028    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1029    /// `~<k>` suffix when several findings of one type share an identity.
1030    /// Line and column are not inputs, so the id survives line shifts,
1031    /// reformats and reorders. A rename of the file or the symbol gives a
1032    /// new id. Absent in output from older versions.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub finding_id: Option<String>,
1035    /// Suggested next steps.
1036    pub actions: Vec<IssueAction>,
1037    /// Set by the audit pass when this finding is introduced relative to
1038    /// the merge-base.
1039    #[serde(default, skip_serializing_if = "Option::is_none")]
1040    pub introduced: Option<AuditIntroduced>,
1041    /// Gate severity of this finding after `rules` and `overrides[].rules`
1042    /// resolve for its path. CI formats read it for the annotation, SARIF
1043    /// and CodeClimate level. Absent in output from older versions. Not
1044    /// part of the finding identity, baseline keys or fingerprints.
1045    #[serde(
1046        default,
1047        skip_serializing_if = "Option::is_none",
1048        deserialize_with = "deserialize_effective_severity"
1049    )]
1050    pub effective_severity: Option<EffectiveSeverity>,
1051}
1052
1053impl BoundaryCoverageViolationFinding {
1054    /// Build the wrapper from a raw [`BoundaryCoverageViolation`].
1055    #[must_use]
1056    pub fn with_actions(violation: BoundaryCoverageViolation) -> Self {
1057        let path = violation.path.to_string_lossy().replace('\\', "/");
1058        let actions = vec![
1059            IssueAction::Fix(FixAction {
1060                kind: FixActionType::RefactorBoundary,
1061                auto_fixable: false,
1062                description: "Add this file to a boundary zone pattern or move it under an existing zone"
1063                    .to_string(),
1064                note: Some(
1065                    "Boundary coverage is enabled, so every analyzed source file must match a zone unless allow-listed"
1066                        .to_string(),
1067                ),
1068                available_in_catalogs: None,
1069                suggested_target: None,
1070            }),
1071            IssueAction::AddToConfig(AddToConfigAction {
1072                kind: AddToConfigKind::AddToConfig,
1073                auto_fixable: false,
1074                description: format!(
1075                    "Add \"{path}\" to boundaries.coverage.allowUnmatched in fallow config"
1076                ),
1077                config_key: "boundaries.coverage.allowUnmatched".to_string(),
1078                value: AddToConfigValue::Scalar(path),
1079                value_schema: Some(
1080                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/boundaries/properties/coverage/properties/allowUnmatched/items"
1081                        .to_string(),
1082                ),
1083            }),
1084            IssueAction::SuppressFile(SuppressFileAction {
1085                kind: SuppressFileKind::SuppressFile,
1086                auto_fixable: false,
1087                description: "Suppress with a file-level comment at the top of the file"
1088                    .to_string(),
1089                comment: "// fallow-ignore-file boundary-violation".to_string(),
1090            }),
1091        ];
1092        Self {
1093            finding_id: None,
1094            violation,
1095            actions,
1096            introduced: None,
1097            effective_severity: None,
1098        }
1099    }
1100}
1101
1102/// Wire-shape envelope for a [`BoundaryCallViolation`] finding. Carries
1103/// actions for refactoring the forbidden call out of the zone or suppressing
1104/// it with the shared `boundary-violation` token.
1105#[derive(Debug, Clone, Serialize, Deserialize)]
1106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1107pub struct BoundaryCallViolationFinding {
1108    /// The underlying forbidden-call entry.
1109    #[serde(flatten)]
1110    pub violation: BoundaryCallViolation,
1111    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1112    /// `~<k>` suffix when several findings of one type share an identity.
1113    /// Line and column are not inputs, so the id survives line shifts,
1114    /// reformats and reorders. A rename of the file or the symbol gives a
1115    /// new id. Absent in output from older versions.
1116    #[serde(default, skip_serializing_if = "Option::is_none")]
1117    pub finding_id: Option<String>,
1118    /// Suggested next steps.
1119    pub actions: Vec<IssueAction>,
1120    /// Set by the audit pass when this finding is introduced relative to
1121    /// the merge-base.
1122    #[serde(default, skip_serializing_if = "Option::is_none")]
1123    pub introduced: Option<AuditIntroduced>,
1124    /// Gate severity of this finding after `rules` and `overrides[].rules`
1125    /// resolve for its path. CI formats read it for the annotation, SARIF
1126    /// and CodeClimate level. Absent in output from older versions. Not
1127    /// part of the finding identity, baseline keys or fingerprints.
1128    #[serde(
1129        default,
1130        skip_serializing_if = "Option::is_none",
1131        deserialize_with = "deserialize_effective_severity"
1132    )]
1133    pub effective_severity: Option<EffectiveSeverity>,
1134}
1135
1136impl BoundaryCallViolationFinding {
1137    /// Build the wrapper from a raw [`BoundaryCallViolation`].
1138    #[must_use]
1139    pub fn with_actions(violation: BoundaryCallViolation) -> Self {
1140        let actions = vec![
1141            IssueAction::Fix(FixAction {
1142                kind: FixActionType::RefactorBoundary,
1143                auto_fixable: false,
1144                description: format!(
1145                    "Move the `{}` call out of zone '{}' or behind an allowed abstraction",
1146                    violation.callee, violation.zone,
1147                ),
1148                note: Some(format!(
1149                    "`boundaries.calls.forbidden` bans callees matching `{}` from zone '{}'. The check is syntactic: it applies only to files classified into a zone and does not follow aliased or re-bound callees",
1150                    violation.pattern, violation.zone,
1151                )),
1152                available_in_catalogs: None,
1153                suggested_target: None,
1154            }),
1155            IssueAction::SuppressLine(SuppressLineAction {
1156                kind: SuppressLineKind::SuppressLine,
1157                auto_fixable: false,
1158                description: "Suppress with an inline comment above the line".to_string(),
1159                comment: "// fallow-ignore-next-line boundary-violation".to_string(),
1160                scope: None,
1161            }),
1162            IssueAction::SuppressFile(SuppressFileAction {
1163                kind: SuppressFileKind::SuppressFile,
1164                auto_fixable: false,
1165                description: "Suppress with a file-level comment at the top of the file"
1166                    .to_string(),
1167                comment: "// fallow-ignore-file boundary-violation".to_string(),
1168            }),
1169        ];
1170        Self {
1171            finding_id: None,
1172            violation,
1173            actions,
1174            introduced: None,
1175            effective_severity: None,
1176        }
1177    }
1178}
1179
1180/// Wire-shape envelope for a [`PolicyViolation`] finding. Carries actions for
1181/// replacing the banned call, import, or effect, or suppressing it with a scoped
1182/// `policy-violation:<pack>/<rule-id>` token.
1183#[derive(Debug, Clone, Serialize, Deserialize)]
1184#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1185pub struct PolicyViolationFinding {
1186    /// The underlying rule-pack policy entry.
1187    #[serde(flatten)]
1188    pub violation: PolicyViolation,
1189    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1190    /// `~<k>` suffix when several findings of one type share an identity.
1191    /// Line and column are not inputs, so the id survives line shifts,
1192    /// reformats and reorders. A rename of the file or the symbol gives a
1193    /// new id. Absent in output from older versions.
1194    #[serde(default, skip_serializing_if = "Option::is_none")]
1195    pub finding_id: Option<String>,
1196    /// Suggested next steps.
1197    pub actions: Vec<IssueAction>,
1198    /// Set by the audit pass when this finding is introduced relative to
1199    /// the merge-base.
1200    #[serde(default, skip_serializing_if = "Option::is_none")]
1201    pub introduced: Option<AuditIntroduced>,
1202}
1203
1204impl PolicyViolationFinding {
1205    /// Build the wrapper from a raw [`PolicyViolation`].
1206    #[must_use]
1207    pub fn with_actions(violation: PolicyViolation) -> Self {
1208        let what = match violation.kind {
1209            crate::results::PolicyRuleKind::BannedCall => "call",
1210            crate::results::PolicyRuleKind::BannedImport => "import",
1211            crate::results::PolicyRuleKind::BannedEffect => "effect",
1212            crate::results::PolicyRuleKind::BannedExport => "export",
1213            crate::results::PolicyRuleKind::GdpProofProducer => "proof producer",
1214        };
1215        let description = match &violation.message {
1216            Some(message) => format!("Replace the `{}` {what}: {message}", violation.matched),
1217            None => format!("Replace the `{}` {what}", violation.matched),
1218        };
1219        let suppress_token = format!("policy-violation:{}/{}", violation.pack, violation.rule_id);
1220        let note = if violation.kind == crate::results::PolicyRuleKind::GdpProofProducer {
1221            "This check resolves the gdp-ts factory through static imports and unambiguous re-exports. Move proof creation to an allowed module. It does not verify authorization logic or follow arbitrary wrappers.".to_owned()
1222        } else {
1223            format!(
1224                "Rule `{}/{}` from the configured rule packs bans this {what}. The check is syntactic: it does not follow aliased or re-bound callees, and import matching uses the raw specifier",
1225                violation.pack, violation.rule_id,
1226            )
1227        };
1228        let actions = vec![
1229            IssueAction::Fix(FixAction {
1230                kind: FixActionType::ResolvePolicyViolation,
1231                auto_fixable: false,
1232                description,
1233                note: Some(note),
1234                available_in_catalogs: None,
1235                suggested_target: None,
1236            }),
1237            IssueAction::SuppressLine(SuppressLineAction {
1238                kind: SuppressLineKind::SuppressLine,
1239                auto_fixable: false,
1240                description: "Suppress this rule-pack rule with an inline comment above the line"
1241                    .to_string(),
1242                comment: format!("// fallow-ignore-next-line {suppress_token}"),
1243                scope: None,
1244            }),
1245            IssueAction::SuppressFile(SuppressFileAction {
1246                kind: SuppressFileKind::SuppressFile,
1247                auto_fixable: false,
1248                description:
1249                    "Suppress this rule-pack rule with a file-level comment at the top of the file"
1250                        .to_string(),
1251                comment: format!("// fallow-ignore-file {suppress_token}"),
1252            }),
1253        ];
1254        Self {
1255            finding_id: None,
1256            violation,
1257            actions,
1258            introduced: None,
1259        }
1260    }
1261}
1262
1263/// Wire-shape envelope for an [`UnusedExport`] finding consumed under the
1264/// `unused_exports` key. Same Rust struct as [`UnusedTypeFinding`], with a
1265/// different fix description so consumers can tell value-export from
1266/// type-export removal at the action level.
1267#[derive(Debug, Clone, Serialize, Deserialize)]
1268#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1269pub struct UnusedExportFinding {
1270    /// The underlying dead-code entry.
1271    #[serde(flatten)]
1272    pub export: UnusedExport,
1273    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1274    /// `~<k>` suffix when several findings of one type share an identity.
1275    /// Line and column are not inputs, so the id survives line shifts,
1276    /// reformats and reorders. A rename of the file or the symbol gives a
1277    /// new id. Absent in output from older versions.
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    pub finding_id: Option<String>,
1280    /// Suggested next steps. Always emitted (possibly empty for
1281    /// forward-compat).
1282    pub actions: Vec<IssueAction>,
1283    /// Type-aware evidence for this exact candidate when requested.
1284    #[serde(default, skip_serializing_if = "Option::is_none")]
1285    pub semantic: Option<SemanticCandidateDecision>,
1286    /// Set by the audit pass when this finding is introduced relative to
1287    /// the merge-base.
1288    #[serde(default, skip_serializing_if = "Option::is_none")]
1289    pub introduced: Option<AuditIntroduced>,
1290    /// Gate severity of this finding after `rules` and `overrides[].rules`
1291    /// resolve for its path. CI formats read it for the annotation, SARIF
1292    /// and CodeClimate level. Absent in output from older versions. Not
1293    /// part of the finding identity, baseline keys or fingerprints.
1294    #[serde(
1295        default,
1296        skip_serializing_if = "Option::is_none",
1297        deserialize_with = "deserialize_effective_severity"
1298    )]
1299    pub effective_severity: Option<EffectiveSeverity>,
1300    /// Advisory caveats on the reachability verdict behind this finding.
1301    /// Sorted, deduplicated, and omitted from the wire when empty. Never gates
1302    /// the finding or the `remove-export` action, though `fallow fix` does
1303    /// withhold the removal of a caveated export as low confidence.
1304    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1305    pub reachability_caveats: Vec<ReachabilityCaveat>,
1306}
1307
1308impl UnusedExportFinding {
1309    /// Build the wrapper. When `export.is_re_export` is true, the fix
1310    /// action's `note` warns about possible public-API surface; otherwise
1311    /// `note` is absent on the fix action.
1312    #[must_use]
1313    pub fn with_actions(export: UnusedExport) -> Self {
1314        let note = if export.is_re_export {
1315            Some(
1316                "This finding originates from a re-export; verify it is not part of your public API before removing"
1317                    .to_string(),
1318            )
1319        } else {
1320            None
1321        };
1322        let actions = vec![
1323            IssueAction::Fix(FixAction {
1324                kind: FixActionType::RemoveExport,
1325                auto_fixable: true,
1326                description: "Remove the unused export from the public API".to_string(),
1327                note,
1328                available_in_catalogs: None,
1329                suggested_target: None,
1330            }),
1331            IssueAction::SuppressLine(SuppressLineAction {
1332                kind: SuppressLineKind::SuppressLine,
1333                auto_fixable: false,
1334                description: "Suppress with an inline comment above the line".to_string(),
1335                comment: "// fallow-ignore-next-line unused-export".to_string(),
1336                scope: None,
1337            }),
1338        ];
1339        Self {
1340            finding_id: None,
1341            export,
1342            actions,
1343            semantic: None,
1344            introduced: None,
1345            effective_severity: None,
1346            reachability_caveats: Vec::new(),
1347        }
1348    }
1349
1350    /// Attach type-aware evidence and disable the syntactic fix when semantic
1351    /// analysis could not establish complete negative evidence.
1352    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
1353        set_export_semantic_action(&mut self.actions, &decision, &self.reachability_caveats);
1354        self.semantic = Some(decision);
1355    }
1356}
1357
1358/// Wire-shape envelope for an [`UnusedExport`] finding consumed under the
1359/// `unused_types` key. Wraps the same bare [`UnusedExport`] struct as
1360/// [`UnusedExportFinding`] but emits a fix action targeted at type-only
1361/// declarations, with the same `is_re_export`-aware note swap.
1362#[derive(Debug, Clone, Serialize, Deserialize)]
1363#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1364pub struct UnusedTypeFinding {
1365    /// The underlying dead-code entry.
1366    #[serde(flatten)]
1367    pub export: UnusedExport,
1368    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1369    /// `~<k>` suffix when several findings of one type share an identity.
1370    /// Line and column are not inputs, so the id survives line shifts,
1371    /// reformats and reorders. A rename of the file or the symbol gives a
1372    /// new id. Absent in output from older versions.
1373    #[serde(default, skip_serializing_if = "Option::is_none")]
1374    pub finding_id: Option<String>,
1375    /// Suggested next steps. Always emitted (possibly empty for
1376    /// forward-compat).
1377    pub actions: Vec<IssueAction>,
1378    /// Type-aware evidence for this exact candidate when requested.
1379    #[serde(default, skip_serializing_if = "Option::is_none")]
1380    pub semantic: Option<SemanticCandidateDecision>,
1381    /// Set by the audit pass when this finding is introduced relative to
1382    /// the merge-base.
1383    #[serde(default, skip_serializing_if = "Option::is_none")]
1384    pub introduced: Option<AuditIntroduced>,
1385    /// Gate severity of this finding after `rules` and `overrides[].rules`
1386    /// resolve for its path. CI formats read it for the annotation, SARIF
1387    /// and CodeClimate level. Absent in output from older versions. Not
1388    /// part of the finding identity, baseline keys or fingerprints.
1389    #[serde(
1390        default,
1391        skip_serializing_if = "Option::is_none",
1392        deserialize_with = "deserialize_effective_severity"
1393    )]
1394    pub effective_severity: Option<EffectiveSeverity>,
1395    /// Advisory caveats on the reachability verdict behind this finding.
1396    /// A type export rests on exactly the reachability test an
1397    /// `unused_exports[]` entry does, and the LSP offers the same
1398    /// remove-the-`export`-keyword quick fix for both, so the two must render
1399    /// with the same confidence. Sorted, deduplicated, omitted when empty.
1400    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1401    pub reachability_caveats: Vec<ReachabilityCaveat>,
1402}
1403
1404impl UnusedTypeFinding {
1405    /// Build the wrapper. `is_re_export` swaps the fix note the same way as
1406    /// [`UnusedExportFinding::with_actions`].
1407    #[must_use]
1408    pub fn with_actions(export: UnusedExport) -> Self {
1409        let note = if export.is_re_export {
1410            Some(
1411                "This finding originates from a re-export; verify it is not part of your public API before removing"
1412                    .to_string(),
1413            )
1414        } else {
1415            None
1416        };
1417        let actions = vec![
1418            IssueAction::Fix(FixAction {
1419                kind: FixActionType::RemoveExport,
1420                auto_fixable: true,
1421                description:
1422                    "Remove the `export` (or `export type`) keyword from the type declaration"
1423                        .to_string(),
1424                note,
1425                available_in_catalogs: None,
1426                suggested_target: None,
1427            }),
1428            IssueAction::SuppressLine(SuppressLineAction {
1429                kind: SuppressLineKind::SuppressLine,
1430                auto_fixable: false,
1431                description: "Suppress with an inline comment above the line".to_string(),
1432                comment: "// fallow-ignore-next-line unused-type".to_string(),
1433                scope: None,
1434            }),
1435        ];
1436        Self {
1437            finding_id: None,
1438            export,
1439            actions,
1440            semantic: None,
1441            introduced: None,
1442            effective_severity: None,
1443            reachability_caveats: Vec::new(),
1444        }
1445    }
1446
1447    /// Attach type-aware evidence and disable the syntactic fix when semantic
1448    /// analysis could not establish complete negative evidence.
1449    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
1450        set_export_semantic_action(&mut self.actions, &decision, &self.reachability_caveats);
1451        self.semantic = Some(decision);
1452    }
1453}
1454
1455/// The semantic pass runs in the API layer, AFTER the analysis layer stamped
1456/// this run's caveats, and it is the one code path that RAISES `auto_fixable`.
1457/// It therefore has to ask the gate too, or a `Complete` semantic verdict would
1458/// silently re-open a mutation the incomplete run had already withheld.
1459fn set_export_semantic_action(
1460    actions: &mut [IssueAction],
1461    decision: &SemanticCandidateDecision,
1462    caveats: &[ReachabilityCaveat],
1463) {
1464    let complete_negative = decision.decision
1465        == SemanticCandidateDecisionKind::ConfirmedNoStaticReferences
1466        && decision.status == SemanticCompleteness::Complete;
1467    let Some(IssueAction::Fix(action)) = actions.first_mut() else {
1468        return;
1469    };
1470    action.auto_fixable = complete_negative && caveats.is_empty();
1471    if !complete_negative {
1472        action.note = Some(
1473            "Type-aware analysis retained this candidate because complete negative evidence was not available"
1474                .to_string(),
1475        );
1476    }
1477    if !caveats.is_empty() {
1478        action.note = Some(INCOMPLETE_EVIDENCE_NOTE.to_string());
1479    }
1480}
1481
1482/// Wire-shape envelope for an [`InvalidClientExport`] finding. There is no safe
1483/// auto-fix: the export itself may be a legitimate client-component value
1484/// export that happens to collide with a Next.js server-only name, so removing
1485/// it could break the component. Actions are a manual `move-to-server-module`
1486/// fix (the real remediation) plus a line-level suppress.
1487#[derive(Debug, Clone, Serialize, Deserialize)]
1488#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1489pub struct InvalidClientExportFinding {
1490    /// The underlying dead-code entry.
1491    #[serde(flatten)]
1492    pub export: InvalidClientExport,
1493    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1494    /// `~<k>` suffix when several findings of one type share an identity.
1495    /// Line and column are not inputs, so the id survives line shifts,
1496    /// reformats and reorders. A rename of the file or the symbol gives a
1497    /// new id. Absent in output from older versions.
1498    #[serde(default, skip_serializing_if = "Option::is_none")]
1499    pub finding_id: Option<String>,
1500    /// Suggested next steps. Always emitted (possibly empty for
1501    /// forward-compat).
1502    pub actions: Vec<IssueAction>,
1503    /// Set by the audit pass when this finding is introduced relative to
1504    /// the merge-base.
1505    #[serde(default, skip_serializing_if = "Option::is_none")]
1506    pub introduced: Option<AuditIntroduced>,
1507    /// Gate severity of this finding after `rules` and `overrides[].rules`
1508    /// resolve for its path. CI formats read it for the annotation, SARIF
1509    /// and CodeClimate level. Absent in output from older versions. Not
1510    /// part of the finding identity, baseline keys or fingerprints.
1511    #[serde(
1512        default,
1513        skip_serializing_if = "Option::is_none",
1514        deserialize_with = "deserialize_effective_severity"
1515    )]
1516    pub effective_severity: Option<EffectiveSeverity>,
1517}
1518
1519impl InvalidClientExportFinding {
1520    /// Build the wrapper from a raw [`InvalidClientExport`]. Emits a manual
1521    /// fix action (move the server-only export to a non-client module) plus a
1522    /// line-level suppress: there is no safe auto-fix because removing the
1523    /// export could break a legitimate client component.
1524    #[must_use]
1525    pub fn with_actions(export: InvalidClientExport) -> Self {
1526        let actions = vec![
1527            IssueAction::Fix(FixAction {
1528                kind: FixActionType::MoveToServerModule,
1529                auto_fixable: false,
1530                description: "Move the server-only export to a non-client module and import it from there"
1531                    .to_string(),
1532                note: Some(
1533                    "A \"use client\" file cannot export a Next.js server-only or route-config name; Next.js rejects it at build time"
1534                        .to_string(),
1535                ),
1536                available_in_catalogs: None,
1537                suggested_target: None,
1538            }),
1539            IssueAction::SuppressLine(SuppressLineAction {
1540                kind: SuppressLineKind::SuppressLine,
1541                auto_fixable: false,
1542                description: "Suppress with an inline comment above the line".to_string(),
1543                comment: "// fallow-ignore-next-line invalid-client-export".to_string(),
1544                scope: None,
1545            }),
1546        ];
1547        Self {
1548            finding_id: None,
1549            export,
1550            actions,
1551            introduced: None,
1552            effective_severity: None,
1553        }
1554    }
1555}
1556
1557/// Wire-shape envelope for a [`MixedClientServerBarrel`] finding. There is no
1558/// safe auto-fix: splitting a barrel into separate client and server modules is
1559/// a human decision (the barrel may intentionally aggregate both surfaces).
1560/// Actions are a manual `split-mixed-barrel` fix (the real remediation) plus a
1561/// line-level suppress.
1562#[derive(Debug, Clone, Serialize, Deserialize)]
1563#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1564pub struct MixedClientServerBarrelFinding {
1565    /// The underlying dead-code entry.
1566    #[serde(flatten)]
1567    pub barrel: MixedClientServerBarrel,
1568    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1569    /// `~<k>` suffix when several findings of one type share an identity.
1570    /// Line and column are not inputs, so the id survives line shifts,
1571    /// reformats and reorders. A rename of the file or the symbol gives a
1572    /// new id. Absent in output from older versions.
1573    #[serde(default, skip_serializing_if = "Option::is_none")]
1574    pub finding_id: Option<String>,
1575    /// Suggested next steps. Always emitted (possibly empty for
1576    /// forward-compat).
1577    pub actions: Vec<IssueAction>,
1578    /// Set by the audit pass when this finding is introduced relative to
1579    /// the merge-base.
1580    #[serde(default, skip_serializing_if = "Option::is_none")]
1581    pub introduced: Option<AuditIntroduced>,
1582    /// Gate severity of this finding after `rules` and `overrides[].rules`
1583    /// resolve for its path. CI formats read it for the annotation, SARIF
1584    /// and CodeClimate level. Absent in output from older versions. Not
1585    /// part of the finding identity, baseline keys or fingerprints.
1586    #[serde(
1587        default,
1588        skip_serializing_if = "Option::is_none",
1589        deserialize_with = "deserialize_effective_severity"
1590    )]
1591    pub effective_severity: Option<EffectiveSeverity>,
1592}
1593
1594impl MixedClientServerBarrelFinding {
1595    /// Build the wrapper from a raw [`MixedClientServerBarrel`]. Emits a manual
1596    /// fix action (split the barrel into separate client and server halves)
1597    /// plus a line-level suppress: there is no safe auto-fix because splitting
1598    /// the barrel is a human decision.
1599    #[must_use]
1600    pub fn with_actions(barrel: MixedClientServerBarrel) -> Self {
1601        let actions = vec![
1602            IssueAction::Fix(FixAction {
1603                kind: FixActionType::SplitMixedBarrel,
1604                auto_fixable: false,
1605                description: "Split the barrel so client and server-only modules are re-exported from separate files"
1606                    .to_string(),
1607                note: Some(
1608                    "Importing one name from this barrel drags the other's directive across the client/server boundary"
1609                        .to_string(),
1610                ),
1611                available_in_catalogs: None,
1612                suggested_target: None,
1613            }),
1614            IssueAction::SuppressLine(SuppressLineAction {
1615                kind: SuppressLineKind::SuppressLine,
1616                auto_fixable: false,
1617                description: "Suppress with an inline comment above the line".to_string(),
1618                comment: "// fallow-ignore-next-line mixed-client-server-barrel".to_string(),
1619                scope: None,
1620            }),
1621        ];
1622        Self {
1623            finding_id: None,
1624            barrel,
1625            actions,
1626            introduced: None,
1627            effective_severity: None,
1628        }
1629    }
1630}
1631
1632/// Wire-shape envelope for a [`MisplacedDirective`] finding. There is no safe
1633/// auto-fix: moving a directive to the leading prologue is a small but
1634/// judgement-bearing edit (the author may have intended the file to be a
1635/// server module after all). Actions are a manual `hoist-directive` fix (the
1636/// real remediation) plus a line-level suppress.
1637#[derive(Debug, Clone, Serialize, Deserialize)]
1638#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1639pub struct MisplacedDirectiveFinding {
1640    /// The underlying dead-code entry.
1641    #[serde(flatten)]
1642    pub directive_site: MisplacedDirective,
1643    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1644    /// `~<k>` suffix when several findings of one type share an identity.
1645    /// Line and column are not inputs, so the id survives line shifts,
1646    /// reformats and reorders. A rename of the file or the symbol gives a
1647    /// new id. Absent in output from older versions.
1648    #[serde(default, skip_serializing_if = "Option::is_none")]
1649    pub finding_id: Option<String>,
1650    /// Suggested next steps. Always emitted (possibly empty for
1651    /// forward-compat).
1652    pub actions: Vec<IssueAction>,
1653    /// Set by the audit pass when this finding is introduced relative to
1654    /// the merge-base.
1655    #[serde(default, skip_serializing_if = "Option::is_none")]
1656    pub introduced: Option<AuditIntroduced>,
1657    /// Gate severity of this finding after `rules` and `overrides[].rules`
1658    /// resolve for its path. CI formats read it for the annotation, SARIF
1659    /// and CodeClimate level. Absent in output from older versions. Not
1660    /// part of the finding identity, baseline keys or fingerprints.
1661    #[serde(
1662        default,
1663        skip_serializing_if = "Option::is_none",
1664        deserialize_with = "deserialize_effective_severity"
1665    )]
1666    pub effective_severity: Option<EffectiveSeverity>,
1667}
1668
1669impl MisplacedDirectiveFinding {
1670    /// Build the wrapper from a raw [`MisplacedDirective`]. Emits a manual fix
1671    /// action (hoist the directive to the leading prologue) plus a line-level
1672    /// suppress: there is no safe auto-fix because moving a directive can
1673    /// change module semantics and is a human decision.
1674    #[must_use]
1675    pub fn with_actions(directive_site: MisplacedDirective) -> Self {
1676        let actions = vec![
1677            IssueAction::Fix(FixAction {
1678                kind: FixActionType::HoistDirective,
1679                auto_fixable: false,
1680                description: "Move the directive to the very top of the file, above all imports and statements"
1681                    .to_string(),
1682                note: Some(
1683                    "An RSC bundler honors the directive only in the leading prologue; here it precedes other statements and is silently ignored"
1684                        .to_string(),
1685                ),
1686                available_in_catalogs: None,
1687                suggested_target: None,
1688            }),
1689            IssueAction::SuppressLine(SuppressLineAction {
1690                kind: SuppressLineKind::SuppressLine,
1691                auto_fixable: false,
1692                description: "Suppress with an inline comment above the line".to_string(),
1693                comment: "// fallow-ignore-next-line misplaced-directive".to_string(),
1694                scope: None,
1695            }),
1696        ];
1697        Self {
1698            finding_id: None,
1699            directive_site,
1700            actions,
1701            introduced: None,
1702            effective_severity: None,
1703        }
1704    }
1705}
1706
1707/// Wire-shape envelope for an [`UnprovidedInject`] finding. There is no safe
1708/// auto-fix: the fix is binary but judgement-bearing (add a `provide` for the
1709/// key, or delete the dead inject). Actions are manual remediation guidance
1710/// plus a line-level suppress.
1711#[derive(Debug, Clone, Serialize, Deserialize)]
1712#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1713pub struct UnprovidedInjectFinding {
1714    /// The underlying finding.
1715    #[serde(flatten)]
1716    pub inject: UnprovidedInject,
1717    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1718    /// `~<k>` suffix when several findings of one type share an identity.
1719    /// Line and column are not inputs, so the id survives line shifts,
1720    /// reformats and reorders. A rename of the file or the symbol gives a
1721    /// new id. Absent in output from older versions.
1722    #[serde(default, skip_serializing_if = "Option::is_none")]
1723    pub finding_id: Option<String>,
1724    /// Suggested next steps. Always emitted (possibly empty for
1725    /// forward-compat).
1726    pub actions: Vec<IssueAction>,
1727    /// Set by the audit pass when this finding is introduced relative to
1728    /// the merge-base.
1729    #[serde(default, skip_serializing_if = "Option::is_none")]
1730    pub introduced: Option<AuditIntroduced>,
1731    /// Gate severity of this finding after `rules` and `overrides[].rules`
1732    /// resolve for its path. CI formats read it for the annotation, SARIF
1733    /// and CodeClimate level. Absent in output from older versions. Not
1734    /// part of the finding identity, baseline keys or fingerprints.
1735    #[serde(
1736        default,
1737        skip_serializing_if = "Option::is_none",
1738        deserialize_with = "deserialize_effective_severity"
1739    )]
1740    pub effective_severity: Option<EffectiveSeverity>,
1741}
1742
1743impl UnprovidedInjectFinding {
1744    /// Build the wrapper from a raw [`UnprovidedInject`]. Emits a manual fix
1745    /// action plus a line-level suppress.
1746    #[must_use]
1747    pub fn with_actions(inject: UnprovidedInject) -> Self {
1748        let actions = vec![
1749            manual_framework_fix(
1750                FixActionType::ProvideInject,
1751                "Provide this injected key, or remove the inject / getContext call",
1752                "Manual review required: dependency-injection keys can be provided by framework wiring, tests, or package consumers outside this project.",
1753            ),
1754            suppress_line("// fallow-ignore-next-line unprovided-inject"),
1755        ];
1756        Self {
1757            finding_id: None,
1758            inject,
1759            actions,
1760            introduced: None,
1761            effective_severity: None,
1762        }
1763    }
1764}
1765
1766/// Wire-shape envelope for an [`UnusedServerAction`] finding. There is no safe
1767/// auto-fix: the fix is binary but judgement-bearing (wire the action up to a
1768/// consumer, or delete it). Actions are manual remediation guidance plus a
1769/// line-level suppress.
1770#[derive(Debug, Clone, Serialize, Deserialize)]
1771#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1772pub struct UnusedServerActionFinding {
1773    /// The underlying finding.
1774    #[serde(flatten)]
1775    pub action: UnusedServerAction,
1776    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1777    /// `~<k>` suffix when several findings of one type share an identity.
1778    /// Line and column are not inputs, so the id survives line shifts,
1779    /// reformats and reorders. A rename of the file or the symbol gives a
1780    /// new id. Absent in output from older versions.
1781    #[serde(default, skip_serializing_if = "Option::is_none")]
1782    pub finding_id: Option<String>,
1783    /// Suggested next steps. Always emitted (possibly empty for
1784    /// forward-compat).
1785    pub actions: Vec<IssueAction>,
1786    /// Set by the audit pass when this finding is introduced relative to
1787    /// the merge-base.
1788    #[serde(default, skip_serializing_if = "Option::is_none")]
1789    pub introduced: Option<AuditIntroduced>,
1790    /// Gate severity of this finding after `rules` and `overrides[].rules`
1791    /// resolve for its path. CI formats read it for the annotation, SARIF
1792    /// and CodeClimate level. Absent in output from older versions. Not
1793    /// part of the finding identity, baseline keys or fingerprints.
1794    #[serde(
1795        default,
1796        skip_serializing_if = "Option::is_none",
1797        deserialize_with = "deserialize_effective_severity"
1798    )]
1799    pub effective_severity: Option<EffectiveSeverity>,
1800}
1801
1802impl UnusedServerActionFinding {
1803    /// Build the wrapper from a raw [`UnusedServerAction`]. Emits a manual fix
1804    /// action plus a line-level suppress.
1805    #[must_use]
1806    pub fn with_actions(action: UnusedServerAction) -> Self {
1807        let actions = vec![
1808            manual_framework_fix(
1809                FixActionType::WireServerAction,
1810                "Wire the server action to a caller or form action, or remove it",
1811                "Manual review required: server actions may still be POST-able by action id or invoked reflectively outside the static project graph.",
1812            ),
1813            suppress_line("// fallow-ignore-next-line unused-server-action"),
1814        ];
1815        Self {
1816            finding_id: None,
1817            action,
1818            actions,
1819            introduced: None,
1820            effective_severity: None,
1821        }
1822    }
1823}
1824
1825/// Wire-shape envelope for an [`UnusedLoadDataKey`] finding. There is no safe
1826/// auto-fix: a `load()` fetch can have side effects, so deleting the key is a
1827/// human call. Actions are manual remediation guidance plus a line-level
1828/// suppress.
1829#[derive(Debug, Clone, Serialize, Deserialize)]
1830#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1831pub struct UnusedLoadDataKeyFinding {
1832    /// The underlying finding.
1833    #[serde(flatten)]
1834    pub key: UnusedLoadDataKey,
1835    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1836    /// `~<k>` suffix when several findings of one type share an identity.
1837    /// Line and column are not inputs, so the id survives line shifts,
1838    /// reformats and reorders. A rename of the file or the symbol gives a
1839    /// new id. Absent in output from older versions.
1840    #[serde(default, skip_serializing_if = "Option::is_none")]
1841    pub finding_id: Option<String>,
1842    /// Suggested next steps. Always emitted (possibly empty for
1843    /// forward-compat).
1844    pub actions: Vec<IssueAction>,
1845    /// Set by the audit pass when this finding is introduced relative to
1846    /// the merge-base.
1847    #[serde(default, skip_serializing_if = "Option::is_none")]
1848    pub introduced: Option<AuditIntroduced>,
1849    /// Gate severity of this finding after `rules` and `overrides[].rules`
1850    /// resolve for its path. CI formats read it for the annotation, SARIF
1851    /// and CodeClimate level. Absent in output from older versions. Not
1852    /// part of the finding identity, baseline keys or fingerprints.
1853    #[serde(
1854        default,
1855        skip_serializing_if = "Option::is_none",
1856        deserialize_with = "deserialize_effective_severity"
1857    )]
1858    pub effective_severity: Option<EffectiveSeverity>,
1859}
1860
1861impl UnusedLoadDataKeyFinding {
1862    /// Build the wrapper from a raw [`UnusedLoadDataKey`]. Emits a manual fix
1863    /// action plus a line-level suppress.
1864    #[must_use]
1865    pub fn with_actions(key: UnusedLoadDataKey) -> Self {
1866        let actions = vec![
1867            manual_framework_fix(
1868                FixActionType::UseLoadData,
1869                "Read this load data key from the route UI, or remove it from the load return",
1870                "Manual review required: load functions can perform real server or database work, so verify side effects before deleting the producer.",
1871            ),
1872            suppress_line("// fallow-ignore-next-line unused-load-data-key"),
1873        ];
1874        Self {
1875            finding_id: None,
1876            key,
1877            actions,
1878            introduced: None,
1879            effective_severity: None,
1880        }
1881    }
1882}
1883
1884/// Wire-shape envelope for an [`UnrenderedComponent`] finding. There is no safe
1885/// auto-fix: the fix is binary but judgement-bearing (render the component
1886/// somewhere, or delete the dead component). Actions are manual remediation
1887/// guidance plus a line-level suppress.
1888#[derive(Debug, Clone, Serialize, Deserialize)]
1889#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1890pub struct UnrenderedComponentFinding {
1891    /// The underlying finding.
1892    #[serde(flatten)]
1893    pub component: UnrenderedComponent,
1894    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1895    /// `~<k>` suffix when several findings of one type share an identity.
1896    /// Line and column are not inputs, so the id survives line shifts,
1897    /// reformats and reorders. A rename of the file or the symbol gives a
1898    /// new id. Absent in output from older versions.
1899    #[serde(default, skip_serializing_if = "Option::is_none")]
1900    pub finding_id: Option<String>,
1901    /// Suggested next steps. Always emitted (possibly empty for
1902    /// forward-compat).
1903    pub actions: Vec<IssueAction>,
1904    /// Set by the audit pass when this finding is introduced relative to
1905    /// the merge-base.
1906    #[serde(default, skip_serializing_if = "Option::is_none")]
1907    pub introduced: Option<AuditIntroduced>,
1908    /// Gate severity of this finding after `rules` and `overrides[].rules`
1909    /// resolve for its path. CI formats read it for the annotation, SARIF
1910    /// and CodeClimate level. Absent in output from older versions. Not
1911    /// part of the finding identity, baseline keys or fingerprints.
1912    #[serde(
1913        default,
1914        skip_serializing_if = "Option::is_none",
1915        deserialize_with = "deserialize_effective_severity"
1916    )]
1917    pub effective_severity: Option<EffectiveSeverity>,
1918}
1919
1920impl UnrenderedComponentFinding {
1921    /// Build the wrapper from a raw [`UnrenderedComponent`]. Emits a manual
1922    /// fix action plus a line-level suppress.
1923    #[must_use]
1924    pub fn with_actions(component: UnrenderedComponent) -> Self {
1925        let actions = vec![
1926            manual_framework_fix(
1927                FixActionType::RenderComponent,
1928                "Render the reachable component from project code, or remove it",
1929                "Manual review required: exported library components and dynamic render registries can be intentionally reachable without static template usage.",
1930            ),
1931            suppress_line("// fallow-ignore-next-line unrendered-component"),
1932        ];
1933        Self {
1934            finding_id: None,
1935            component,
1936            actions,
1937            introduced: None,
1938            effective_severity: None,
1939        }
1940    }
1941}
1942
1943/// Wire-shape envelope for an [`UnusedComponentProp`] finding. There is no safe
1944/// auto-fix: removing a declared prop is judgement-bearing (the prop may be part
1945/// of a deliberately-stable public component API). Actions are manual
1946/// remediation guidance plus a line-level suppress at the prop declaration.
1947#[derive(Debug, Clone, Serialize, Deserialize)]
1948#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1949pub struct UnusedComponentPropFinding {
1950    /// The underlying finding.
1951    #[serde(flatten)]
1952    pub prop: UnusedComponentProp,
1953    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
1954    /// `~<k>` suffix when several findings of one type share an identity.
1955    /// Line and column are not inputs, so the id survives line shifts,
1956    /// reformats and reorders. A rename of the file or the symbol gives a
1957    /// new id. Absent in output from older versions.
1958    #[serde(default, skip_serializing_if = "Option::is_none")]
1959    pub finding_id: Option<String>,
1960    /// Suggested next steps. Always emitted (possibly empty for
1961    /// forward-compat).
1962    pub actions: Vec<IssueAction>,
1963    /// Set by the audit pass when this finding is introduced relative to
1964    /// the merge-base.
1965    #[serde(default, skip_serializing_if = "Option::is_none")]
1966    pub introduced: Option<AuditIntroduced>,
1967    /// Gate severity of this finding after `rules` and `overrides[].rules`
1968    /// resolve for its path. CI formats read it for the annotation, SARIF
1969    /// and CodeClimate level. Absent in output from older versions. Not
1970    /// part of the finding identity, baseline keys or fingerprints.
1971    #[serde(
1972        default,
1973        skip_serializing_if = "Option::is_none",
1974        deserialize_with = "deserialize_effective_severity"
1975    )]
1976    pub effective_severity: Option<EffectiveSeverity>,
1977}
1978
1979impl UnusedComponentPropFinding {
1980    /// Build the wrapper from a raw [`UnusedComponentProp`]. Emits a manual
1981    /// fix action plus a line-level suppress.
1982    #[must_use]
1983    pub fn with_actions(prop: UnusedComponentProp) -> Self {
1984        let actions = vec![
1985            manual_framework_fix(
1986                FixActionType::UseComponentProp,
1987                "Use the declared prop in the component, or remove it from the component API",
1988                "Manual review required: public component APIs can intentionally keep stable props for external consumers.",
1989            ),
1990            suppress_line("// fallow-ignore-next-line unused-component-prop"),
1991        ];
1992        Self {
1993            finding_id: None,
1994            prop,
1995            actions,
1996            introduced: None,
1997            effective_severity: None,
1998        }
1999    }
2000}
2001
2002/// Wire-shape envelope for an [`UnusedComponentEmit`] finding. There is no safe
2003/// auto-fix: removing a declared emit is judgement-bearing (the event may be
2004/// part of a deliberately-stable public component API). Actions are manual
2005/// remediation guidance plus a line-level suppress at the emit declaration.
2006#[derive(Debug, Clone, Serialize, Deserialize)]
2007#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2008pub struct UnusedComponentEmitFinding {
2009    /// The underlying finding.
2010    #[serde(flatten)]
2011    pub emit: UnusedComponentEmit,
2012    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2013    /// `~<k>` suffix when several findings of one type share an identity.
2014    /// Line and column are not inputs, so the id survives line shifts,
2015    /// reformats and reorders. A rename of the file or the symbol gives a
2016    /// new id. Absent in output from older versions.
2017    #[serde(default, skip_serializing_if = "Option::is_none")]
2018    pub finding_id: Option<String>,
2019    /// Suggested next steps. Always emitted (possibly empty for
2020    /// forward-compat).
2021    pub actions: Vec<IssueAction>,
2022    /// Set by the audit pass when this finding is introduced relative to
2023    /// the merge-base.
2024    #[serde(default, skip_serializing_if = "Option::is_none")]
2025    pub introduced: Option<AuditIntroduced>,
2026    /// Gate severity of this finding after `rules` and `overrides[].rules`
2027    /// resolve for its path. CI formats read it for the annotation, SARIF
2028    /// and CodeClimate level. Absent in output from older versions. Not
2029    /// part of the finding identity, baseline keys or fingerprints.
2030    #[serde(
2031        default,
2032        skip_serializing_if = "Option::is_none",
2033        deserialize_with = "deserialize_effective_severity"
2034    )]
2035    pub effective_severity: Option<EffectiveSeverity>,
2036}
2037
2038impl UnusedComponentEmitFinding {
2039    /// Build the wrapper from a raw [`UnusedComponentEmit`]. Emits a manual
2040    /// fix action plus a line-level suppress.
2041    #[must_use]
2042    pub fn with_actions(emit: UnusedComponentEmit) -> Self {
2043        let actions = vec![
2044            manual_framework_fix(
2045                FixActionType::EmitComponentEvent,
2046                "Emit the declared event from the component, or remove it from the component API",
2047                "Manual review required: public component APIs can intentionally keep stable events for external listeners.",
2048            ),
2049            suppress_line("// fallow-ignore-next-line unused-component-emit"),
2050        ];
2051        Self {
2052            finding_id: None,
2053            emit,
2054            actions,
2055            introduced: None,
2056            effective_severity: None,
2057        }
2058    }
2059}
2060
2061/// Wire-shape envelope for an [`UnusedSvelteEvent`] finding. There is no safe
2062/// auto-fix: removing a dispatched event is judgement-bearing (the event may be
2063/// part of a deliberately-stable public component API, or a listener may be
2064/// added later). Actions are manual remediation guidance plus a line-level
2065/// suppress at the `dispatch` call.
2066#[derive(Debug, Clone, Serialize, Deserialize)]
2067#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2068pub struct UnusedSvelteEventFinding {
2069    /// The underlying finding.
2070    #[serde(flatten)]
2071    pub event: UnusedSvelteEvent,
2072    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2073    /// `~<k>` suffix when several findings of one type share an identity.
2074    /// Line and column are not inputs, so the id survives line shifts,
2075    /// reformats and reorders. A rename of the file or the symbol gives a
2076    /// new id. Absent in output from older versions.
2077    #[serde(default, skip_serializing_if = "Option::is_none")]
2078    pub finding_id: Option<String>,
2079    /// Suggested next steps. Always emitted (possibly empty for
2080    /// forward-compat).
2081    pub actions: Vec<IssueAction>,
2082    /// Set by the audit pass when this finding is introduced relative to
2083    /// the merge-base.
2084    #[serde(default, skip_serializing_if = "Option::is_none")]
2085    pub introduced: Option<AuditIntroduced>,
2086    /// Gate severity of this finding after `rules` and `overrides[].rules`
2087    /// resolve for its path. CI formats read it for the annotation, SARIF
2088    /// and CodeClimate level. Absent in output from older versions. Not
2089    /// part of the finding identity, baseline keys or fingerprints.
2090    #[serde(
2091        default,
2092        skip_serializing_if = "Option::is_none",
2093        deserialize_with = "deserialize_effective_severity"
2094    )]
2095    pub effective_severity: Option<EffectiveSeverity>,
2096}
2097
2098impl UnusedSvelteEventFinding {
2099    /// Build the wrapper from a raw [`UnusedSvelteEvent`]. Emits a manual fix
2100    /// action plus a line-level suppress.
2101    #[must_use]
2102    pub fn with_actions(event: UnusedSvelteEvent) -> Self {
2103        let actions = vec![
2104            manual_framework_fix(
2105                FixActionType::WireSvelteEvent,
2106                "Add or forward a listener for this custom event, or remove the dispatch",
2107                "Manual review required: public Svelte component APIs can intentionally dispatch events for package consumers outside this project.",
2108            ),
2109            suppress_line("// fallow-ignore-next-line unused-svelte-event"),
2110        ];
2111        Self {
2112            finding_id: None,
2113            event,
2114            actions,
2115            introduced: None,
2116            effective_severity: None,
2117        }
2118    }
2119}
2120
2121/// Wire-shape envelope for a [`DuplicateExportAlias`] finding. There is no
2122/// safe auto-fix: a consumer outside the project can import any of the
2123/// names. Actions are manual remediation guidance plus a line-level
2124/// suppress.
2125#[derive(Debug, Clone, Serialize, Deserialize)]
2126#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2127pub struct DuplicateExportAliasFinding {
2128    /// The underlying finding.
2129    #[serde(flatten)]
2130    pub alias: DuplicateExportAlias,
2131    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2132    /// `~<k>` suffix when several findings of one type share an identity.
2133    /// Line and column are not inputs, so the id survives line shifts,
2134    /// reformats and reorders. A rename of the file or the binding gives a
2135    /// new id. Absent in output from older versions.
2136    #[serde(default, skip_serializing_if = "Option::is_none")]
2137    pub finding_id: Option<String>,
2138    /// Suggested next steps. Always emitted (possibly empty for
2139    /// forward-compat).
2140    pub actions: Vec<IssueAction>,
2141    /// Set by the audit pass when this finding is introduced relative to
2142    /// the merge-base.
2143    #[serde(default, skip_serializing_if = "Option::is_none")]
2144    pub introduced: Option<AuditIntroduced>,
2145    /// Gate severity of this finding after `rules` and `overrides[].rules`
2146    /// resolve for its path. CI formats read it for the annotation, SARIF
2147    /// and CodeClimate level. Absent in output from older versions. Not
2148    /// part of the finding identity, baseline keys or fingerprints.
2149    #[serde(
2150        default,
2151        skip_serializing_if = "Option::is_none",
2152        deserialize_with = "deserialize_effective_severity"
2153    )]
2154    pub effective_severity: Option<EffectiveSeverity>,
2155}
2156
2157impl DuplicateExportAliasFinding {
2158    /// Build the wrapper from a raw [`DuplicateExportAlias`]. Emits a manual
2159    /// fix action plus a line-level suppress.
2160    #[must_use]
2161    pub fn with_actions(alias: DuplicateExportAlias) -> Self {
2162        let actions = vec![
2163            manual_framework_fix(
2164                FixActionType::RemoveDuplicate,
2165                "Keep one export name for the binding and remove the other names",
2166                "Manual review required: update the importers of a removed name first. Code outside the analyzed project can import any of the names. If the names are an intentional public API, add them to ignoreExports.",
2167            ),
2168            suppress_line("// fallow-ignore-next-line duplicate-export-alias"),
2169        ];
2170        Self {
2171            finding_id: None,
2172            alias,
2173            actions,
2174            introduced: None,
2175            effective_severity: None,
2176        }
2177    }
2178}
2179
2180/// Wire-shape envelope for an [`UnusedEffectLayer`] finding. There is no safe auto-fix: a test or a script outside the project graph can still use the layer. Actions are manual
2181/// remediation guidance plus a line-level suppress.
2182#[derive(Debug, Clone, Serialize, Deserialize)]
2183#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2184pub struct UnusedEffectLayerFinding {
2185    /// The underlying finding.
2186    #[serde(flatten)]
2187    pub layer: UnusedEffectLayer,
2188    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2189    /// `~<k>` suffix when several findings of one type share an identity.
2190    /// Line and column are not inputs, so the id survives line shifts,
2191    /// reformats and reorders. A rename of the file or the symbol gives a
2192    /// new id. Absent in output from older versions.
2193    #[serde(default, skip_serializing_if = "Option::is_none")]
2194    pub finding_id: Option<String>,
2195    /// Suggested next steps. Always emitted (possibly empty for
2196    /// forward-compat).
2197    pub actions: Vec<IssueAction>,
2198    /// Set by the audit pass when this finding is introduced relative to
2199    /// the merge-base.
2200    #[serde(default, skip_serializing_if = "Option::is_none")]
2201    pub introduced: Option<AuditIntroduced>,
2202    /// Gate severity of this finding after `rules` and `overrides[].rules`
2203    /// resolve for its path. CI formats read it for the annotation, SARIF
2204    /// and CodeClimate level. Absent in output from older versions. Not
2205    /// part of the finding identity, baseline keys or fingerprints.
2206    #[serde(
2207        default,
2208        skip_serializing_if = "Option::is_none",
2209        deserialize_with = "deserialize_effective_severity"
2210    )]
2211    pub effective_severity: Option<EffectiveSeverity>,
2212}
2213
2214impl UnusedEffectLayerFinding {
2215    /// Build the wrapper from a raw [`UnusedEffectLayer`]. Emits a manual fix action plus
2216    /// a line-level suppress.
2217    #[must_use]
2218    pub fn with_actions(layer: UnusedEffectLayer) -> Self {
2219        let actions = vec![
2220            manual_framework_fix(
2221                FixActionType::ComposeEffectLayer,
2222                "Compose the layer into a layer that reaches a runtime, or remove it with its unused consumers",
2223                "Manual review required: remove the unused consumer layers first, then this layer. Code outside the analyzed project can still compose it.",
2224            ),
2225            suppress_line("// fallow-ignore-next-line unused-effect-layer"),
2226        ];
2227        Self {
2228            finding_id: None,
2229            layer,
2230            actions,
2231            introduced: None,
2232            effective_severity: None,
2233        }
2234    }
2235}
2236
2237/// Wire-shape envelope for an [`UnusedTaggedError`] finding. There is no safe auto-fix: the error can be part of a public API contract. Actions are manual
2238/// remediation guidance plus a line-level suppress.
2239#[derive(Debug, Clone, Serialize, Deserialize)]
2240#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2241pub struct UnusedTaggedErrorFinding {
2242    /// The underlying finding.
2243    #[serde(flatten)]
2244    pub error: UnusedTaggedError,
2245    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2246    /// `~<k>` suffix when several findings of one type share an identity.
2247    /// Line and column are not inputs, so the id survives line shifts,
2248    /// reformats and reorders. A rename of the file or the symbol gives a
2249    /// new id. Absent in output from older versions.
2250    #[serde(default, skip_serializing_if = "Option::is_none")]
2251    pub finding_id: Option<String>,
2252    /// Suggested next steps. Always emitted (possibly empty for
2253    /// forward-compat).
2254    pub actions: Vec<IssueAction>,
2255    /// Set by the audit pass when this finding is introduced relative to
2256    /// the merge-base.
2257    #[serde(default, skip_serializing_if = "Option::is_none")]
2258    pub introduced: Option<AuditIntroduced>,
2259    /// Gate severity of this finding after `rules` and `overrides[].rules`
2260    /// resolve for its path. CI formats read it for the annotation, SARIF
2261    /// and CodeClimate level. Absent in output from older versions. Not
2262    /// part of the finding identity, baseline keys or fingerprints.
2263    #[serde(
2264        default,
2265        skip_serializing_if = "Option::is_none",
2266        deserialize_with = "deserialize_effective_severity"
2267    )]
2268    pub effective_severity: Option<EffectiveSeverity>,
2269}
2270
2271impl UnusedTaggedErrorFinding {
2272    /// Build the wrapper from a raw [`UnusedTaggedError`]. Emits a manual fix action plus
2273    /// a line-level suppress.
2274    #[must_use]
2275    pub fn with_actions(error: UnusedTaggedError) -> Self {
2276        let actions = vec![
2277            manual_framework_fix(
2278                FixActionType::FailTaggedError,
2279                "Fail with this error where the condition occurs, or remove the class and its catchTag handlers",
2280                "Manual review required: consumers outside the analyzed project can construct or decode the error.",
2281            ),
2282            suppress_line("// fallow-ignore-next-line unused-tagged-error"),
2283        ];
2284        Self {
2285            finding_id: None,
2286            error,
2287            actions,
2288            introduced: None,
2289            effective_severity: None,
2290        }
2291    }
2292}
2293
2294/// Wire-shape envelope for an [`UnproducedCatchTag`] finding. There is no safe auto-fix: the handler can guard against a future producer. Actions are manual
2295/// remediation guidance plus a line-level suppress.
2296#[derive(Debug, Clone, Serialize, Deserialize)]
2297#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2298pub struct UnproducedCatchTagFinding {
2299    /// The underlying finding.
2300    #[serde(flatten)]
2301    pub catch_tag: UnproducedCatchTag,
2302    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2303    /// `~<k>` suffix when several findings of one type share an identity.
2304    /// Line and column are not inputs, so the id survives line shifts,
2305    /// reformats and reorders. A rename of the file or the symbol gives a
2306    /// new id. Absent in output from older versions.
2307    #[serde(default, skip_serializing_if = "Option::is_none")]
2308    pub finding_id: Option<String>,
2309    /// Suggested next steps. Always emitted (possibly empty for
2310    /// forward-compat).
2311    pub actions: Vec<IssueAction>,
2312    /// Set by the audit pass when this finding is introduced relative to
2313    /// the merge-base.
2314    #[serde(default, skip_serializing_if = "Option::is_none")]
2315    pub introduced: Option<AuditIntroduced>,
2316    /// Gate severity of this finding after `rules` and `overrides[].rules`
2317    /// resolve for its path. CI formats read it for the annotation, SARIF
2318    /// and CodeClimate level. Absent in output from older versions. Not
2319    /// part of the finding identity, baseline keys or fingerprints.
2320    #[serde(
2321        default,
2322        skip_serializing_if = "Option::is_none",
2323        deserialize_with = "deserialize_effective_severity"
2324    )]
2325    pub effective_severity: Option<EffectiveSeverity>,
2326}
2327
2328impl UnproducedCatchTagFinding {
2329    /// Build the wrapper from a raw [`UnproducedCatchTag`]. Emits a manual fix action plus
2330    /// a line-level suppress.
2331    #[must_use]
2332    pub fn with_actions(catch_tag: UnproducedCatchTag) -> Self {
2333        let actions = vec![
2334            manual_framework_fix(
2335                FixActionType::RemoveCatchTagHandler,
2336                "Remove the handler for this tag, or fail with the error where the condition occurs",
2337                "Manual review required: a package or code outside the analyzed project can produce the tag.",
2338            ),
2339            suppress_line("// fallow-ignore-next-line unproduced-catch-tag"),
2340        ];
2341        Self {
2342            finding_id: None,
2343            catch_tag,
2344            actions,
2345            introduced: None,
2346            effective_severity: None,
2347        }
2348    }
2349}
2350
2351/// Wire-shape envelope for a [`PropDrillingChain`] finding. There is no safe
2352/// auto-fix: collapsing a drilling chain (colocate the consumer, lift to a
2353/// context, or compose the component) is a design decision. The only action is a
2354/// line-level suppress at the source hop's prop declaration. The rule defaults
2355/// to `off` (opt-in health signal), so this finding is dormant by default.
2356#[derive(Debug, Clone, Serialize, Deserialize)]
2357#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2358pub struct PropDrillingChainFinding {
2359    /// The underlying located chain.
2360    #[serde(flatten)]
2361    pub chain: PropDrillingChain,
2362    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2363    /// `~<k>` suffix when several findings of one type share an identity.
2364    /// Line and column are not inputs, so the id survives line shifts,
2365    /// reformats and reorders. A rename of the file or the symbol gives a
2366    /// new id. Absent in output from older versions.
2367    #[serde(default, skip_serializing_if = "Option::is_none")]
2368    pub finding_id: Option<String>,
2369    /// Suggested next steps. Always emitted (possibly empty for
2370    /// forward-compat).
2371    pub actions: Vec<IssueAction>,
2372    /// Set by the audit pass when this finding is introduced relative to
2373    /// the merge-base.
2374    #[serde(default, skip_serializing_if = "Option::is_none")]
2375    pub introduced: Option<AuditIntroduced>,
2376    /// Rule severity after resolving overrides for the source hop. An explicit
2377    /// `error` enforces the chain; `warn` stays advisory under strict flags.
2378    /// Saved reports use this value for CI levels. Absent in older output.
2379    /// Not part of finding identity, baseline keys or fingerprints.
2380    #[serde(
2381        default,
2382        skip_serializing_if = "Option::is_none",
2383        deserialize_with = "deserialize_effective_severity"
2384    )]
2385    pub effective_severity: Option<EffectiveSeverity>,
2386}
2387
2388impl PropDrillingChainFinding {
2389    /// Build the wrapper from a raw [`PropDrillingChain`]. Emits only a
2390    /// line-level suppress action anchored at the source hop: there is no safe
2391    /// auto-fix because collapsing the chain is a design decision (colocate,
2392    /// lift to context, or compose).
2393    #[must_use]
2394    pub fn with_actions(chain: PropDrillingChain) -> Self {
2395        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2396            kind: SuppressLineKind::SuppressLine,
2397            auto_fixable: false,
2398            description: "Suppress with an inline comment above the source prop declaration"
2399                .to_string(),
2400            comment: "// fallow-ignore-next-line prop-drilling".to_string(),
2401            scope: None,
2402        })];
2403        Self {
2404            finding_id: None,
2405            chain,
2406            actions,
2407            introduced: None,
2408            effective_severity: None,
2409        }
2410    }
2411}
2412
2413/// Wire-shape envelope for a [`ThinWrapper`] finding. There is no safe
2414/// auto-fix: inlining a thin wrapper at its call sites (or deleting it) is a
2415/// design decision. The only action is a line-level suppress at the wrapper's
2416/// definition. The rule defaults to `off` (opt-in health signal), so this
2417/// finding is dormant by default.
2418#[derive(Debug, Clone, Serialize, Deserialize)]
2419#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2420pub struct ThinWrapperFinding {
2421    /// The underlying located thin wrapper.
2422    #[serde(flatten)]
2423    pub wrapper: ThinWrapper,
2424    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2425    /// `~<k>` suffix when several findings of one type share an identity.
2426    /// Line and column are not inputs, so the id survives line shifts,
2427    /// reformats and reorders. A rename of the file or the symbol gives a
2428    /// new id. Absent in output from older versions.
2429    #[serde(default, skip_serializing_if = "Option::is_none")]
2430    pub finding_id: Option<String>,
2431    /// Suggested next steps. Always emitted (possibly empty for
2432    /// forward-compat).
2433    pub actions: Vec<IssueAction>,
2434    /// Set by the audit pass when this finding is introduced relative to
2435    /// the merge-base.
2436    #[serde(default, skip_serializing_if = "Option::is_none")]
2437    pub introduced: Option<AuditIntroduced>,
2438    /// Rule severity of this finding. Explicit errors enforce analysis gates;
2439    /// warnings stay advisory, including under strict flags. Saved reports
2440    /// retain this value for CI levels without the original config. Absent
2441    /// in output from older versions. Not part of finding identity, baseline
2442    /// keys or fingerprints.
2443    #[serde(
2444        default,
2445        skip_serializing_if = "Option::is_none",
2446        deserialize_with = "deserialize_effective_severity"
2447    )]
2448    pub effective_severity: Option<EffectiveSeverity>,
2449}
2450
2451impl ThinWrapperFinding {
2452    /// Build the wrapper from a raw [`ThinWrapper`]. Emits only a line-level
2453    /// suppress action anchored at the wrapper definition: there is no safe
2454    /// auto-fix because inlining or deleting the wrapper is a design decision.
2455    #[must_use]
2456    pub fn with_actions(wrapper: ThinWrapper) -> Self {
2457        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2458            kind: SuppressLineKind::SuppressLine,
2459            auto_fixable: false,
2460            description: "Suppress with an inline comment above the component definition"
2461                .to_string(),
2462            comment: "// fallow-ignore-next-line thin-wrapper".to_string(),
2463            scope: None,
2464        })];
2465        Self {
2466            finding_id: None,
2467            wrapper,
2468            actions,
2469            introduced: None,
2470            effective_severity: None,
2471        }
2472    }
2473}
2474
2475/// Wire-shape envelope for a [`DuplicatePropShape`] finding. There is no safe
2476/// auto-fix: extracting a shared `Props` type or a base component for a group of
2477/// same-shaped components is a design decision. The actions are manual guidance
2478/// (extract the shared shape) plus a line-level suppress at the component
2479/// definition and a file-level suppress escape hatch (mirroring the
2480/// route-collision multi-file model). The rule defaults to `off` (opt-in health
2481/// signal), so this finding is dormant by default.
2482#[derive(Debug, Clone, Serialize, Deserialize)]
2483#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2484pub struct DuplicatePropShapeFinding {
2485    /// The underlying duplicate-prop-shape entry.
2486    #[serde(flatten)]
2487    pub shape: DuplicatePropShape,
2488    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2489    /// `~<k>` suffix when several findings of one type share an identity.
2490    /// Line and column are not inputs, so the id survives line shifts,
2491    /// reformats and reorders. A rename of the file or the symbol gives a
2492    /// new id. Absent in output from older versions.
2493    #[serde(default, skip_serializing_if = "Option::is_none")]
2494    pub finding_id: Option<String>,
2495    /// Suggested next steps. Always emitted (possibly empty for
2496    /// forward-compat).
2497    pub actions: Vec<IssueAction>,
2498    /// Set by the audit pass when this finding is introduced relative to
2499    /// the merge-base.
2500    #[serde(default, skip_serializing_if = "Option::is_none")]
2501    pub introduced: Option<AuditIntroduced>,
2502    /// Rule severity of this finding. Explicit errors enforce analysis gates;
2503    /// warnings stay advisory, including under strict flags. Saved reports
2504    /// retain this value for CI levels without the original config. Absent
2505    /// in output from older versions. Not part of finding identity, baseline
2506    /// keys or fingerprints.
2507    #[serde(
2508        default,
2509        skip_serializing_if = "Option::is_none",
2510        deserialize_with = "deserialize_effective_severity"
2511    )]
2512    pub effective_severity: Option<EffectiveSeverity>,
2513}
2514
2515impl DuplicatePropShapeFinding {
2516    /// Build the wrapper from a raw [`DuplicatePropShape`]. Manual guidance is
2517    /// the primary action (extract a shared shape); a line-level suppress at the
2518    /// component definition and a file-level suppress escape hatch follow,
2519    /// mirroring the multi-file route-collision suppress model. There is no safe
2520    /// auto-fix because extracting a shared type or base component is a design
2521    /// decision.
2522    #[must_use]
2523    pub fn with_actions(shape: DuplicatePropShape) -> Self {
2524        let actions = vec![
2525            IssueAction::SuppressLine(SuppressLineAction {
2526                kind: SuppressLineKind::SuppressLine,
2527                auto_fixable: false,
2528                description: "Three or more components share this exact prop shape. Extract one \
2529                              shared `Props` type (or a base component) that every member reuses, \
2530                              or keep them separate if a per-variant divergence is planned. \
2531                              Suppress one member with an inline comment above the component \
2532                              definition."
2533                    .to_string(),
2534                comment: "// fallow-ignore-next-line duplicate-prop-shape".to_string(),
2535                scope: None,
2536            }),
2537            IssueAction::SuppressFile(SuppressFileAction {
2538                kind: SuppressFileKind::SuppressFile,
2539                auto_fixable: false,
2540                description: "Escape hatch: a file-level suppress silences this member but it \
2541                              still appears in its siblings' `sharing_components` (the group is \
2542                              real regardless of suppression)."
2543                    .to_string(),
2544                comment: "// fallow-ignore-file duplicate-prop-shape".to_string(),
2545            }),
2546        ];
2547        Self {
2548            finding_id: None,
2549            shape,
2550            actions,
2551            introduced: None,
2552            effective_severity: None,
2553        }
2554    }
2555}
2556
2557/// Wire-shape envelope for an [`UnusedComponentInput`] finding. There is no safe
2558/// auto-fix: removing a declared input is judgement-bearing (the input may be
2559/// part of a deliberately-stable public component API). The only action is a
2560/// line-level suppress at the input declaration.
2561#[derive(Debug, Clone, Serialize, Deserialize)]
2562#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2563pub struct UnusedComponentInputFinding {
2564    /// The underlying finding.
2565    #[serde(flatten)]
2566    pub input: UnusedComponentInput,
2567    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2568    /// `~<k>` suffix when several findings of one type share an identity.
2569    /// Line and column are not inputs, so the id survives line shifts,
2570    /// reformats and reorders. A rename of the file or the symbol gives a
2571    /// new id. Absent in output from older versions.
2572    #[serde(default, skip_serializing_if = "Option::is_none")]
2573    pub finding_id: Option<String>,
2574    /// Suggested next steps. Always emitted (possibly empty for
2575    /// forward-compat).
2576    pub actions: Vec<IssueAction>,
2577    /// Set by the audit pass when this finding is introduced relative to
2578    /// the merge-base.
2579    #[serde(default, skip_serializing_if = "Option::is_none")]
2580    pub introduced: Option<AuditIntroduced>,
2581    /// Gate severity of this finding after `rules` and `overrides[].rules`
2582    /// resolve for its path. CI formats read it for the annotation, SARIF
2583    /// and CodeClimate level. Absent in output from older versions. Not
2584    /// part of the finding identity, baseline keys or fingerprints.
2585    #[serde(
2586        default,
2587        skip_serializing_if = "Option::is_none",
2588        deserialize_with = "deserialize_effective_severity"
2589    )]
2590    pub effective_severity: Option<EffectiveSeverity>,
2591}
2592
2593impl UnusedComponentInputFinding {
2594    /// Build the wrapper from a raw [`UnusedComponentInput`]. Emits only a
2595    /// line-level suppress action: there is no safe auto-fix because removing an
2596    /// input is a human decision (it may be part of a stable component API).
2597    #[must_use]
2598    pub fn with_actions(input: UnusedComponentInput) -> Self {
2599        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2600            kind: SuppressLineKind::SuppressLine,
2601            auto_fixable: false,
2602            description: "Suppress with an inline comment above the line".to_string(),
2603            comment: "// fallow-ignore-next-line unused-component-input".to_string(),
2604            scope: None,
2605        })];
2606        Self {
2607            finding_id: None,
2608            input,
2609            actions,
2610            introduced: None,
2611            effective_severity: None,
2612        }
2613    }
2614}
2615
2616/// Wire-shape envelope for an [`UnusedComponentOutput`] finding. There is no safe
2617/// auto-fix: removing a declared output is judgement-bearing (the event may be
2618/// part of a deliberately-stable public component API). The only action is a
2619/// line-level suppress at the output declaration.
2620#[derive(Debug, Clone, Serialize, Deserialize)]
2621#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2622pub struct UnusedComponentOutputFinding {
2623    /// The underlying finding.
2624    #[serde(flatten)]
2625    pub output: UnusedComponentOutput,
2626    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2627    /// `~<k>` suffix when several findings of one type share an identity.
2628    /// Line and column are not inputs, so the id survives line shifts,
2629    /// reformats and reorders. A rename of the file or the symbol gives a
2630    /// new id. Absent in output from older versions.
2631    #[serde(default, skip_serializing_if = "Option::is_none")]
2632    pub finding_id: Option<String>,
2633    /// Suggested next steps. Always emitted (possibly empty for
2634    /// forward-compat).
2635    pub actions: Vec<IssueAction>,
2636    /// Set by the audit pass when this finding is introduced relative to
2637    /// the merge-base.
2638    #[serde(default, skip_serializing_if = "Option::is_none")]
2639    pub introduced: Option<AuditIntroduced>,
2640    /// Gate severity of this finding after `rules` and `overrides[].rules`
2641    /// resolve for its path. CI formats read it for the annotation, SARIF
2642    /// and CodeClimate level. Absent in output from older versions. Not
2643    /// part of the finding identity, baseline keys or fingerprints.
2644    #[serde(
2645        default,
2646        skip_serializing_if = "Option::is_none",
2647        deserialize_with = "deserialize_effective_severity"
2648    )]
2649    pub effective_severity: Option<EffectiveSeverity>,
2650}
2651
2652impl UnusedComponentOutputFinding {
2653    /// Build the wrapper from a raw [`UnusedComponentOutput`]. Emits only a
2654    /// line-level suppress action: there is no safe auto-fix because removing an
2655    /// output is a human decision (it may be part of a stable component API).
2656    #[must_use]
2657    pub fn with_actions(output: UnusedComponentOutput) -> Self {
2658        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2659            kind: SuppressLineKind::SuppressLine,
2660            auto_fixable: false,
2661            description: "Suppress with an inline comment above the line".to_string(),
2662            comment: "// fallow-ignore-next-line unused-component-output".to_string(),
2663            scope: None,
2664        })];
2665        Self {
2666            finding_id: None,
2667            output,
2668            actions,
2669            introduced: None,
2670            effective_severity: None,
2671        }
2672    }
2673}
2674
2675/// Wire-shape envelope for a [`RouteCollision`] finding. A route collision is a
2676/// guaranteed `next build` failure, so the primary action is manual guidance
2677/// (move or merge one of the colliding files), NOT a suppress: suppressing a
2678/// build error never makes the build pass. A file-level suppress is offered as
2679/// an escape hatch only.
2680#[derive(Debug, Clone, Serialize, Deserialize)]
2681#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2682pub struct RouteCollisionFinding {
2683    /// The underlying route-collision entry.
2684    #[serde(flatten)]
2685    pub collision: RouteCollision,
2686    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2687    /// `~<k>` suffix when several findings of one type share an identity.
2688    /// Line and column are not inputs, so the id survives line shifts,
2689    /// reformats and reorders. A rename of the file or the symbol gives a
2690    /// new id. Absent in output from older versions.
2691    #[serde(default, skip_serializing_if = "Option::is_none")]
2692    pub finding_id: Option<String>,
2693    /// Suggested next steps. Always emitted (possibly empty for
2694    /// forward-compat).
2695    pub actions: Vec<IssueAction>,
2696    /// Set by the audit pass when this finding is introduced relative to
2697    /// the merge-base.
2698    #[serde(default, skip_serializing_if = "Option::is_none")]
2699    pub introduced: Option<AuditIntroduced>,
2700    /// Gate severity of this finding after `rules` and `overrides[].rules`
2701    /// resolve for its path. CI formats read it for the annotation, SARIF
2702    /// and CodeClimate level. Absent in output from older versions. Not
2703    /// part of the finding identity, baseline keys or fingerprints.
2704    #[serde(
2705        default,
2706        skip_serializing_if = "Option::is_none",
2707        deserialize_with = "deserialize_effective_severity"
2708    )]
2709    pub effective_severity: Option<EffectiveSeverity>,
2710}
2711
2712impl RouteCollisionFinding {
2713    /// Build the wrapper from a raw [`RouteCollision`]. The primary action is
2714    /// manual guidance because suppressing a guaranteed build error is never
2715    /// the right fix; a file-level suppress is the escape hatch only.
2716    #[must_use]
2717    pub fn with_actions(collision: RouteCollision) -> Self {
2718        let actions = vec![
2719            IssueAction::Fix(FixAction {
2720                kind: FixActionType::ResolveRouteCollision,
2721                auto_fixable: false,
2722                description: "Two or more files resolve to the same URL. Move or merge one so \
2723                              each URL has a single owner. Route groups `(name)` and parallel \
2724                              slots `@name` are the only legal same-URL shapes."
2725                    .to_string(),
2726                note: Some(
2727                    "Next.js fails the build with \"You cannot have two parallel pages that \
2728                     resolve to the same path\". See the sibling `conflicting_paths` array for \
2729                     the other files that own this URL."
2730                        .to_string(),
2731                ),
2732                available_in_catalogs: None,
2733                suggested_target: None,
2734            }),
2735            IssueAction::SuppressFile(SuppressFileAction {
2736                kind: SuppressFileKind::SuppressFile,
2737                auto_fixable: false,
2738                description: "Escape hatch only: a file-level suppress silences the finding but \
2739                              does NOT make `next build` pass. Prefer moving or merging a file."
2740                    .to_string(),
2741                comment: "// fallow-ignore-file route-collision".to_string(),
2742            }),
2743        ];
2744        Self {
2745            finding_id: None,
2746            collision,
2747            actions,
2748            introduced: None,
2749            effective_severity: None,
2750        }
2751    }
2752}
2753
2754/// Wire-shape envelope for a [`DynamicSegmentNameConflict`] finding. The
2755/// conflict is a Next.js dev / runtime error (`next build` does NOT catch it),
2756/// so the primary action is manual guidance (rename the dynamic segments to a
2757/// single consistent slug name), with a file-level suppress as escape hatch.
2758#[derive(Debug, Clone, Serialize, Deserialize)]
2759#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2760pub struct DynamicSegmentNameConflictFinding {
2761    /// The underlying dynamic-segment-name-conflict entry.
2762    #[serde(flatten)]
2763    pub conflict: DynamicSegmentNameConflict,
2764    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2765    /// `~<k>` suffix when several findings of one type share an identity.
2766    /// Line and column are not inputs, so the id survives line shifts,
2767    /// reformats and reorders. A rename of the file or the symbol gives a
2768    /// new id. Absent in output from older versions.
2769    #[serde(default, skip_serializing_if = "Option::is_none")]
2770    pub finding_id: Option<String>,
2771    /// Suggested next steps. Always emitted (possibly empty for
2772    /// forward-compat).
2773    pub actions: Vec<IssueAction>,
2774    /// Set by the audit pass when this finding is introduced relative to
2775    /// the merge-base.
2776    #[serde(default, skip_serializing_if = "Option::is_none")]
2777    pub introduced: Option<AuditIntroduced>,
2778    /// Gate severity of this finding after `rules` and `overrides[].rules`
2779    /// resolve for its path. CI formats read it for the annotation, SARIF
2780    /// and CodeClimate level. Absent in output from older versions. Not
2781    /// part of the finding identity, baseline keys or fingerprints.
2782    #[serde(
2783        default,
2784        skip_serializing_if = "Option::is_none",
2785        deserialize_with = "deserialize_effective_severity"
2786    )]
2787    pub effective_severity: Option<EffectiveSeverity>,
2788}
2789
2790impl DynamicSegmentNameConflictFinding {
2791    /// Build the wrapper from a raw [`DynamicSegmentNameConflict`]. Manual
2792    /// guidance primary action; file-level suppress escape hatch only.
2793    #[must_use]
2794    pub fn with_actions(conflict: DynamicSegmentNameConflict) -> Self {
2795        let actions = vec![
2796            IssueAction::Fix(FixAction {
2797                kind: FixActionType::ResolveDynamicSegmentNameConflict,
2798                auto_fixable: false,
2799                description: "Sibling dynamic segments at the same position use different param \
2800                              names. Rename them to one consistent slug name (e.g. pick `[id]` \
2801                              or `[slug]` for both)."
2802                    .to_string(),
2803                note: Some(
2804                    "Next.js throws \"You cannot use different slug names for the same dynamic \
2805                     path\" at dev / runtime when the position is hit; `next build` does not \
2806                     catch it. See the sibling `conflicting_segments` array."
2807                        .to_string(),
2808                ),
2809                available_in_catalogs: None,
2810                suggested_target: None,
2811            }),
2812            IssueAction::SuppressFile(SuppressFileAction {
2813                kind: SuppressFileKind::SuppressFile,
2814                auto_fixable: false,
2815                description: "Escape hatch only: a file-level suppress silences the finding but \
2816                              does NOT stop Next.js from throwing at dev / runtime. Prefer \
2817                              renaming the segments."
2818                    .to_string(),
2819                comment: "// fallow-ignore-file dynamic-segment-name-conflict".to_string(),
2820            }),
2821        ];
2822        Self {
2823            finding_id: None,
2824            conflict,
2825            actions,
2826            introduced: None,
2827            effective_severity: None,
2828        }
2829    }
2830}
2831
2832/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
2833/// `unused_enum_members` key.
2834#[derive(Debug, Clone, Serialize, Deserialize)]
2835#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2836pub struct UnusedEnumMemberFinding {
2837    /// The underlying dead-code entry.
2838    #[serde(flatten)]
2839    pub member: UnusedMember,
2840    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2841    /// `~<k>` suffix when several findings of one type share an identity.
2842    /// Line and column are not inputs, so the id survives line shifts,
2843    /// reformats and reorders. A rename of the file or the symbol gives a
2844    /// new id. Absent in output from older versions.
2845    #[serde(default, skip_serializing_if = "Option::is_none")]
2846    pub finding_id: Option<String>,
2847    /// Suggested next steps. Always emitted (possibly empty for
2848    /// forward-compat).
2849    pub actions: Vec<IssueAction>,
2850    /// Set by the audit pass when this finding is introduced relative to
2851    /// the merge-base.
2852    #[serde(default, skip_serializing_if = "Option::is_none")]
2853    pub introduced: Option<AuditIntroduced>,
2854    /// Gate severity of this finding after `rules` and `overrides[].rules`
2855    /// resolve for its path. CI formats read it for the annotation, SARIF
2856    /// and CodeClimate level. Absent in output from older versions. Not
2857    /// part of the finding identity, baseline keys or fingerprints.
2858    #[serde(
2859        default,
2860        skip_serializing_if = "Option::is_none",
2861        deserialize_with = "deserialize_effective_severity"
2862    )]
2863    pub effective_severity: Option<EffectiveSeverity>,
2864    /// Advisory caveats on the verdict behind this finding. A member's usage
2865    /// is collected by walking the member accesses of every module the run
2866    /// parsed, so a member whose only reference lives in a file the run never
2867    /// read reads as unused exactly like an export does. Sorted,
2868    /// deduplicated, and omitted from the wire when empty. Never gates the
2869    /// finding; it does withhold the `remove-enum-member` mutation.
2870    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2871    pub reachability_caveats: Vec<ReachabilityCaveat>,
2872}
2873
2874impl UnusedEnumMemberFinding {
2875    /// Build the wrapper from a raw [`UnusedMember`].
2876    #[must_use]
2877    pub fn with_actions(member: UnusedMember) -> Self {
2878        let actions = vec![
2879            IssueAction::Fix(FixAction {
2880                kind: FixActionType::RemoveEnumMember,
2881                auto_fixable: true,
2882                description: "Remove this enum member".to_string(),
2883                note: None,
2884                available_in_catalogs: None,
2885                suggested_target: None,
2886            }),
2887            IssueAction::SuppressLine(SuppressLineAction {
2888                kind: SuppressLineKind::SuppressLine,
2889                auto_fixable: false,
2890                description: "Suppress with an inline comment above the line".to_string(),
2891                comment: "// fallow-ignore-next-line unused-enum-member".to_string(),
2892                scope: None,
2893            }),
2894        ];
2895        Self {
2896            finding_id: None,
2897            member,
2898            actions,
2899            introduced: None,
2900            effective_severity: None,
2901            reachability_caveats: Vec::new(),
2902        }
2903    }
2904}
2905
2906/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
2907/// `unused_class_members` key. Same Rust struct as
2908/// [`UnusedEnumMemberFinding`]; the fix action and suppress comment carry
2909/// the class-member kebab-case identifier instead.
2910#[derive(Debug, Clone, Serialize, Deserialize)]
2911#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2912pub struct UnusedClassMemberFinding {
2913    /// The underlying dead-code entry.
2914    #[serde(flatten)]
2915    pub member: UnusedMember,
2916    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2917    /// `~<k>` suffix when several findings of one type share an identity.
2918    /// Line and column are not inputs, so the id survives line shifts,
2919    /// reformats and reorders. A rename of the file or the symbol gives a
2920    /// new id. Absent in output from older versions.
2921    #[serde(default, skip_serializing_if = "Option::is_none")]
2922    pub finding_id: Option<String>,
2923    /// Suggested next steps. Always emitted (possibly empty for
2924    /// forward-compat).
2925    pub actions: Vec<IssueAction>,
2926    /// Type-aware evidence for this exact candidate when requested.
2927    #[serde(default, skip_serializing_if = "Option::is_none")]
2928    pub semantic: Option<SemanticCandidateDecision>,
2929    /// Internal marker for a framework member that the syntactic analysis
2930    /// suppresses, but the semantic pass may promote after proving complete
2931    /// closed-world absence. Never serialized as part of the public finding.
2932    #[serde(skip)]
2933    #[cfg_attr(feature = "schema", schemars(skip))]
2934    pub semantic_only_candidate: bool,
2935    /// Set by the audit pass when this finding is introduced relative to
2936    /// the merge-base.
2937    #[serde(default, skip_serializing_if = "Option::is_none")]
2938    pub introduced: Option<AuditIntroduced>,
2939    /// Gate severity of this finding after `rules` and `overrides[].rules`
2940    /// resolve for its path. CI formats read it for the annotation, SARIF
2941    /// and CodeClimate level. Absent in output from older versions. Not
2942    /// part of the finding identity, baseline keys or fingerprints.
2943    #[serde(
2944        default,
2945        skip_serializing_if = "Option::is_none",
2946        deserialize_with = "deserialize_effective_severity"
2947    )]
2948    pub effective_severity: Option<EffectiveSeverity>,
2949    /// Advisory caveats on the verdict behind this finding. A class member's
2950    /// usage is collected by the same reachability-free member-access walk an
2951    /// enum member's is, so it takes the enum-member rule unchanged: any module
2952    /// this run analyzed incompletely can hold the access that credits it.
2953    /// Sorted, deduplicated, and omitted from the wire when empty. Never gates
2954    /// the finding; it does withhold the `remove-class-member` mutation that
2955    /// the type-aware pass would otherwise open.
2956    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2957    pub reachability_caveats: Vec<ReachabilityCaveat>,
2958}
2959
2960impl UnusedClassMemberFinding {
2961    /// Build the wrapper from a raw [`UnusedMember`]. Class-member fixes
2962    /// are not auto-applied (members can be used via dependency injection
2963    /// or decorators), so `auto_fixable` is `false` and a context note is
2964    /// attached.
2965    #[must_use]
2966    pub fn with_actions(member: UnusedMember) -> Self {
2967        let actions = vec![
2968            IssueAction::Fix(FixAction {
2969                kind: FixActionType::RemoveClassMember,
2970                auto_fixable: false,
2971                description: "Remove this class member".to_string(),
2972                note: Some(
2973                    "Class member may be used via dependency injection or decorators".to_string(),
2974                ),
2975                available_in_catalogs: None,
2976                suggested_target: None,
2977            }),
2978            IssueAction::SuppressLine(SuppressLineAction {
2979                kind: SuppressLineKind::SuppressLine,
2980                auto_fixable: false,
2981                description: "Suppress with an inline comment above the line".to_string(),
2982                comment: "// fallow-ignore-next-line unused-class-member".to_string(),
2983                scope: None,
2984            }),
2985        ];
2986        Self {
2987            finding_id: None,
2988            member,
2989            actions,
2990            semantic: None,
2991            semantic_only_candidate: false,
2992            introduced: None,
2993            effective_severity: None,
2994            reachability_caveats: Vec::new(),
2995        }
2996    }
2997
2998    /// Mark this finding as latent until semantic analysis proves that the
2999    /// framework contract does not apply and no static references exist.
3000    #[must_use]
3001    pub const fn semantic_only_candidate(mut self) -> Self {
3002        self.semantic_only_candidate = true;
3003        self
3004    }
3005
3006    /// Attach the canonical semantic decision and expose the class-member fix
3007    /// only when the API policy granted closed-world eligibility AND this run
3008    /// holds the evidence for the mutation.
3009    ///
3010    /// This is the one code path that RAISES `auto_fixable` on a class member,
3011    /// and it runs in the API layer AFTER the analysis layer stamped the run's
3012    /// caveats, so it asks the gate for the same reason
3013    /// `set_export_semantic_action` does: a closed-world verdict computed
3014    /// over a program the run never fully read must not re-open a removal the
3015    /// incomplete run already withheld. The withheld note names the evidence
3016    /// gap rather than the semantic explanation, which stays readable on the
3017    /// finding's own `semantic` object.
3018    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
3019        let evidence_complete = self.reachability_caveats.is_empty();
3020        if let Some(IssueAction::Fix(action)) = self.actions.first_mut() {
3021            action.auto_fixable = decision.closed_world_eligible && evidence_complete;
3022            action.note = Some(if evidence_complete {
3023                decision.explanation.clone()
3024            } else {
3025                INCOMPLETE_EVIDENCE_NOTE.to_string()
3026            });
3027        }
3028        self.semantic = Some(decision);
3029    }
3030}
3031
3032/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
3033/// `unused_store_members` key (a Pinia `state` / `getters` / `actions` key, or
3034/// a setup-store returned key, declared but never accessed by any consumer
3035/// project-wide). Same Rust struct as [`UnusedClassMemberFinding`]. Emits only
3036/// a line-level suppress action: there is no safe auto-fix because a store
3037/// member can be accessed reflectively (a Pinia plugin, `store.$onAction`, or
3038/// dynamic dispatch) in ways syntactic analysis cannot see, so removal is a
3039/// behavioral change the user must own.
3040#[derive(Debug, Clone, Serialize, Deserialize)]
3041#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3042pub struct UnusedStoreMemberFinding {
3043    /// The underlying dead-code entry.
3044    #[serde(flatten)]
3045    pub member: UnusedMember,
3046    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3047    /// `~<k>` suffix when several findings of one type share an identity.
3048    /// Line and column are not inputs, so the id survives line shifts,
3049    /// reformats and reorders. A rename of the file or the symbol gives a
3050    /// new id. Absent in output from older versions.
3051    #[serde(default, skip_serializing_if = "Option::is_none")]
3052    pub finding_id: Option<String>,
3053    /// Suggested next steps. Always emitted (possibly empty for
3054    /// forward-compat).
3055    pub actions: Vec<IssueAction>,
3056    /// Set by the audit pass when this finding is introduced relative to
3057    /// the merge-base.
3058    #[serde(default, skip_serializing_if = "Option::is_none")]
3059    pub introduced: Option<AuditIntroduced>,
3060    /// Gate severity of this finding after `rules` and `overrides[].rules`
3061    /// resolve for its path. CI formats read it for the annotation, SARIF
3062    /// and CodeClimate level. Absent in output from older versions. Not
3063    /// part of the finding identity, baseline keys or fingerprints.
3064    #[serde(
3065        default,
3066        skip_serializing_if = "Option::is_none",
3067        deserialize_with = "deserialize_effective_severity"
3068    )]
3069    pub effective_severity: Option<EffectiveSeverity>,
3070    /// Advisory caveats on the verdict behind this finding. A store member's
3071    /// usage is collected by the same reachability-free member-access walk a
3072    /// class member's is, so it takes the member rule unchanged: any module
3073    /// this run analyzed incompletely can hold the access that credits it.
3074    /// Sorted, deduplicated, and omitted from the wire when empty. There is no
3075    /// mutation here to withhold, because a store member offers none on any
3076    /// surface; this is disclosure only, so a reader deciding by hand is told
3077    /// what the run did not see.
3078    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3079    pub reachability_caveats: Vec<ReachabilityCaveat>,
3080}
3081
3082impl UnusedStoreMemberFinding {
3083    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
3084    /// suppress action (no auto-fix: store members can be accessed
3085    /// reflectively, so removal is never provably safe).
3086    #[must_use]
3087    pub fn with_actions(member: UnusedMember) -> Self {
3088        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
3089            kind: SuppressLineKind::SuppressLine,
3090            auto_fixable: false,
3091            description: "Suppress with an inline comment above the line".to_string(),
3092            comment: "// fallow-ignore-next-line unused-store-member".to_string(),
3093            scope: None,
3094        })];
3095        Self {
3096            finding_id: None,
3097            member,
3098            actions,
3099            introduced: None,
3100            effective_severity: None,
3101            reachability_caveats: Vec::new(),
3102        }
3103    }
3104}
3105
3106/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
3107/// `unused_namespace_members` key (an exported member of an exported
3108/// TypeScript namespace that no code reads). `member_name` is the dotted path
3109/// from the exported namespace, for example `Inner.x`. Emits only a
3110/// line-level suppress action: a member can be a multi-line function, class
3111/// or nested namespace, so there is no safe one-line auto-fix.
3112#[derive(Debug, Clone, Serialize, Deserialize)]
3113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3114pub struct UnusedNamespaceMemberFinding {
3115    /// The underlying dead-code entry.
3116    #[serde(flatten)]
3117    pub member: UnusedMember,
3118    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3119    /// `~<k>` suffix when several findings of one type share an identity.
3120    /// Line and column are not inputs, so the id survives line shifts,
3121    /// reformats and reorders. A rename of the file or the symbol gives a
3122    /// new id. Absent in output from older versions.
3123    #[serde(default, skip_serializing_if = "Option::is_none")]
3124    pub finding_id: Option<String>,
3125    /// Suggested next steps. Always emitted (possibly empty for
3126    /// forward-compat).
3127    pub actions: Vec<IssueAction>,
3128    /// Set by the audit pass when this finding is introduced relative to
3129    /// the merge-base.
3130    #[serde(default, skip_serializing_if = "Option::is_none")]
3131    pub introduced: Option<AuditIntroduced>,
3132    /// Gate severity of this finding after `rules` and `overrides[].rules`
3133    /// resolve for its path. CI formats read it for the annotation, SARIF
3134    /// and CodeClimate level. Absent in output from older versions. Not
3135    /// part of the finding identity, baseline keys or fingerprints.
3136    #[serde(
3137        default,
3138        skip_serializing_if = "Option::is_none",
3139        deserialize_with = "deserialize_effective_severity"
3140    )]
3141    pub effective_severity: Option<EffectiveSeverity>,
3142    /// Advisory caveats on the verdict behind this finding. A namespace
3143    /// member takes the member rule unchanged: any module this run analyzed
3144    /// incompletely can hold the access that credits it. Sorted,
3145    /// deduplicated, and omitted from the wire when empty. This is disclosure
3146    /// only, because a namespace member offers no mutation.
3147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3148    pub reachability_caveats: Vec<ReachabilityCaveat>,
3149}
3150
3151impl UnusedNamespaceMemberFinding {
3152    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
3153    /// suppress action.
3154    #[must_use]
3155    pub fn with_actions(member: UnusedMember) -> Self {
3156        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
3157            kind: SuppressLineKind::SuppressLine,
3158            auto_fixable: false,
3159            description: "Suppress with an inline comment above the line".to_string(),
3160            comment: "// fallow-ignore-next-line unused-namespace-member".to_string(),
3161            scope: None,
3162        })];
3163        Self {
3164            finding_id: None,
3165            member,
3166            actions,
3167            introduced: None,
3168            effective_severity: None,
3169            reachability_caveats: Vec::new(),
3170        }
3171    }
3172}
3173
3174/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
3175/// `unused_protected_class_members` key (a `protected` class method or
3176/// property that neither its class nor a subclass reads). Emits only a
3177/// line-level suppress action: a subclass outside the project can read the
3178/// member, so removal is a decision for the user.
3179#[derive(Debug, Clone, Serialize, Deserialize)]
3180#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3181pub struct UnusedProtectedClassMemberFinding {
3182    /// The underlying dead-code entry.
3183    #[serde(flatten)]
3184    pub member: UnusedMember,
3185    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3186    /// `~<k>` suffix when several findings of one type share an identity.
3187    /// Line and column are not inputs, so the id survives line shifts,
3188    /// reformats and reorders. A rename of the file or the symbol gives a
3189    /// new id. Absent in output from older versions.
3190    #[serde(default, skip_serializing_if = "Option::is_none")]
3191    pub finding_id: Option<String>,
3192    /// Suggested next steps. Always emitted (possibly empty for
3193    /// forward-compat).
3194    pub actions: Vec<IssueAction>,
3195    /// Set by the audit pass when this finding is introduced relative to
3196    /// the merge-base.
3197    #[serde(default, skip_serializing_if = "Option::is_none")]
3198    pub introduced: Option<AuditIntroduced>,
3199    /// Gate severity of this finding after `rules` and `overrides[].rules`
3200    /// resolve for its path. CI formats read it for the annotation, SARIF
3201    /// and CodeClimate level. Absent in output from older versions. Not
3202    /// part of the finding identity, baseline keys or fingerprints.
3203    #[serde(
3204        default,
3205        skip_serializing_if = "Option::is_none",
3206        deserialize_with = "deserialize_effective_severity"
3207    )]
3208    pub effective_severity: Option<EffectiveSeverity>,
3209    /// Advisory caveats on the verdict behind this finding. A protected
3210    /// member takes the member rule unchanged: any module this run analyzed
3211    /// incompletely can hold the access that credits it. Sorted,
3212    /// deduplicated, and omitted from the wire when empty. This is disclosure
3213    /// only, because a protected member offers no mutation.
3214    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3215    pub reachability_caveats: Vec<ReachabilityCaveat>,
3216}
3217
3218impl UnusedProtectedClassMemberFinding {
3219    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
3220    /// suppress action.
3221    #[must_use]
3222    pub fn with_actions(member: UnusedMember) -> Self {
3223        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
3224            kind: SuppressLineKind::SuppressLine,
3225            auto_fixable: false,
3226            description: "Suppress with an inline comment above the line".to_string(),
3227            comment: "// fallow-ignore-next-line unused-protected-class-member".to_string(),
3228            scope: None,
3229        })];
3230        Self {
3231            finding_id: None,
3232            member,
3233            actions,
3234            introduced: None,
3235            effective_severity: None,
3236            reachability_caveats: Vec::new(),
3237        }
3238    }
3239}
3240
3241/// Build an `ignoreDependencies` config action for a package manifest finding.
3242fn build_ignore_dependencies_suppress_action(package_name: &str) -> IssueAction {
3243    IssueAction::AddToConfig(AddToConfigAction {
3244        kind: AddToConfigKind::AddToConfig,
3245        auto_fixable: false,
3246        description: format!("Add \"{package_name}\" to ignoreDependencies in fallow config"),
3247        config_key: "ignoreDependencies".to_string(),
3248        value: AddToConfigValue::Scalar(package_name.to_string()),
3249        value_schema: Some(
3250            "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencies/items"
3251                .to_string(),
3252        ),
3253    })
3254}
3255
3256/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3257/// the `unused_dependencies` key (production deps). Flattens the bare
3258/// finding; the typed `actions` array carries either a `remove-dependency`
3259/// or `move-dependency` primary depending on
3260/// `inner.used_in_workspaces`.
3261#[derive(Debug, Clone, Serialize, Deserialize)]
3262#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3263pub struct UnusedDependencyFinding {
3264    /// The underlying dead-code entry.
3265    #[serde(flatten)]
3266    pub dep: UnusedDependency,
3267    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3268    /// `~<k>` suffix when several findings of one type share an identity.
3269    /// Line and column are not inputs, so the id survives line shifts,
3270    /// reformats and reorders. A rename of the file or the symbol gives a
3271    /// new id. Absent in output from older versions.
3272    #[serde(default, skip_serializing_if = "Option::is_none")]
3273    pub finding_id: Option<String>,
3274    /// Suggested next steps. Always emitted (possibly empty for
3275    /// forward-compat).
3276    pub actions: Vec<IssueAction>,
3277    /// Set by the audit pass when this finding is introduced relative to
3278    /// the merge-base.
3279    #[serde(default, skip_serializing_if = "Option::is_none")]
3280    pub introduced: Option<AuditIntroduced>,
3281    /// Gate severity of this finding after `rules` and `overrides[].rules`
3282    /// resolve for its path. CI formats read it for the annotation, SARIF
3283    /// and CodeClimate level. Absent in output from older versions. Not
3284    /// part of the finding identity, baseline keys or fingerprints.
3285    #[serde(
3286        default,
3287        skip_serializing_if = "Option::is_none",
3288        deserialize_with = "deserialize_effective_severity"
3289    )]
3290    pub effective_severity: Option<EffectiveSeverity>,
3291    /// Advisory caveats on the verdict behind this finding. A dependency is
3292    /// reported unused when NO module in the project imports its specifier,
3293    /// so a module that parsed with errors can hide the import that would
3294    /// have credited the package. Sorted, deduplicated, and omitted from the
3295    /// wire when empty. Never gates the finding, though `fallow fix`
3296    /// withholds the `remove-dependency` write while a caveat stands.
3297    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3298    pub reachability_caveats: Vec<ReachabilityCaveat>,
3299}
3300
3301impl UnusedDependencyFinding {
3302    /// Build the wrapper. Switches the primary fix from `remove-dependency`
3303    /// to `move-dependency` when the dep is imported by another workspace.
3304    #[must_use]
3305    pub fn with_actions(dep: UnusedDependency) -> Self {
3306        let actions = build_unused_dependency_actions(&dep, "dependencies");
3307        Self {
3308            finding_id: None,
3309            dep,
3310            actions,
3311            introduced: None,
3312            effective_severity: None,
3313            reachability_caveats: Vec::new(),
3314        }
3315    }
3316}
3317
3318/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3319/// the `unused_dev_dependencies` key. Same bare struct as
3320/// [`UnusedDependencyFinding`]; the fix description points at
3321/// `devDependencies` and the suppress comment uses
3322/// `unused-dev-dependency`.
3323#[derive(Debug, Clone, Serialize, Deserialize)]
3324#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3325pub struct UnusedDevDependencyFinding {
3326    /// The underlying dead-code entry.
3327    #[serde(flatten)]
3328    pub dep: UnusedDependency,
3329    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3330    /// `~<k>` suffix when several findings of one type share an identity.
3331    /// Line and column are not inputs, so the id survives line shifts,
3332    /// reformats and reorders. A rename of the file or the symbol gives a
3333    /// new id. Absent in output from older versions.
3334    #[serde(default, skip_serializing_if = "Option::is_none")]
3335    pub finding_id: Option<String>,
3336    /// Suggested next steps. Always emitted (possibly empty for
3337    /// forward-compat).
3338    pub actions: Vec<IssueAction>,
3339    /// Set by the audit pass when this finding is introduced relative to
3340    /// the merge-base.
3341    #[serde(default, skip_serializing_if = "Option::is_none")]
3342    pub introduced: Option<AuditIntroduced>,
3343    /// Gate severity of this finding after `rules` and `overrides[].rules`
3344    /// resolve for its path. CI formats read it for the annotation, SARIF
3345    /// and CodeClimate level. Absent in output from older versions. Not
3346    /// part of the finding identity, baseline keys or fingerprints.
3347    #[serde(
3348        default,
3349        skip_serializing_if = "Option::is_none",
3350        deserialize_with = "deserialize_effective_severity"
3351    )]
3352    pub effective_severity: Option<EffectiveSeverity>,
3353    /// Advisory caveats on the verdict behind this finding. A dependency is
3354    /// reported unused when NO module in the project imports its specifier,
3355    /// so a module that parsed with errors can hide the import that would
3356    /// have credited the package. Sorted, deduplicated, and omitted from the
3357    /// wire when empty. Never gates the finding, though `fallow fix`
3358    /// withholds the `remove-dependency` write while a caveat stands.
3359    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3360    pub reachability_caveats: Vec<ReachabilityCaveat>,
3361}
3362
3363impl UnusedDevDependencyFinding {
3364    /// Build the wrapper.
3365    #[must_use]
3366    pub fn with_actions(dep: UnusedDependency) -> Self {
3367        let actions = build_unused_dependency_actions(&dep, "devDependencies");
3368        Self {
3369            finding_id: None,
3370            dep,
3371            actions,
3372            introduced: None,
3373            effective_severity: None,
3374            reachability_caveats: Vec::new(),
3375        }
3376    }
3377}
3378
3379/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3380/// the `unused_optional_dependencies` key. Same bare struct as
3381/// [`UnusedDependencyFinding`]; the fix description points at
3382/// `optionalDependencies`. Reuses the `unused-dependency` suppress
3383/// `IssueKind` because there is no dedicated variant for optional deps.
3384#[derive(Debug, Clone, Serialize, Deserialize)]
3385#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3386pub struct UnusedOptionalDependencyFinding {
3387    /// The underlying dead-code entry.
3388    #[serde(flatten)]
3389    pub dep: UnusedDependency,
3390    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3391    /// `~<k>` suffix when several findings of one type share an identity.
3392    /// Line and column are not inputs, so the id survives line shifts,
3393    /// reformats and reorders. A rename of the file or the symbol gives a
3394    /// new id. Absent in output from older versions.
3395    #[serde(default, skip_serializing_if = "Option::is_none")]
3396    pub finding_id: Option<String>,
3397    /// Suggested next steps. Always emitted (possibly empty for
3398    /// forward-compat).
3399    pub actions: Vec<IssueAction>,
3400    /// Set by the audit pass when this finding is introduced relative to
3401    /// the merge-base.
3402    #[serde(default, skip_serializing_if = "Option::is_none")]
3403    pub introduced: Option<AuditIntroduced>,
3404    /// Gate severity of this finding after `rules` and `overrides[].rules`
3405    /// resolve for its path. CI formats read it for the annotation, SARIF
3406    /// and CodeClimate level. Absent in output from older versions. Not
3407    /// part of the finding identity, baseline keys or fingerprints.
3408    #[serde(
3409        default,
3410        skip_serializing_if = "Option::is_none",
3411        deserialize_with = "deserialize_effective_severity"
3412    )]
3413    pub effective_severity: Option<EffectiveSeverity>,
3414    /// Advisory caveats on the verdict behind this finding. A dependency is
3415    /// reported unused when NO module in the project imports its specifier,
3416    /// so a module that parsed with errors can hide the import that would
3417    /// have credited the package. Sorted, deduplicated, and omitted from the
3418    /// wire when empty. Never gates the finding, though `fallow fix`
3419    /// withholds the `remove-dependency` write while a caveat stands.
3420    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3421    pub reachability_caveats: Vec<ReachabilityCaveat>,
3422}
3423
3424impl UnusedOptionalDependencyFinding {
3425    /// Build the wrapper.
3426    #[must_use]
3427    pub fn with_actions(dep: UnusedDependency) -> Self {
3428        let actions = build_unused_dependency_actions(&dep, "optionalDependencies");
3429        Self {
3430            finding_id: None,
3431            dep,
3432            actions,
3433            introduced: None,
3434            effective_severity: None,
3435            reachability_caveats: Vec::new(),
3436        }
3437    }
3438}
3439
3440/// Wire-shape envelope for an [`UnlistedDependency`] finding. Carries an
3441/// `install-dependency` primary (non-auto-fixable) plus the standard
3442/// `ignoreDependencies` config suppress.
3443#[derive(Debug, Clone, Serialize, Deserialize)]
3444#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3445pub struct UnlistedDependencyFinding {
3446    /// The underlying dead-code entry.
3447    #[serde(flatten)]
3448    pub dep: UnlistedDependency,
3449    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3450    /// `~<k>` suffix when several findings of one type share an identity.
3451    /// Line and column are not inputs, so the id survives line shifts,
3452    /// reformats and reorders. A rename of the file or the symbol gives a
3453    /// new id. Absent in output from older versions.
3454    #[serde(default, skip_serializing_if = "Option::is_none")]
3455    pub finding_id: Option<String>,
3456    /// Suggested next steps. Always emitted (possibly empty for
3457    /// forward-compat).
3458    pub actions: Vec<IssueAction>,
3459    /// Set by the audit pass when this finding is introduced relative to
3460    /// the merge-base.
3461    #[serde(default, skip_serializing_if = "Option::is_none")]
3462    pub introduced: Option<AuditIntroduced>,
3463    /// Gate severity of this finding after `rules` and `overrides[].rules`
3464    /// resolve for its path. CI formats read it for the annotation, SARIF
3465    /// and CodeClimate level. Absent in output from older versions. Not
3466    /// part of the finding identity, baseline keys or fingerprints.
3467    #[serde(
3468        default,
3469        skip_serializing_if = "Option::is_none",
3470        deserialize_with = "deserialize_effective_severity"
3471    )]
3472    pub effective_severity: Option<EffectiveSeverity>,
3473}
3474
3475impl UnlistedDependencyFinding {
3476    /// Build the wrapper.
3477    #[must_use]
3478    pub fn with_actions(dep: UnlistedDependency) -> Self {
3479        let actions = vec![
3480            IssueAction::Fix(FixAction {
3481                kind: FixActionType::InstallDependency,
3482                auto_fixable: false,
3483                description: "Add this package to dependencies in package.json".to_string(),
3484                note: Some(
3485                    "Verify this package should be a direct dependency before adding".to_string(),
3486                ),
3487                available_in_catalogs: None,
3488                suggested_target: None,
3489            }),
3490            build_ignore_dependencies_suppress_action(&dep.package_name),
3491        ];
3492        Self {
3493            finding_id: None,
3494            dep,
3495            actions,
3496            introduced: None,
3497            effective_severity: None,
3498        }
3499    }
3500}
3501
3502/// Wire-shape envelope for an [`UnlistedBinary`] finding. Carries an
3503/// `install-dependency` primary (non-auto-fixable) plus an `ignoreBinaries`
3504/// config suppress.
3505#[derive(Debug, Clone, Serialize, Deserialize)]
3506#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3507pub struct UnlistedBinaryFinding {
3508    /// The underlying dead-code entry.
3509    #[serde(flatten)]
3510    pub binary: UnlistedBinary,
3511    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3512    /// `~<k>` suffix when several findings of one type share an identity.
3513    /// Line and column are not inputs, so the id survives line shifts,
3514    /// reformats and reorders. Absent in output from older versions.
3515    #[serde(default, skip_serializing_if = "Option::is_none")]
3516    pub finding_id: Option<String>,
3517    /// Suggested next steps. Always emitted (possibly empty for
3518    /// forward-compat).
3519    pub actions: Vec<IssueAction>,
3520    /// Set by the audit pass when this finding is introduced relative to
3521    /// the merge-base.
3522    #[serde(default, skip_serializing_if = "Option::is_none")]
3523    pub introduced: Option<AuditIntroduced>,
3524    /// Gate severity of this finding after `rules` and `overrides[].rules`
3525    /// resolve for its path. CI formats read it for the annotation, SARIF
3526    /// and CodeClimate level. Absent in output from older versions. Not
3527    /// part of the finding identity, baseline keys or fingerprints.
3528    #[serde(
3529        default,
3530        skip_serializing_if = "Option::is_none",
3531        deserialize_with = "deserialize_effective_severity"
3532    )]
3533    pub effective_severity: Option<EffectiveSeverity>,
3534}
3535
3536impl UnlistedBinaryFinding {
3537    /// Build the wrapper.
3538    #[must_use]
3539    pub fn with_actions(binary: UnlistedBinary) -> Self {
3540        let name = &binary.binary_name;
3541        let actions = vec![
3542            IssueAction::Fix(FixAction {
3543                kind: FixActionType::InstallDependency,
3544                auto_fixable: false,
3545                description: "Add the package that provides this binary to devDependencies"
3546                    .to_string(),
3547                note: Some(
3548                    "If the operating system or the CI image provides this binary, add it to ignoreBinaries instead"
3549                        .to_string(),
3550                ),
3551                available_in_catalogs: None,
3552                suggested_target: None,
3553            }),
3554            IssueAction::AddToConfig(AddToConfigAction {
3555                kind: AddToConfigKind::AddToConfig,
3556                auto_fixable: false,
3557                description: format!("Add \"{name}\" to ignoreBinaries in fallow config"),
3558                config_key: "ignoreBinaries".to_string(),
3559                value: AddToConfigValue::Scalar(name.clone()),
3560                value_schema: Some(
3561                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreBinaries/items"
3562                        .to_string(),
3563                ),
3564            }),
3565        ];
3566        Self {
3567            finding_id: None,
3568            binary,
3569            actions,
3570            introduced: None,
3571            effective_severity: None,
3572        }
3573    }
3574}
3575
3576/// Wire-shape envelope for a [`TypeOnlyDependency`] finding. Carries a
3577/// `move-to-dev` primary plus the standard `ignoreDependencies` config
3578/// suppress.
3579#[derive(Debug, Clone, Serialize, Deserialize)]
3580#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3581pub struct TypeOnlyDependencyFinding {
3582    /// The underlying dead-code entry.
3583    #[serde(flatten)]
3584    pub dep: TypeOnlyDependency,
3585    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3586    /// `~<k>` suffix when several findings of one type share an identity.
3587    /// Line and column are not inputs, so the id survives line shifts,
3588    /// reformats and reorders. A rename of the file or the symbol gives a
3589    /// new id. Absent in output from older versions.
3590    #[serde(default, skip_serializing_if = "Option::is_none")]
3591    pub finding_id: Option<String>,
3592    /// Suggested next steps. Always emitted (possibly empty for
3593    /// forward-compat).
3594    pub actions: Vec<IssueAction>,
3595    /// Set by the audit pass when this finding is introduced relative to
3596    /// the merge-base.
3597    #[serde(default, skip_serializing_if = "Option::is_none")]
3598    pub introduced: Option<AuditIntroduced>,
3599    /// Gate severity of this finding after `rules` and `overrides[].rules`
3600    /// resolve for its path. CI formats read it for the annotation, SARIF
3601    /// and CodeClimate level. Absent in output from older versions. Not
3602    /// part of the finding identity, baseline keys or fingerprints.
3603    #[serde(
3604        default,
3605        skip_serializing_if = "Option::is_none",
3606        deserialize_with = "deserialize_effective_severity"
3607    )]
3608    pub effective_severity: Option<EffectiveSeverity>,
3609}
3610
3611impl TypeOnlyDependencyFinding {
3612    /// Build the wrapper.
3613    #[must_use]
3614    pub fn with_actions(dep: TypeOnlyDependency) -> Self {
3615        let actions = vec![
3616            IssueAction::Fix(FixAction {
3617                kind: FixActionType::MoveToDev,
3618                auto_fixable: false,
3619                description: "Move to devDependencies (only type imports are used)".to_string(),
3620                note: Some(
3621                    "Type imports are erased at runtime so this dependency is not needed in production"
3622                        .to_string(),
3623                ),
3624                available_in_catalogs: None,
3625                suggested_target: None,
3626            }),
3627            build_ignore_dependencies_suppress_action(&dep.package_name),
3628        ];
3629        Self {
3630            finding_id: None,
3631            dep,
3632            actions,
3633            introduced: None,
3634            effective_severity: None,
3635        }
3636    }
3637}
3638
3639/// Wire-shape envelope for a [`TestOnlyDependency`] finding. Carries a
3640/// `move-to-dev` primary (different prose than [`TypeOnlyDependencyFinding`])
3641/// plus the standard `ignoreDependencies` config suppress.
3642#[derive(Debug, Clone, Serialize, Deserialize)]
3643#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3644pub struct TestOnlyDependencyFinding {
3645    /// The underlying dead-code entry.
3646    #[serde(flatten)]
3647    pub dep: TestOnlyDependency,
3648    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3649    /// `~<k>` suffix when several findings of one type share an identity.
3650    /// Line and column are not inputs, so the id survives line shifts,
3651    /// reformats and reorders. A rename of the file or the symbol gives a
3652    /// new id. Absent in output from older versions.
3653    #[serde(default, skip_serializing_if = "Option::is_none")]
3654    pub finding_id: Option<String>,
3655    /// Suggested next steps. Always emitted (possibly empty for
3656    /// forward-compat).
3657    pub actions: Vec<IssueAction>,
3658    /// Set by the audit pass when this finding is introduced relative to
3659    /// the merge-base.
3660    #[serde(default, skip_serializing_if = "Option::is_none")]
3661    pub introduced: Option<AuditIntroduced>,
3662    /// Gate severity of this finding after `rules` and `overrides[].rules`
3663    /// resolve for its path. CI formats read it for the annotation, SARIF
3664    /// and CodeClimate level. Absent in output from older versions. Not
3665    /// part of the finding identity, baseline keys or fingerprints.
3666    #[serde(
3667        default,
3668        skip_serializing_if = "Option::is_none",
3669        deserialize_with = "deserialize_effective_severity"
3670    )]
3671    pub effective_severity: Option<EffectiveSeverity>,
3672}
3673
3674impl TestOnlyDependencyFinding {
3675    /// Build the wrapper.
3676    #[must_use]
3677    pub fn with_actions(dep: TestOnlyDependency) -> Self {
3678        let actions = vec![
3679            IssueAction::Fix(FixAction {
3680                kind: FixActionType::MoveToDev,
3681                auto_fixable: false,
3682                description: "Move to devDependencies (only test files import this)".to_string(),
3683                note: Some(
3684                    "Only test files import this package so it does not need to be a production dependency"
3685                        .to_string(),
3686                ),
3687                available_in_catalogs: None,
3688                suggested_target: None,
3689            }),
3690            build_ignore_dependencies_suppress_action(&dep.package_name),
3691        ];
3692        Self {
3693            finding_id: None,
3694            dep,
3695            actions,
3696            introduced: None,
3697            effective_severity: None,
3698        }
3699    }
3700}
3701
3702/// Wire-shape envelope for a [`DevDependencyInProduction`] finding. Carries a
3703/// `move-to-prod` primary (the promote-side mirror of
3704/// [`TestOnlyDependencyFinding`]'s `move-to-dev`) plus the standard
3705/// `ignoreDependencies` config suppress.
3706#[derive(Debug, Clone, Serialize, Deserialize)]
3707#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3708pub struct DevDependencyInProductionFinding {
3709    /// The underlying dead-code entry.
3710    #[serde(flatten)]
3711    pub dep: DevDependencyInProduction,
3712    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3713    /// `~<k>` suffix when several findings of one type share an identity.
3714    /// Line and column are not inputs, so the id survives line shifts,
3715    /// reformats and reorders. A rename of the file or the symbol gives a
3716    /// new id. Absent in output from older versions.
3717    #[serde(default, skip_serializing_if = "Option::is_none")]
3718    pub finding_id: Option<String>,
3719    /// Suggested next steps. Always emitted (possibly empty for
3720    /// forward-compat).
3721    pub actions: Vec<IssueAction>,
3722    /// Set by the audit pass when this finding is introduced relative to
3723    /// the merge-base.
3724    #[serde(default, skip_serializing_if = "Option::is_none")]
3725    pub introduced: Option<AuditIntroduced>,
3726    /// Gate severity of this finding after `rules` and `overrides[].rules`
3727    /// resolve for its path. CI formats read it for the annotation, SARIF
3728    /// and CodeClimate level. Absent in output from older versions. Not
3729    /// part of the finding identity, baseline keys or fingerprints.
3730    #[serde(
3731        default,
3732        skip_serializing_if = "Option::is_none",
3733        deserialize_with = "deserialize_effective_severity"
3734    )]
3735    pub effective_severity: Option<EffectiveSeverity>,
3736}
3737
3738impl DevDependencyInProductionFinding {
3739    /// Build the wrapper.
3740    #[must_use]
3741    pub fn with_actions(dep: DevDependencyInProduction) -> Self {
3742        let actions = vec![
3743            IssueAction::Fix(FixAction {
3744                kind: FixActionType::MoveToProd,
3745                auto_fixable: false,
3746                description:
3747                    "Move to dependencies if the deployment installs them (production code imports this)"
3748                        .to_string(),
3749                note: Some(
3750                    "A production-only install (`pnpm install --prod`) omits devDependencies, so an import resolved at runtime breaks. A build that inlines the package into its output resolves nothing at runtime, and moving it there can instead make the deployment require an install it did not need"
3751                        .to_string(),
3752                ),
3753                available_in_catalogs: None,
3754                suggested_target: None,
3755            }),
3756            build_ignore_dependencies_suppress_action(&dep.package_name),
3757        ];
3758        Self {
3759            finding_id: None,
3760            dep,
3761            actions,
3762            introduced: None,
3763            effective_severity: None,
3764        }
3765    }
3766}
3767
3768// ── Catalog / dep-override family ───────────────────────────────
3769//
3770// These six wrappers replace the legacy `inject_actions` post-pass in
3771// `crates/cli/src/report/json.rs` for the catalog and dependency-override
3772// findings. Each `with_actions(...)` builds the typed `actions` array
3773// directly from the inner struct (and any per-call context such as
3774// `config_fixable`), so the wire shape is identical to the pre-2.76
3775// post-pass output but the Rust compiler now owns the action contract.
3776
3777/// Wire-shape envelope for a [`DuplicateExport`] finding. Carries up to
3778/// three actions in position-locked order: an `add-to-config` `ignoreExports`
3779/// snippet (only when `locations[]` carries at least one path) followed by
3780/// the `remove-duplicate` fix and the multi-location suppress.
3781///
3782/// The `add-to-config` action sits at position 0 because the documented
3783/// primary slot points at the safe, non-destructive path: the shadcn /
3784/// Radix / bits-ui namespace-barrel case where every `index.*` reexports
3785/// the directory's neighbours. The `remove-duplicate` fix stays as the
3786/// secondary so consumers that pattern-match on `actions[0].type` for
3787/// "primary fix" never propose deletion of an intentional barrel surface.
3788#[derive(Debug, Clone, Serialize, Deserialize)]
3789#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3790pub struct DuplicateExportFinding {
3791    /// The underlying finding.
3792    #[serde(flatten)]
3793    pub export: DuplicateExport,
3794    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3795    /// `~<k>` suffix when several findings of one type share an identity.
3796    /// Line and column are not inputs, so the id survives line shifts,
3797    /// reformats and reorders. A rename of the file or the symbol gives a
3798    /// new id. Absent in output from older versions.
3799    #[serde(default, skip_serializing_if = "Option::is_none")]
3800    pub finding_id: Option<String>,
3801    /// Suggested next steps. Always emitted (possibly empty for
3802    /// forward-compat).
3803    pub actions: Vec<IssueAction>,
3804    /// Set by the audit pass when this finding is introduced relative to
3805    /// the merge-base.
3806    #[serde(default, skip_serializing_if = "Option::is_none")]
3807    pub introduced: Option<AuditIntroduced>,
3808    /// Gate severity of this finding after `rules` and `overrides[].rules`
3809    /// resolve for its path. CI formats read it for the annotation, SARIF
3810    /// and CodeClimate level. Absent in output from older versions. Not
3811    /// part of the finding identity, baseline keys or fingerprints.
3812    #[serde(
3813        default,
3814        skip_serializing_if = "Option::is_none",
3815        deserialize_with = "deserialize_effective_severity"
3816    )]
3817    pub effective_severity: Option<EffectiveSeverity>,
3818}
3819
3820impl DuplicateExportFinding {
3821    /// Build the wrapper with the `add-to-config` action's `auto_fixable`
3822    /// defaulting to `false`. The CLI's `build_json_with_config_fixable`
3823    /// path layers the actual `config_fixable` signal via
3824    /// [`Self::set_config_fixable`] right before serialization (the
3825    /// fix-applier readiness check lives in `fallow-cli::fix` and is not
3826    /// reachable from the analyzer layer where wrappers are first built).
3827    /// Embedders that build `AnalysisResults` directly and never route
3828    /// through the CLI's JSON path keep the conservative default.
3829    #[must_use]
3830    pub fn with_actions(export: DuplicateExport) -> Self {
3831        let mut actions: Vec<IssueAction> = Vec::with_capacity(3);
3832
3833        if let Some(rules) = build_duplicate_exports_ignore_rules(&export) {
3834            actions.push(IssueAction::AddToConfig(AddToConfigAction {
3835                kind: AddToConfigKind::AddToConfig,
3836                auto_fixable: false,
3837                description: "Add an ignoreExports rule so these files are excluded from duplicate-export grouping (use when this duplication is an intentional namespace-barrel API).".to_string(),
3838                config_key: "ignoreExports".to_string(),
3839                value: AddToConfigValue::ExportsRules(rules),
3840                value_schema: Some(IGNORE_EXPORTS_VALUE_SCHEMA.to_string()),
3841            }));
3842        }
3843
3844        actions.push(IssueAction::Fix(FixAction {
3845            kind: FixActionType::RemoveDuplicate,
3846            auto_fixable: false,
3847            description: "Keep one canonical export location and remove the others".to_string(),
3848            note: Some(NAMESPACE_BARREL_HINT.to_string()),
3849            available_in_catalogs: None,
3850            suggested_target: None,
3851        }));
3852
3853        actions.push(IssueAction::SuppressLine(SuppressLineAction {
3854            kind: SuppressLineKind::SuppressLine,
3855            auto_fixable: false,
3856            description: "Suppress with an inline comment above the line".to_string(),
3857            comment: "// fallow-ignore-next-line duplicate-export".to_string(),
3858            scope: Some(SuppressLineScope::PerLocation),
3859        }));
3860
3861        Self {
3862            finding_id: None,
3863            export,
3864            actions,
3865            introduced: None,
3866            effective_severity: None,
3867        }
3868    }
3869
3870    /// Update the position-0 `add-to-config` action's `auto_fixable` flag.
3871    /// Idempotent and a no-op when position 0 is not an `add-to-config`
3872    /// action (happens when the finding has no locations). Called by the
3873    /// CLI's JSON serializer with the result of
3874    /// `crate::fix::is_config_fixable` before emitting bytes.
3875    pub fn set_config_fixable(&mut self, fixable: bool) {
3876        if let Some(IssueAction::AddToConfig(action)) = self.actions.first_mut() {
3877            action.auto_fixable = fixable;
3878        }
3879    }
3880}
3881
3882/// Wire-shape envelope for an [`UnusedCatalogEntry`] finding. Per-instance
3883/// `auto_fixable` flips to `false` when `hardcoded_consumers` is non-empty or
3884/// the source is not `pnpm-workspace.yaml`.
3885#[derive(Debug, Clone, Serialize, Deserialize)]
3886#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3887pub struct UnusedCatalogEntryFinding {
3888    /// The underlying finding.
3889    #[serde(flatten)]
3890    pub entry: UnusedCatalogEntry,
3891    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3892    /// `~<k>` suffix when several findings of one type share an identity.
3893    /// Line and column are not inputs, so the id survives line shifts,
3894    /// reformats and reorders. A rename of the file or the symbol gives a
3895    /// new id. Absent in output from older versions.
3896    #[serde(default, skip_serializing_if = "Option::is_none")]
3897    pub finding_id: Option<String>,
3898    /// Suggested next steps. Always emitted.
3899    pub actions: Vec<IssueAction>,
3900    /// Set by the audit pass when this finding is introduced relative to
3901    /// the merge-base.
3902    #[serde(default, skip_serializing_if = "Option::is_none")]
3903    pub introduced: Option<AuditIntroduced>,
3904    /// Gate severity of this finding after `rules` and `overrides[].rules`
3905    /// resolve for its path. CI formats read it for the annotation, SARIF
3906    /// and CodeClimate level. Absent in output from older versions. Not
3907    /// part of the finding identity, baseline keys or fingerprints.
3908    #[serde(
3909        default,
3910        skip_serializing_if = "Option::is_none",
3911        deserialize_with = "deserialize_effective_severity"
3912    )]
3913    pub effective_severity: Option<EffectiveSeverity>,
3914}
3915
3916impl UnusedCatalogEntryFinding {
3917    /// Build the wrapper. Per-instance `auto_fixable` is `true` only when
3918    /// `hardcoded_consumers` is empty and the source is `pnpm-workspace.yaml`;
3919    /// otherwise `fallow fix` skips the entry to avoid breaking installs or
3920    /// applying YAML edits to Bun `package.json` catalogs.
3921    #[must_use]
3922    pub fn with_actions(entry: UnusedCatalogEntry) -> Self {
3923        let is_pnpm_source = is_pnpm_catalog_source(&entry.path);
3924        let auto_fixable = entry.hardcoded_consumers.is_empty() && is_pnpm_source;
3925        let note = if is_pnpm_source {
3926            Some(
3927                "If any consumer declares the same package with a hardcoded version, switch the consumer to `catalog:` before removing"
3928                    .to_string(),
3929            )
3930        } else {
3931            Some(
3932                "fallow fix only edits pnpm-workspace.yaml catalog entries. Edit Bun package.json catalogs manually."
3933                    .to_string(),
3934            )
3935        };
3936        let mut actions = vec![IssueAction::Fix(FixAction {
3937            kind: FixActionType::RemoveCatalogEntry,
3938            auto_fixable,
3939            description: if is_pnpm_source {
3940                "Remove the entry from pnpm-workspace.yaml".to_string()
3941            } else {
3942                "Remove the entry from the catalog source file manually".to_string()
3943            },
3944            note,
3945            available_in_catalogs: None,
3946            suggested_target: None,
3947        })];
3948        if is_pnpm_source {
3949            actions.push(IssueAction::SuppressLine(SuppressLineAction {
3950                kind: SuppressLineKind::SuppressLine,
3951                auto_fixable: false,
3952                description: "Suppress with a YAML comment above the line".to_string(),
3953                comment: "# fallow-ignore-next-line unused-catalog-entry".to_string(),
3954                scope: None,
3955            }));
3956        }
3957        Self {
3958            finding_id: None,
3959            entry,
3960            actions,
3961            introduced: None,
3962            effective_severity: None,
3963        }
3964    }
3965}
3966
3967/// Wire-shape envelope for an [`EmptyCatalogGroup`] finding. Carries a
3968/// `remove-empty-catalog-group` primary. YAML-sourced findings also include a
3969/// YAML-comment suppress action.
3970#[derive(Debug, Clone, Serialize, Deserialize)]
3971#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3972pub struct EmptyCatalogGroupFinding {
3973    /// The underlying finding.
3974    #[serde(flatten)]
3975    pub group: EmptyCatalogGroup,
3976    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3977    /// `~<k>` suffix when several findings of one type share an identity.
3978    /// Line and column are not inputs, so the id survives line shifts,
3979    /// reformats and reorders. A rename of the file or the symbol gives a
3980    /// new id. Absent in output from older versions.
3981    #[serde(default, skip_serializing_if = "Option::is_none")]
3982    pub finding_id: Option<String>,
3983    /// Suggested next steps. Always emitted.
3984    pub actions: Vec<IssueAction>,
3985    /// Set by the audit pass when this finding is introduced relative to
3986    /// the merge-base.
3987    #[serde(default, skip_serializing_if = "Option::is_none")]
3988    pub introduced: Option<AuditIntroduced>,
3989    /// Gate severity of this finding after `rules` and `overrides[].rules`
3990    /// resolve for its path. CI formats read it for the annotation, SARIF
3991    /// and CodeClimate level. Absent in output from older versions. Not
3992    /// part of the finding identity, baseline keys or fingerprints.
3993    #[serde(
3994        default,
3995        skip_serializing_if = "Option::is_none",
3996        deserialize_with = "deserialize_effective_severity"
3997    )]
3998    pub effective_severity: Option<EffectiveSeverity>,
3999}
4000
4001impl EmptyCatalogGroupFinding {
4002    /// Build the wrapper.
4003    #[must_use]
4004    pub fn with_actions(group: EmptyCatalogGroup) -> Self {
4005        let auto_fixable = is_pnpm_catalog_source(&group.path);
4006        let mut actions = vec![IssueAction::Fix(FixAction {
4007            kind: FixActionType::RemoveEmptyCatalogGroup,
4008            auto_fixable,
4009            description: if auto_fixable {
4010                "Remove the empty named catalog group from pnpm-workspace.yaml".to_string()
4011            } else {
4012                "Remove the empty named catalog group from the catalog source file manually"
4013                    .to_string()
4014            },
4015            note: Some(if auto_fixable {
4016                "Only named groups under `catalogs:` are flagged; the top-level `catalog:` hook is intentionally ignored"
4017                    .to_string()
4018            } else {
4019                "fallow fix only edits pnpm-workspace.yaml catalog groups. Edit Bun package.json catalogs manually."
4020                    .to_string()
4021            }),
4022            available_in_catalogs: None,
4023            suggested_target: None,
4024        })];
4025        if auto_fixable {
4026            actions.push(IssueAction::SuppressLine(SuppressLineAction {
4027                kind: SuppressLineKind::SuppressLine,
4028                auto_fixable: false,
4029                description: "Suppress with a YAML comment above the line".to_string(),
4030                comment: "# fallow-ignore-next-line empty-catalog-group".to_string(),
4031                scope: None,
4032            }));
4033        }
4034        Self {
4035            finding_id: None,
4036            group,
4037            actions,
4038            introduced: None,
4039            effective_severity: None,
4040        }
4041    }
4042}
4043
4044/// Wire-shape envelope for an [`UnresolvedCatalogReference`] finding. The
4045/// primary action at position 0 discriminates on `available_in_catalogs`:
4046/// `add-catalog-entry` when the array is empty (no other catalog declares
4047/// the package), or `update-catalog-reference` when at least one
4048/// alternative exists. When exactly one alternative exists, the action
4049/// also carries `suggested_target` so deterministic agents can land the
4050/// edit without picking from a list.
4051#[derive(Debug, Clone, Serialize, Deserialize)]
4052#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4053pub struct UnresolvedCatalogReferenceFinding {
4054    /// The underlying finding.
4055    #[serde(flatten)]
4056    pub reference: UnresolvedCatalogReference,
4057    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4058    /// `~<k>` suffix when several findings of one type share an identity.
4059    /// Line and column are not inputs, so the id survives line shifts,
4060    /// reformats and reorders. A rename of the file or the symbol gives a
4061    /// new id. Absent in output from older versions.
4062    #[serde(default, skip_serializing_if = "Option::is_none")]
4063    pub finding_id: Option<String>,
4064    /// Suggested next steps. Always emitted; position 0 is the discriminated
4065    /// primary (see struct docs).
4066    pub actions: Vec<IssueAction>,
4067    /// Set by the audit pass when this finding is introduced relative to
4068    /// the merge-base.
4069    #[serde(default, skip_serializing_if = "Option::is_none")]
4070    pub introduced: Option<AuditIntroduced>,
4071    /// Gate severity of this finding after `rules` and `overrides[].rules`
4072    /// resolve for its path. CI formats read it for the annotation, SARIF
4073    /// and CodeClimate level. Absent in output from older versions. Not
4074    /// part of the finding identity, baseline keys or fingerprints.
4075    #[serde(
4076        default,
4077        skip_serializing_if = "Option::is_none",
4078        deserialize_with = "deserialize_effective_severity"
4079    )]
4080    pub effective_severity: Option<EffectiveSeverity>,
4081}
4082
4083impl UnresolvedCatalogReferenceFinding {
4084    /// Build the wrapper. The discriminator at position 0 is the
4085    /// `add-catalog-entry` vs `update-catalog-reference` pick documented on
4086    /// the struct.
4087    #[must_use]
4088    pub fn with_actions(reference: UnresolvedCatalogReference) -> Self {
4089        // Normalize separators to forward slashes so the
4090        // `ignoreCatalogReferences.consumer` action value is portable when
4091        // pasted into a Windows-authored config. See
4092        // `build_duplicate_exports_ignore_rules` for the same pattern.
4093        let consumer_path = reference.path.to_string_lossy().replace('\\', "/");
4094        let primary = catalog_reference_primary_action(&reference);
4095        let fallback = remove_catalog_reference_action();
4096        let suppress = suppress_catalog_reference_action(&reference, consumer_path);
4097
4098        Self {
4099            finding_id: None,
4100            reference,
4101            actions: vec![primary, fallback, suppress],
4102            introduced: None,
4103            effective_severity: None,
4104        }
4105    }
4106}
4107
4108fn catalog_reference_primary_action(reference: &UnresolvedCatalogReference) -> IssueAction {
4109    if reference.available_in_catalogs.is_empty() {
4110        return IssueAction::Fix(FixAction {
4111            kind: FixActionType::AddCatalogEntry,
4112            auto_fixable: false,
4113            description: format!(
4114                "Add `{}` to the `{}` catalog in pnpm-workspace.yaml",
4115                reference.entry_name, reference.catalog_name
4116            ),
4117            note: Some(
4118                "Pin a version that satisfies the consumer's import; no other catalog declares this package today"
4119                    .to_string(),
4120            ),
4121            available_in_catalogs: None,
4122            suggested_target: None,
4123        });
4124    }
4125
4126    let available = reference.available_in_catalogs.clone();
4127    let suggested_target = (available.len() == 1).then(|| available[0].clone());
4128    IssueAction::Fix(FixAction {
4129        kind: FixActionType::UpdateCatalogReference,
4130        auto_fixable: false,
4131        description: format!(
4132            "Switch the reference from `catalog:{}` to a catalog that declares `{}`",
4133            reference.catalog_name, reference.entry_name
4134        ),
4135        note: None,
4136        available_in_catalogs: Some(available),
4137        suggested_target,
4138    })
4139}
4140
4141fn remove_catalog_reference_action() -> IssueAction {
4142    IssueAction::Fix(FixAction {
4143        kind: FixActionType::RemoveCatalogReference,
4144        auto_fixable: false,
4145        description: "Remove the catalog reference and pin a hardcoded version in its place"
4146            .to_string(),
4147        note: Some(
4148            "Use only when neither another catalog declares the package nor the named catalog should grow to include it"
4149                .to_string(),
4150        ),
4151        available_in_catalogs: None,
4152        suggested_target: None,
4153    })
4154}
4155
4156fn suppress_catalog_reference_action(
4157    reference: &UnresolvedCatalogReference,
4158    consumer_path: String,
4159) -> IssueAction {
4160    let mut suppress_value = serde_json::Map::new();
4161    suppress_value.insert(
4162        "package".to_string(),
4163        serde_json::Value::String(reference.entry_name.clone()),
4164    );
4165    suppress_value.insert(
4166        "catalog".to_string(),
4167        serde_json::Value::String(reference.catalog_name.clone()),
4168    );
4169    suppress_value.insert(
4170        "consumer".to_string(),
4171        serde_json::Value::String(consumer_path),
4172    );
4173    IssueAction::AddToConfig(AddToConfigAction {
4174        kind: AddToConfigKind::AddToConfig,
4175        auto_fixable: false,
4176        description: "Suppress this reference via ignoreCatalogReferences in fallow config (use when the catalog edit is intentionally landing in a separate PR or the package is a placeholder).".to_string(),
4177        config_key: "ignoreCatalogReferences".to_string(),
4178        value: AddToConfigValue::RuleObject(suppress_value),
4179        value_schema: Some(IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA.to_string()),
4180    })
4181}
4182
4183/// Wire-shape envelope for an [`UnusedDependencyOverride`] finding. Carries
4184/// a `remove-dependency-override` primary plus an `add-to-config`
4185/// `ignoreDependencyOverrides` suppress scoped to the target package and
4186/// declaration source.
4187#[derive(Debug, Clone, Serialize, Deserialize)]
4188#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4189pub struct UnusedDependencyOverrideFinding {
4190    /// The underlying finding.
4191    #[serde(flatten)]
4192    pub entry: UnusedDependencyOverride,
4193    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4194    /// `~<k>` suffix when several findings of one type share an identity.
4195    /// Line and column are not inputs, so the id survives line shifts,
4196    /// reformats and reorders. A rename of the file or the symbol gives a
4197    /// new id. Absent in output from older versions.
4198    #[serde(default, skip_serializing_if = "Option::is_none")]
4199    pub finding_id: Option<String>,
4200    /// Suggested next steps. Always emitted.
4201    pub actions: Vec<IssueAction>,
4202    /// Set by the audit pass when this finding is introduced relative to
4203    /// the merge-base.
4204    #[serde(default, skip_serializing_if = "Option::is_none")]
4205    pub introduced: Option<AuditIntroduced>,
4206    /// Gate severity of this finding after `rules` and `overrides[].rules`
4207    /// resolve for its path. CI formats read it for the annotation, SARIF
4208    /// and CodeClimate level. Absent in output from older versions. Not
4209    /// part of the finding identity, baseline keys or fingerprints.
4210    #[serde(
4211        default,
4212        skip_serializing_if = "Option::is_none",
4213        deserialize_with = "deserialize_effective_severity"
4214    )]
4215    pub effective_severity: Option<EffectiveSeverity>,
4216}
4217
4218impl UnusedDependencyOverrideFinding {
4219    /// Build the wrapper.
4220    #[must_use]
4221    pub fn with_actions(entry: UnusedDependencyOverride) -> Self {
4222        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
4223        actions.push(IssueAction::Fix(FixAction {
4224            kind: FixActionType::RemoveDependencyOverride,
4225            auto_fixable: false,
4226            description: "Remove the package-manager override entry from its declaration source"
4227                .to_string(),
4228            note: Some(
4229                "Conservative static check; verify against the active package manager's frozen-lockfile install before removing in case the override targets a transitive dependency (CVE-fix pattern)"
4230                    .to_string(),
4231            ),
4232            available_in_catalogs: None,
4233            suggested_target: None,
4234        }));
4235
4236        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
4237            Some(&entry.target_package),
4238            &entry.raw_key,
4239            entry.source,
4240        ) {
4241            actions.push(suppress);
4242        }
4243
4244        Self {
4245            finding_id: None,
4246            entry,
4247            actions,
4248            introduced: None,
4249            effective_severity: None,
4250        }
4251    }
4252}
4253
4254/// Wire-shape envelope for a [`MisconfiguredDependencyOverride`] finding.
4255/// Carries a `fix-dependency-override` primary plus the conditional
4256/// `add-to-config` `ignoreDependencyOverrides` suppress (skipped when both
4257/// `target_package` and `raw_key` are empty, since the rule matcher keys on
4258/// a non-empty package name).
4259#[derive(Debug, Clone, Serialize, Deserialize)]
4260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4261pub struct MisconfiguredDependencyOverrideFinding {
4262    /// The underlying finding.
4263    #[serde(flatten)]
4264    pub entry: MisconfiguredDependencyOverride,
4265    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4266    /// `~<k>` suffix when several findings of one type share an identity.
4267    /// Line and column are not inputs, so the id survives line shifts,
4268    /// reformats and reorders. A rename of the file or the symbol gives a
4269    /// new id. Absent in output from older versions.
4270    #[serde(default, skip_serializing_if = "Option::is_none")]
4271    pub finding_id: Option<String>,
4272    /// Suggested next steps. Always emitted.
4273    pub actions: Vec<IssueAction>,
4274    /// Set by the audit pass when this finding is introduced relative to
4275    /// the merge-base.
4276    #[serde(default, skip_serializing_if = "Option::is_none")]
4277    pub introduced: Option<AuditIntroduced>,
4278    /// Gate severity of this finding after `rules` and `overrides[].rules`
4279    /// resolve for its path. CI formats read it for the annotation, SARIF
4280    /// and CodeClimate level. Absent in output from older versions. Not
4281    /// part of the finding identity, baseline keys or fingerprints.
4282    #[serde(
4283        default,
4284        skip_serializing_if = "Option::is_none",
4285        deserialize_with = "deserialize_effective_severity"
4286    )]
4287    pub effective_severity: Option<EffectiveSeverity>,
4288}
4289
4290impl MisconfiguredDependencyOverrideFinding {
4291    /// Build the wrapper. The suppress action is omitted when neither
4292    /// `target_package` (set on `EmptyValue` cases) nor `raw_key` provides a
4293    /// non-empty package name; an `ignoreDependencyOverrides` entry with
4294    /// `package: ""` would be silently ignored by the config parser.
4295    #[must_use]
4296    pub fn with_actions(entry: MisconfiguredDependencyOverride) -> Self {
4297        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
4298        actions.push(IssueAction::Fix(FixAction {
4299            kind: FixActionType::FixDependencyOverride,
4300            auto_fixable: false,
4301            description:
4302                "Fix the package-manager override key or value: invalid entries are rejected or ignored"
4303                    .to_string(),
4304            note: Some(
4305                "Common shapes: bare `pkg`, scoped `@scope/pkg`, version-selector `pkg@<2`, parent-chain `parent>child`. Valid values include semver ranges, `-` (removal), `$ref` (self-ref), and `npm:alias@^1`."
4306                    .to_string(),
4307            ),
4308            available_in_catalogs: None,
4309            suggested_target: None,
4310        }));
4311
4312        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
4313            entry.target_package.as_deref(),
4314            &entry.raw_key,
4315            entry.source,
4316        ) {
4317            actions.push(suppress);
4318        }
4319
4320        Self {
4321            finding_id: None,
4322            entry,
4323            actions,
4324            introduced: None,
4325            effective_severity: None,
4326        }
4327    }
4328}
4329
4330/// Shared `add-to-config` `ignoreDependencyOverrides` builder for the two
4331/// override findings. Returns `None` when no non-empty package name is
4332/// available; the config parser silently drops entries with an empty
4333/// `package` field, so emitting one would be a no-op that misleads agents.
4334fn build_ignore_dependency_overrides_suppress(
4335    target_package: Option<&str>,
4336    raw_key: &str,
4337    source: DependencyOverrideSource,
4338) -> Option<IssueAction> {
4339    let package = target_package
4340        .filter(|s| !s.is_empty())
4341        .or_else(|| Some(raw_key).filter(|s| !s.is_empty()))?
4342        .to_string();
4343    let mut value = serde_json::Map::new();
4344    value.insert("package".to_string(), serde_json::Value::String(package));
4345    value.insert(
4346        "source".to_string(),
4347        serde_json::Value::String(source.as_label().to_string()),
4348    );
4349    Some(IssueAction::AddToConfig(AddToConfigAction {
4350        kind: AddToConfigKind::AddToConfig,
4351        auto_fixable: false,
4352        description: "Suppress this override finding via ignoreDependencyOverrides in fallow config (use for CVE-fix overrides that target a purely-transitive package).".to_string(),
4353        config_key: "ignoreDependencyOverrides".to_string(),
4354        value: AddToConfigValue::RuleObject(value),
4355        value_schema: Some(IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA.to_string()),
4356    }))
4357}
4358
4359// ── The mutation gate, registered once ──────────────────────────
4360//
4361// Every finding whose reachability verdict a lost import edge can distort.
4362// The analysis layer stamps caveats through `set_reachability_caveats`, which
4363// enforces the gate on the finding's actions in the same call; every mutation
4364// surface reads the answer back through `may_auto_apply_mutation`.
4365impl_caveated_finding!(
4366    UnusedFileFinding,
4367    UnusedExportFinding,
4368    UnusedTypeFinding,
4369    UnusedEnumMemberFinding,
4370    UnusedClassMemberFinding,
4371    UnusedNamespaceMemberFinding,
4372    UnusedProtectedClassMemberFinding,
4373    UnusedStoreMemberFinding,
4374    UnusedDependencyFinding,
4375    UnusedDevDependencyFinding,
4376    UnusedOptionalDependencyFinding,
4377);
4378
4379/// Gate severity of one finding after rule resolution.
4380///
4381/// It is the severity that `rules` and the matching `overrides[].rules` give
4382/// the finding for its path. `--fail-on-issues` raises `warn` to `error`. A
4383/// finding whose rule is `off` is not reported, so there is no `off` value.
4384/// The type is separate from the health `severity` band, which ranks a
4385/// finding and does not gate it.
4386///
4387/// The `fallow dead-code` findings gate fails when a finding is `error`.
4388/// Other gates (regression, stale baseline) decide on their own inputs. Two
4389/// commands differ: the `fallow audit` `new-only` gate fails only on introduced
4390/// findings, so an inherited `error` finding does not fail the audit, and the
4391/// combined command (`fallow` without a subcommand) exits 0 for machine
4392/// formats unless `--fail-on-issues` or `--ci` is set.
4393///
4394/// Complexity findings carry the same type. The `complexity-cyclomatic`,
4395/// `complexity-cognitive` and `complexity-crap` rules set it, and the
4396/// `fallow health` findings gate and the audit verdict read it.
4397#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4398#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4399#[serde(rename_all = "lowercase")]
4400pub enum EffectiveSeverity {
4401    /// The finding fails the run.
4402    Error,
4403    /// The finding is reported and does not fail the run.
4404    Warn,
4405}
4406
4407/// Read an optional [`EffectiveSeverity`] and treat an unknown value as absent.
4408///
4409/// A saved report from a newer version can carry a value this version does not
4410/// know. The renderers then use the rule-based level, as for a report without
4411/// the field, and the envelope still loads.
4412///
4413/// # Errors
4414///
4415/// Returns an error only when the input is not valid JSON-like data.
4416pub fn deserialize_effective_severity<'de, D>(
4417    deserializer: D,
4418) -> Result<Option<EffectiveSeverity>, D::Error>
4419where
4420    D: serde::Deserializer<'de>,
4421{
4422    #[derive(Deserialize)]
4423    #[serde(untagged)]
4424    enum Tolerant {
4425        Known(EffectiveSeverity),
4426        Unknown(serde::de::IgnoredAny),
4427    }
4428    Ok(match Option::<Tolerant>::deserialize(deserializer)? {
4429        Some(Tolerant::Known(severity)) => Some(severity),
4430        Some(Tolerant::Unknown(_)) | None => None,
4431    })
4432}
4433
4434/// A finding wrapper that carries an [`EffectiveSeverity`].
4435///
4436/// The analysis layer writes the value one time after rule resolution. CI
4437/// renderers read it and fall back to the rule-level severity when it is
4438/// absent, for example in a saved report from an older version.
4439pub trait GatedFinding {
4440    /// The gate severity, or `None` when no value was written.
4441    fn effective_severity(&self) -> Option<EffectiveSeverity>;
4442
4443    /// Write the gate severity.
4444    fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>);
4445}
4446
4447/// Implement [`GatedFinding`] for wrappers with an `effective_severity` field.
4448macro_rules! impl_gated_finding {
4449    ($($finding:ty),+ $(,)?) => {
4450        $(
4451            impl GatedFinding for $finding {
4452                fn effective_severity(&self) -> Option<EffectiveSeverity> {
4453                    self.effective_severity
4454                }
4455
4456                fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>) {
4457                    self.effective_severity = severity;
4458                }
4459            }
4460        )+
4461    };
4462}
4463
4464impl_gated_finding!(
4465    UnusedFileFinding,
4466    PrivateTypeLeakFinding,
4467    DeprecatedExportInUseFinding,
4468    UnresolvedImportFinding,
4469    CircularDependencyFinding,
4470    ReExportCycleFinding,
4471    PackageCycleFinding,
4472    BoundaryViolationFinding,
4473    BoundaryCoverageViolationFinding,
4474    BoundaryCallViolationFinding,
4475    UnusedExportFinding,
4476    UnusedTypeFinding,
4477    InvalidClientExportFinding,
4478    MixedClientServerBarrelFinding,
4479    MisplacedDirectiveFinding,
4480    UnprovidedInjectFinding,
4481    UnusedServerActionFinding,
4482    UnusedLoadDataKeyFinding,
4483    UnrenderedComponentFinding,
4484    UnusedComponentPropFinding,
4485    AbsentComponentPropFinding,
4486    UnusedComponentEmitFinding,
4487    UnusedSvelteEventFinding,
4488    UnusedEffectLayerFinding,
4489    UnusedTaggedErrorFinding,
4490    UnproducedCatchTagFinding,
4491    UnusedComponentInputFinding,
4492    UnusedComponentOutputFinding,
4493    RouteCollisionFinding,
4494    DynamicSegmentNameConflictFinding,
4495    UnusedEnumMemberFinding,
4496    UnusedClassMemberFinding,
4497    UnusedNamespaceMemberFinding,
4498    UnusedProtectedClassMemberFinding,
4499    UnusedStoreMemberFinding,
4500    UnusedDependencyFinding,
4501    UnusedDevDependencyFinding,
4502    UnusedOptionalDependencyFinding,
4503    UnlistedDependencyFinding,
4504    UnlistedBinaryFinding,
4505    TypeOnlyDependencyFinding,
4506    TestOnlyDependencyFinding,
4507    DevDependencyInProductionFinding,
4508    DuplicateExportFinding,
4509    DuplicateExportAliasFinding,
4510    UnusedCatalogEntryFinding,
4511    EmptyCatalogGroupFinding,
4512    UnresolvedCatalogReferenceFinding,
4513    UnusedDependencyOverrideFinding,
4514    MisconfiguredDependencyOverrideFinding,
4515    PropDrillingChainFinding,
4516    ThinWrapperFinding,
4517    DuplicatePropShapeFinding,
4518    crate::results::StaleSuppression,
4519);
4520
4521#[path = "output_dead_code_actions.rs"]
4522mod output_dead_code_actions;
4523use output_dead_code_actions::{
4524    build_duplicate_exports_ignore_rules, build_unused_dependency_actions,
4525};
4526
4527#[cfg(test)]
4528#[path = "output_dead_code_caveat_tokens.rs"]
4529mod caveat_tokens;
4530
4531/// A caveated finding must expose no automatic fix. An uncaveated finding keeps its actions.
4532/// The annotation pass requires an implementation of `CaveatedFinding`.
4533/// The tests also cover finding types that can expose automatic fixes.
4534#[cfg(test)]
4535#[path = "output_dead_code_mutation_gate.rs"]
4536mod mutation_gate;
4537
4538// These tests pin the primary action at actions[0] for consumers that read it.
4539#[cfg(test)]
4540#[path = "output_dead_code_position_0_invariants.rs"]
4541mod position_0_invariants;