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};
31use std::path::Path;
32
33use crate::envelope::AuditIntroduced;
34use crate::output::{
35    AddToConfigAction, AddToConfigKind, AddToConfigValue, FixAction, FixActionType,
36    IgnoreExportsRule, IssueAction, SuppressFileAction, SuppressFileKind, SuppressLineAction,
37    SuppressLineKind, SuppressLineScope,
38};
39use crate::results::{
40    AbsentComponentProp, BoundaryCallViolation, BoundaryCoverageViolation, BoundaryViolation,
41    CircularDependency, DependencyOverrideSource, DeprecatedExportInUse, DevDependencyInProduction,
42    DuplicateExport, DuplicateExportAlias, DuplicatePropShape, DynamicSegmentNameConflict,
43    EmptyCatalogGroup, InvalidClientExport, MisconfiguredDependencyOverride, MisplacedDirective,
44    MixedClientServerBarrel, PackageCycle, PolicyViolation, PrivateTypeLeak, PropDrillingChain,
45    ReExportCycle, ReExportCycleKind, RouteCollision, TestOnlyDependency, ThinWrapper,
46    TypeOnlyDependency, UnlistedBinary, UnlistedDependency, UnproducedCatchTag, UnprovidedInject,
47    UnrenderedComponent, UnresolvedCatalogReference, UnresolvedImport, UnusedCatalogEntry,
48    UnusedComponentEmit, UnusedComponentInput, UnusedComponentOutput, UnusedComponentProp,
49    UnusedDependency, UnusedDependencyOverride, UnusedEffectLayer, UnusedExport, UnusedFile,
50    UnusedLoadDataKey, UnusedMember, UnusedServerAction, UnusedSvelteEvent, UnusedTaggedError,
51};
52use crate::semantic::{
53    SemanticCandidateDecision, SemanticCandidateDecisionKind, SemanticCompleteness,
54};
55
56/// Shared note for the `duplicate-exports` fix action. This const is the
57/// single source of truth: `crates/cli/src/report/shared.rs` aliases it for
58/// the human report.
59pub 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.";
60
61/// JSON Schema fragment URL for the `add-to-config` `ignoreExports` action's
62/// `value` payload. Pinned to the main branch so users browsing the action
63/// value can navigate directly to the rule shape.
64const IGNORE_EXPORTS_VALUE_SCHEMA: &str =
65    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreExports";
66
67/// JSON Schema fragment URL for the `ignoreCatalogReferences` rule items
68/// referenced by `add-to-config` actions on `unresolved-catalog-references`.
69const IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreCatalogReferences/items";
70
71/// JSON Schema fragment URL for the `ignoreDependencyOverrides` rule items
72/// referenced by `add-to-config` actions on both the unused- and
73/// misconfigured-override findings.
74const IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencyOverrides/items";
75
76const PNPM_WORKSPACE_FILE: &str = "pnpm-workspace.yaml";
77
78fn manual_framework_fix(kind: FixActionType, description: &str, note: &str) -> IssueAction {
79    IssueAction::Fix(FixAction {
80        kind,
81        auto_fixable: false,
82        description: description.to_string(),
83        note: Some(note.to_string()),
84        available_in_catalogs: None,
85        suggested_target: None,
86    })
87}
88
89fn suppress_line(comment: &str) -> IssueAction {
90    IssueAction::SuppressLine(SuppressLineAction {
91        kind: SuppressLineKind::SuppressLine,
92        auto_fixable: false,
93        description: "Suppress with an inline comment above the line".to_string(),
94        comment: comment.to_string(),
95        scope: None,
96    })
97}
98
99/// A per-finding caveat on a dead-code verdict that a file this run never
100/// fully analyzed can distort.
101///
102/// Advisory provenance, in the same spirit as the fix path's
103/// `low_confidence_off_graph` / `low_confidence_unresolved_imports` skip
104/// reasons: a caveat NEVER withholds, reorders, downgrades, or re-severities
105/// the finding, and never changes an exit code. It records that the verdict
106/// was computed over an import graph fallow already knows is incomplete, so a
107/// reader who sees the finding also sees the caveat instead of having to
108/// notice a diagnostic at the other end of the envelope.
109///
110/// Deliberately NOT named `confidence`: `health --targets` already emits a
111/// `confidence` key holding an enum string, and a shared consumer helper that
112/// met both would see the same key change type. Emitted on every finding type
113/// that registers it: the reachability arrays (`unused_files[]`,
114/// `unused_exports[]`, `unused_types[]`), the member arrays
115/// (`unused_enum_members[]`, `unused_class_members[]`, `unused_store_members[]`),
116/// and the three dependency arrays. Sorted and deduplicated, absent from the
117/// wire when empty. The set is open in the same sense
118/// `workspace_diagnostics[].kind` is: treat an unrecognised value as "some
119/// caveat" rather than as an error.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
121#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
122#[serde(rename_all = "kebab-case")]
123pub enum ReachabilityCaveat {
124    /// This finding's own file is one the run did not fully analyze, so the
125    /// export and import lists extracted from it may stop short of the real
126    /// ones. That reaches an `unused-file` verdict directly, because the
127    /// "is any export of this file referenced from a reachable module" test
128    /// reads exactly that truncated export list.
129    ///
130    /// Three workspace diagnostics put a file in this state: a partial parse
131    /// (`source-parse-degraded`), no parse (`source-nesting-too-deep`), or no
132    /// read (`source-read-failure`). The token names the consequence rather than
133    /// either cause, so a future kind that leaves a discovered file partially
134    /// extracted carries the same value.
135    ///
136    /// Dependency findings never carry this value: the file they name is a
137    /// `package.json`, not a parsed source module.
138    IncompleteFileAnalysis,
139    /// A module whose import list feeds this verdict was not analyzed, so the
140    /// import that would have credited this finding may never have been seen.
141    ///
142    /// The cause is any workspace diagnostic that leaves a source file's
143    /// imports unseen: a partial parse (`source-parse-degraded`), no parse
144    /// (`source-nesting-too-deep`), no read (`source-read-failure`), or a skip
145    /// by discovery before the read (`skipped-large-file`,
146    /// `skipped-minified-file`, `skipped-source-dotdir`). The token names the
147    /// class rather than any one cause.
148    ///
149    /// Which modules feed the verdict differs by array, and the caveat is
150    /// emitted only when a degraded module is actually one of them:
151    ///
152    /// - `unused_files[]`, `unused_exports[]`, and `unused_types[]` rest on
153    ///   reachability, so only a degraded module that is itself observed
154    ///   reachable can change the verdict. When every degraded module is
155    ///   unreachable the caveat is absent, and soundly: the FIRST missing edge
156    ///   on any entry-point path leaves from a module whose every predecessor
157    ///   edge was observed, so that module is observed reachable. A file the
158    ///   run never read has no module and no graph node, so its reachability
159    ///   is not observable at all and that narrowing cannot be applied: any
160    ///   skipped or unreadable source caveats every reachability verdict in
161    ///   the run.
162    /// - the member arrays (`unused_enum_members[]`, `unused_class_members[]`,
163    ///   `unused_store_members[]`) do not rest on reachability at all: member
164    ///   usage is collected by walking every module the run resolved,
165    ///   reachable or not, so this narrowing does not apply to them either.
166    ///   Same unnarrowed condition as the dependency arrays below, plus the
167    ///   per-finding value above when the member's own file is the one that
168    ///   was incompletely analyzed.
169    /// - the dependency arrays rest on whether ANY module in the project
170    ///   imports the package specifier, reachable or not, so any degraded
171    ///   parse anywhere can hide the import that would have credited the
172    ///   package. Reachability does not narrow that one.
173    ///
174    /// The limit, stated because an approximation presented as exact is worse
175    /// than nothing: this is a RUN-level condition, not proof that a degraded
176    /// module imports this path or package. An import the parser never saw
177    /// cannot be attributed to a target, so the link cannot be narrowed
178    /// further without re-reading the source. Read `workspace_diagnostics[]`
179    /// for which files degraded.
180    IncompleteImportGraph,
181}
182
183impl ReachabilityCaveat {
184    /// The wire token.
185    #[must_use]
186    pub const fn token(self) -> &'static str {
187        match self {
188            Self::IncompleteFileAnalysis => "incomplete-file-analysis",
189            Self::IncompleteImportGraph => "incomplete-import-graph",
190        }
191    }
192
193    /// A one-line explanation for human and agent-facing renderers.
194    ///
195    /// Neither sentence names a single cause. A degraded parse is only one of
196    /// the ways a file goes unread: it may also have been unreadable, or
197    /// skipped before it was ever opened (oversized, minified, in a dotdir).
198    /// Naming the parse case alone sent a reader whose run was degraded by the
199    /// size guard hunting for parse errors that do not exist, so both messages
200    /// point at `workspace_diagnostics[]`, which names the actual files.
201    #[must_use]
202    pub const fn message(self) -> &'static str {
203        match self {
204            Self::IncompleteFileAnalysis => {
205                "low: this file was not fully analyzed, so its extracted exports and imports may be incomplete; see workspace_diagnostics[]"
206            }
207            Self::IncompleteImportGraph => {
208                "low: a module this run did not fully read may hold an import that would credit this; see workspace_diagnostics[]"
209            }
210        }
211    }
212
213    /// A compact label for a one-line human renderer, where the full
214    /// [`Self::message`] would not fit next to the finding.
215    #[must_use]
216    pub const fn short_label(self) -> &'static str {
217        match self {
218            Self::IncompleteFileAnalysis => "incomplete file analysis",
219            Self::IncompleteImportGraph => "incomplete import graph",
220        }
221    }
222}
223
224/// The compact labels of `caveats`, joined for a one-line renderer, or `None`
225/// when there is nothing to say.
226#[must_use]
227pub fn caveat_labels(caveats: &[ReachabilityCaveat]) -> Option<String> {
228    if caveats.is_empty() {
229        return None;
230    }
231    let labels: Vec<&str> = caveats
232        .iter()
233        .map(|caveat| ReachabilityCaveat::short_label(*caveat))
234        .collect();
235    Some(labels.join(", "))
236}
237
238/// The compact parenthetical a one-line human renderer appends to a finding
239/// carrying `caveats`, or `None` when there is nothing to say. Shared by every
240/// dead-code section so the suffix reads the same everywhere.
241#[must_use]
242pub fn caveat_suffix(caveats: &[ReachabilityCaveat]) -> Option<String> {
243    caveat_labels(caveats).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
244}
245
246/// The opening of the parenthetical [`caveat_suffix`] renders. Public because
247/// one consumer can only see the rendered description: the CI review formats
248/// build their comments from CodeClimate issues, whose `description` is the
249/// only place the caveat survives (the CodeClimate wire is a published
250/// contract with no field for it). Recognising the marker is what lets those
251/// formats withhold a one-click mutation.
252pub const CAVEAT_SUFFIX_MARKER: &str = " (caveat: ";
253
254/// Whether a rendered finding description already carries a caveat
255/// parenthetical, for a surface holding the string rather than the typed
256/// finding.
257///
258/// Lives here, next to the renderer, so the producer and the recogniser cannot
259/// drift; `a_rendered_suffix_is_recognised_by_the_marker` pins the pair.
260#[must_use]
261pub fn description_carries_caveat(description: &str) -> bool {
262    description.contains(CAVEAT_SUFFIX_MARKER)
263}
264
265/// The compact label for one wire token, for a renderer that reads
266/// `reachability_caveats[]` back off a serialized envelope instead of holding
267/// the typed findings.
268///
269/// The value set is OPEN, exactly as the wire documentation says: a token this
270/// build does not recognise is still a caveat, so it is rendered as itself with
271/// its separators relaxed into spaces rather than dropped. Dropping it would
272/// turn a finding whose evidence is incomplete back into a confident one,
273/// which is the failure this whole mechanism exists to prevent.
274#[must_use]
275pub fn caveat_label_for_token(token: &str) -> String {
276    match token {
277        "incomplete-file-analysis" => {
278            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteFileAnalysis).to_owned()
279        }
280        "incomplete-import-graph" => {
281            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteImportGraph).to_owned()
282        }
283        other => other.replace('-', " "),
284    }
285}
286
287/// The joined compact labels for wire tokens, or `None` when there are none.
288/// The token-side twin of [`caveat_labels`], for renderers driven by a
289/// serialized envelope rather than by typed findings.
290#[must_use]
291pub fn caveat_labels_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
292    let labels: Vec<String> = tokens.into_iter().map(caveat_label_for_token).collect();
293    if labels.is_empty() {
294        return None;
295    }
296    Some(labels.join(", "))
297}
298
299/// The token-side twin of [`caveat_suffix`], so an envelope-driven renderer
300/// appends the same parenthetical as a findings-driven one.
301#[must_use]
302pub fn caveat_suffix_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
303    caveat_labels_for_tokens(tokens).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
304}
305
306/// The note every mutating action carries once [`MutationEvidence`] withholds
307/// it. One string, so the CLI action array, the LSP diagnostic, and the MCP
308/// tool contract all say the same thing about the same finding.
309pub const INCOMPLETE_EVIDENCE_NOTE: &str = "Evidence is incomplete: a file this run did not fully analyze may hold the reference that \
310     credits this finding, so this mutation is not applied automatically. Resolve the files named \
311     in workspace_diagnostics[] and re-run, or confirm and remove it by hand.";
312
313/// The one question every mutation surface asks before it offers, plans, or
314/// performs a dead-code finding's removal.
315///
316/// A finding whose reachability verdict rests on a file the run never fully
317/// read is still REPORTED, always: a caveat withholds no finding, changes no
318/// severity, and moves no exit code. What it withholds is the automation. The
319/// predicate lives here, next to the findings, rather than in any one consumer,
320/// because it was re-derived per surface three times and a fourth door opened
321/// every time: `fallow fix`, the LSP quick fix, and the `auto_fixable` flag an
322/// agent plans against each answered it differently. Every one of those now
323/// calls [`Self::may_auto_apply_mutation`], so a sixth finding type or a fourth
324/// mutation surface cannot silently opt out.
325///
326/// Implemented only by the findings that can carry a caveat. A finding type
327/// that exposes an auto-fixable mutation and does NOT implement this trait is
328/// the bug this trait exists to make visible; `every_auto_fixable_dead_code_
329/// mutation_is_gated` in this module's tests pins that.
330pub trait MutationEvidence {
331    /// The advisory caveats recorded on the reachability verdict behind this
332    /// finding. Empty when the run analyzed every file it discovered.
333    fn reachability_caveats(&self) -> &[ReachabilityCaveat];
334
335    /// Whether this finding's mutation may be applied without a human first
336    /// being told the evidence is incomplete. THE gate: never re-derive it,
337    /// never widen it per surface.
338    fn may_auto_apply_mutation(&self) -> bool {
339        self.reachability_caveats().is_empty()
340    }
341}
342
343/// Record a run's caveats on a finding, enforcing [`MutationEvidence`] on its
344/// typed `actions` in the same step.
345///
346/// Separate from [`MutationEvidence`] so a read-only consumer (the fixer, the
347/// LSP, a renderer) depends only on the question and never on the answer's
348/// setter. `annotate` in the analysis layer is the single writer.
349pub trait CaveatedFinding: MutationEvidence {
350    /// Store `caveats` and downgrade every mutating action the gate now
351    /// withholds. The field itself stays `pub` (a renderer test builds an
352    /// already-caveated fixture directly, without running the annotation
353    /// pass); every non-test writer goes through this setter instead of the
354    /// field so the downgrade travels with the write.
355    fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>);
356}
357
358/// Downgrade every `Fix` action in `actions` when `caveats` is non-empty, so
359/// the `auto_fixable` flag an agent plans against matches what `fallow fix`
360/// will actually do. Only ever downgrades: a surface that has already decided
361/// a mutation is unsafe for its own reasons keeps that decision.
362fn withhold_caveated_mutations(actions: &mut [IssueAction], caveats: &[ReachabilityCaveat]) {
363    if caveats.is_empty() {
364        return;
365    }
366    for action in actions {
367        let IssueAction::Fix(fix) = action else {
368            continue;
369        };
370        fix.auto_fixable = false;
371        fix.note = Some(match fix.note.take() {
372            Some(existing) => format!("{existing}. {INCOMPLETE_EVIDENCE_NOTE}"),
373            None => INCOMPLETE_EVIDENCE_NOTE.to_string(),
374        });
375    }
376}
377
378/// Implement the gate for a finding wrapper carrying a `reachability_caveats`
379/// field alongside a typed `actions` array. A new caveated finding type adds
380/// one line here rather than a new per-surface branch.
381macro_rules! impl_caveated_finding {
382    ($($finding:ty),+ $(,)?) => {
383        $(
384            impl MutationEvidence for $finding {
385                fn reachability_caveats(&self) -> &[ReachabilityCaveat] {
386                    &self.reachability_caveats
387                }
388            }
389
390            impl CaveatedFinding for $finding {
391                fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>) {
392                    withhold_caveated_mutations(&mut self.actions, &caveats);
393                    self.reachability_caveats = caveats;
394                }
395            }
396        )+
397    };
398}
399
400/// Wire-shape envelope for an [`UnusedFile`] finding. The bare finding
401/// flattens in via `#[serde(flatten)]`, with a typed `actions` array
402/// populated at construction time and the audit-pass `introduced` flag
403/// attached as an optional sibling.
404#[derive(Debug, Clone, Serialize, Deserialize)]
405#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
406pub struct UnusedFileFinding {
407    /// The underlying dead-code entry.
408    #[serde(flatten)]
409    pub file: UnusedFile,
410    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
411    /// `~<k>` suffix when several findings of one type share an identity.
412    /// Line and column are not inputs, so the id survives line shifts,
413    /// reformats and reorders. A rename of the file or the symbol gives a
414    /// new id. Absent in output from older versions.
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub finding_id: Option<String>,
417    /// Suggested next steps: a `delete-file` primary and a `suppress-file`
418    /// secondary. Always emitted (possibly empty for forward-compat).
419    pub actions: Vec<IssueAction>,
420    /// Set by the audit pass when this finding is introduced relative to
421    /// the merge-base. `None` when serialized directly from Rust.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub introduced: Option<AuditIntroduced>,
424    /// Gate severity of this finding after `rules` and `overrides[].rules`
425    /// resolve for its path. CI formats read it for the annotation, SARIF
426    /// and CodeClimate level. Absent in output from older versions. Not
427    /// part of the finding identity, baseline keys or fingerprints.
428    #[serde(
429        default,
430        skip_serializing_if = "Option::is_none",
431        deserialize_with = "deserialize_effective_severity"
432    )]
433    pub effective_severity: Option<EffectiveSeverity>,
434    /// Advisory caveats on the reachability verdict behind this finding.
435    /// Sorted, deduplicated, and omitted from the wire when empty, so a run
436    /// that analyzed every discovered file is byte-identical. Never gates the
437    /// finding or the `delete-file` action, though `fallow fix` does withhold
438    /// the removal of a caveated finding as low confidence.
439    #[serde(default, skip_serializing_if = "Vec::is_empty")]
440    pub reachability_caveats: Vec<ReachabilityCaveat>,
441}
442
443impl UnusedFileFinding {
444    /// Build the wrapper from a raw [`UnusedFile`], computing the typed
445    /// `actions` array inline. `introduced` stays `None` and is set later
446    /// by `annotate_dead_code_json` if the audit pass runs.
447    #[must_use]
448    pub fn with_actions(file: UnusedFile) -> Self {
449        let actions = vec![
450            IssueAction::Fix(FixAction {
451                kind: FixActionType::DeleteFile,
452                auto_fixable: false,
453                description: "Delete this file".to_string(),
454                note: Some(
455                    "File deletion may remove runtime functionality not visible to static analysis"
456                        .to_string(),
457                ),
458                available_in_catalogs: None,
459                suggested_target: None,
460            }),
461            IssueAction::SuppressFile(SuppressFileAction {
462                kind: SuppressFileKind::SuppressFile,
463                auto_fixable: false,
464                description: "Suppress with a file-level comment at the top of the file"
465                    .to_string(),
466                comment: "// fallow-ignore-file unused-file".to_string(),
467            }),
468        ];
469        Self {
470            finding_id: None,
471            file,
472            actions,
473            introduced: None,
474            effective_severity: None,
475            reachability_caveats: Vec::new(),
476        }
477    }
478}
479
480/// Wire-shape envelope for a [`PrivateTypeLeak`] finding. Mirrors
481/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
482/// `actions` array (`export-type` primary plus `suppress-line` secondary).
483#[derive(Debug, Clone, Serialize, Deserialize)]
484#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
485pub struct PrivateTypeLeakFinding {
486    /// The underlying dead-code entry.
487    #[serde(flatten)]
488    pub leak: PrivateTypeLeak,
489    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
490    /// `~<k>` suffix when several findings of one type share an identity.
491    /// Line and column are not inputs, so the id survives line shifts,
492    /// reformats and reorders. A rename of the file or the symbol gives a
493    /// new id. Absent in output from older versions.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub finding_id: Option<String>,
496    /// Suggested next steps. Always emitted (possibly empty for
497    /// forward-compat).
498    pub actions: Vec<IssueAction>,
499    /// Set by the audit pass when this finding is introduced relative to
500    /// the merge-base.
501    #[serde(default, skip_serializing_if = "Option::is_none")]
502    pub introduced: Option<AuditIntroduced>,
503    /// Gate severity of this finding after `rules` and `overrides[].rules`
504    /// resolve for its path. CI formats read it for the annotation, SARIF
505    /// and CodeClimate level. Absent in output from older versions. Not
506    /// part of the finding identity, baseline keys or fingerprints.
507    #[serde(
508        default,
509        skip_serializing_if = "Option::is_none",
510        deserialize_with = "deserialize_effective_severity"
511    )]
512    pub effective_severity: Option<EffectiveSeverity>,
513}
514
515impl PrivateTypeLeakFinding {
516    /// Build the wrapper from a raw [`PrivateTypeLeak`].
517    #[must_use]
518    pub fn with_actions(leak: PrivateTypeLeak) -> Self {
519        let actions = vec![
520            IssueAction::Fix(FixAction {
521                kind: FixActionType::ExportType,
522                auto_fixable: false,
523                description: "Export the referenced private type by name".to_string(),
524                note: Some(
525                    "Keep the type exported while it is part of a public signature".to_string(),
526                ),
527                available_in_catalogs: None,
528                suggested_target: None,
529            }),
530            IssueAction::SuppressLine(SuppressLineAction {
531                kind: SuppressLineKind::SuppressLine,
532                auto_fixable: false,
533                description: "Suppress with an inline comment above the line".to_string(),
534                comment: "// fallow-ignore-next-line private-type-leak".to_string(),
535                scope: None,
536            }),
537        ];
538        Self {
539            finding_id: None,
540            leak,
541            actions,
542            introduced: None,
543            effective_severity: None,
544        }
545    }
546}
547
548/// Wire-shape envelope for a [`DeprecatedExportInUse`] finding. Carries a
549/// manual `migrate-deprecated-export` primary action plus a `suppress-line`
550/// secondary. Never auto-fixable: fallow does not rewrite consumers.
551#[derive(Debug, Clone, Serialize, Deserialize)]
552#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
553pub struct DeprecatedExportInUseFinding {
554    /// The underlying dead-code entry.
555    #[serde(flatten)]
556    pub export: DeprecatedExportInUse,
557    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
558    /// `~<k>` suffix when several findings of one type share an identity.
559    /// Line and column are not inputs, so the id survives line shifts,
560    /// reformats and reorders. A rename of the file or the symbol gives a
561    /// new id. Absent in output from older versions.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub finding_id: Option<String>,
564    /// Suggested next steps. Always emitted (possibly empty for
565    /// forward-compat).
566    pub actions: Vec<IssueAction>,
567    /// Set by the audit pass when this finding is introduced relative to
568    /// the merge-base.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub introduced: Option<AuditIntroduced>,
571    /// Gate severity of this finding after `rules` and `overrides[].rules`
572    /// resolve for its path. CI formats read it for the annotation, SARIF
573    /// and CodeClimate level. Absent in output from older versions. Not
574    /// part of the finding identity, baseline keys or fingerprints.
575    #[serde(
576        default,
577        skip_serializing_if = "Option::is_none",
578        deserialize_with = "deserialize_effective_severity"
579    )]
580    pub effective_severity: Option<EffectiveSeverity>,
581}
582
583impl DeprecatedExportInUseFinding {
584    /// Build the wrapper from a raw [`DeprecatedExportInUse`].
585    #[must_use]
586    pub fn with_actions(export: DeprecatedExportInUse) -> Self {
587        let trace_hint = format!(
588            "For the full consumer list, run `fallow dead-code --trace <path>:{}` with the `path` of this finding.",
589            export.export_name
590        );
591        let note = if export.public_api {
592            format!(
593                "This export is public API. External consumers are not visible, so do not remove it on this evidence alone. {trace_hint}"
594            )
595        } else {
596            format!(
597                "Move each consumer to the replacement that the deprecation message names, then remove the export. {trace_hint}"
598            )
599        };
600        let actions = vec![
601            IssueAction::Fix(FixAction {
602                kind: FixActionType::MigrateDeprecatedExport,
603                auto_fixable: false,
604                description: "Move the consumers off the deprecated export".to_string(),
605                note: Some(note),
606                available_in_catalogs: None,
607                suggested_target: None,
608            }),
609            suppress_line("// fallow-ignore-next-line deprecated-export-in-use"),
610        ];
611        Self {
612            finding_id: None,
613            export,
614            actions,
615            introduced: None,
616            effective_severity: None,
617        }
618    }
619}
620
621/// Wire-shape envelope for an [`UnresolvedImport`] finding. Mirrors
622/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
623/// `actions` array (`resolve-import` primary plus config and inline
624/// suppression actions).
625#[derive(Debug, Clone, Serialize, Deserialize)]
626#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
627pub struct UnresolvedImportFinding {
628    /// The underlying dead-code entry.
629    #[serde(flatten)]
630    pub import: UnresolvedImport,
631    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
632    /// `~<k>` suffix when several findings of one type share an identity.
633    /// Line and column are not inputs, so the id survives line shifts,
634    /// reformats and reorders. A rename of the file or the symbol gives a
635    /// new id. Absent in output from older versions.
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub finding_id: Option<String>,
638    /// Suggested next steps. Always emitted (possibly empty for
639    /// forward-compat).
640    pub actions: Vec<IssueAction>,
641    /// Set by the audit pass when this finding is introduced relative to
642    /// the merge-base.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub introduced: Option<AuditIntroduced>,
645    /// Gate severity of this finding after `rules` and `overrides[].rules`
646    /// resolve for its path. CI formats read it for the annotation, SARIF
647    /// and CodeClimate level. Absent in output from older versions. Not
648    /// part of the finding identity, baseline keys or fingerprints.
649    #[serde(
650        default,
651        skip_serializing_if = "Option::is_none",
652        deserialize_with = "deserialize_effective_severity"
653    )]
654    pub effective_severity: Option<EffectiveSeverity>,
655}
656
657impl UnresolvedImportFinding {
658    /// Build the wrapper from a raw [`UnresolvedImport`].
659    #[must_use]
660    pub fn with_actions(import: UnresolvedImport) -> Self {
661        let actions = vec![
662            IssueAction::Fix(FixAction {
663                kind: FixActionType::ResolveImport,
664                auto_fixable: false,
665                description: "Fix the import specifier or install the missing module".to_string(),
666                note: Some(
667                    "Verify the module path and check tsconfig paths configuration".to_string(),
668                ),
669                available_in_catalogs: None,
670                suggested_target: None,
671            }),
672            IssueAction::AddToConfig(AddToConfigAction {
673                kind: AddToConfigKind::AddToConfig,
674                auto_fixable: false,
675                description: format!(
676                    "Add \"{}\" to ignoreUnresolvedImports in fallow config",
677                    import.specifier
678                ),
679                config_key: "ignoreUnresolvedImports".to_string(),
680                value: AddToConfigValue::Scalar(import.specifier.clone()),
681                value_schema: Some(
682                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreUnresolvedImports/items"
683                        .to_string(),
684                ),
685            }),
686            IssueAction::SuppressLine(SuppressLineAction {
687                kind: SuppressLineKind::SuppressLine,
688                auto_fixable: false,
689                description: "Suppress with an inline comment above the line".to_string(),
690                comment: "// fallow-ignore-next-line unresolved-import".to_string(),
691                scope: None,
692            }),
693        ];
694        Self {
695            finding_id: None,
696            import,
697            actions,
698            introduced: None,
699            effective_severity: None,
700        }
701    }
702}
703
704/// Wire-shape envelope for a [`CircularDependency`] finding. Mirrors
705/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
706/// `actions` array (`refactor-cycle` primary plus `suppress-line`
707/// secondary).
708#[derive(Debug, Clone, Serialize, Deserialize)]
709#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
710pub struct CircularDependencyFinding {
711    /// The underlying dead-code entry.
712    #[serde(flatten)]
713    pub cycle: CircularDependency,
714    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
715    /// `~<k>` suffix when several findings of one type share an identity.
716    /// Line and column are not inputs, so the id survives line shifts,
717    /// reformats and reorders. A rename of the file or the symbol gives a
718    /// new id. Absent in output from older versions.
719    #[serde(default, skip_serializing_if = "Option::is_none")]
720    pub finding_id: Option<String>,
721    /// Suggested next steps. Always emitted (possibly empty for
722    /// forward-compat).
723    pub actions: Vec<IssueAction>,
724    /// Set by the audit pass when this finding is introduced relative to
725    /// the merge-base.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub introduced: Option<AuditIntroduced>,
728    /// Gate severity of this finding after `rules` and `overrides[].rules`
729    /// resolve for its path. CI formats read it for the annotation, SARIF
730    /// and CodeClimate level. Absent in output from older versions. Not
731    /// part of the finding identity, baseline keys or fingerprints.
732    #[serde(
733        default,
734        skip_serializing_if = "Option::is_none",
735        deserialize_with = "deserialize_effective_severity"
736    )]
737    pub effective_severity: Option<EffectiveSeverity>,
738}
739
740impl CircularDependencyFinding {
741    /// Build the wrapper from a raw [`CircularDependency`].
742    #[must_use]
743    pub fn with_actions(cycle: CircularDependency) -> Self {
744        let actions = vec![
745            IssueAction::Fix(FixAction {
746                kind: FixActionType::RefactorCycle,
747                auto_fixable: false,
748                description: "Extract shared logic into a separate module to break the cycle"
749                    .to_string(),
750                note: Some(
751                    "Circular imports can cause initialization issues and make code harder to reason about"
752                        .to_string(),
753                ),
754                available_in_catalogs: None,
755                suggested_target: None,
756            }),
757            IssueAction::SuppressLine(SuppressLineAction {
758                kind: SuppressLineKind::SuppressLine,
759                auto_fixable: false,
760                description: "Suppress with an inline comment above the line".to_string(),
761                comment: "// fallow-ignore-next-line circular-dependency".to_string(),
762                scope: None,
763            }),
764        ];
765        Self {
766            finding_id: None,
767            cycle,
768            actions,
769            introduced: None,
770            effective_severity: None,
771        }
772    }
773}
774
775/// Wire-shape envelope for a [`ReExportCycle`] finding. Mirrors
776/// [`CircularDependencyFinding`]: flattens the bare finding and carries a
777/// typed `actions` array (`refactor-re-export-cycle` informational primary
778/// plus `suppress-file` secondary; cycles are file-scoped so a single
779/// file-level suppression on the alphabetically-first member breaks the
780/// cycle, and no `// fallow-ignore-next-line` form makes sense because the
781/// diagnostic is anchored at line 1 col 0 of each member).
782#[derive(Debug, Clone, Serialize, Deserialize)]
783#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
784pub struct ReExportCycleFinding {
785    /// The underlying dead-code entry.
786    #[serde(flatten)]
787    pub cycle: ReExportCycle,
788    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
789    /// `~<k>` suffix when several findings of one type share an identity.
790    /// Line and column are not inputs, so the id survives line shifts,
791    /// reformats and reorders. A rename of the file or the symbol gives a
792    /// new id. Absent in output from older versions.
793    #[serde(default, skip_serializing_if = "Option::is_none")]
794    pub finding_id: Option<String>,
795    /// Suggested next steps. Always emitted (possibly empty for
796    /// forward-compat).
797    pub actions: Vec<IssueAction>,
798    /// Set by the audit pass when this finding is introduced relative to
799    /// the merge-base.
800    #[serde(default, skip_serializing_if = "Option::is_none")]
801    pub introduced: Option<AuditIntroduced>,
802    /// Gate severity of this finding after `rules` and `overrides[].rules`
803    /// resolve for its path. CI formats read it for the annotation, SARIF
804    /// and CodeClimate level. Absent in output from older versions. Not
805    /// part of the finding identity, baseline keys or fingerprints.
806    #[serde(
807        default,
808        skip_serializing_if = "Option::is_none",
809        deserialize_with = "deserialize_effective_severity"
810    )]
811    pub effective_severity: Option<EffectiveSeverity>,
812}
813
814impl ReExportCycleFinding {
815    /// Build the wrapper from a raw [`ReExportCycle`].
816    ///
817    /// The `SuppressFile` action targets the alphabetically-first member
818    /// (`cycle.files[0]`; the `files` Vec is already sorted at graph layer);
819    /// for multi-node cycles the description names the other members so
820    /// consumers see context for why one file-level suppression suffices.
821    #[must_use]
822    pub fn with_actions(cycle: ReExportCycle) -> Self {
823        // The description is a path-free hint about the suppression's
824        // structural effect; the cycle's member list already ships in the
825        // sibling `files` field, so consumers can correlate without
826        // re-reading the description (and absolute paths cannot leak in
827        // here, which the wrapper has no root-prefix context to strip).
828        let suppress_description = match cycle.kind {
829            ReExportCycleKind::SelfLoop => {
830                "Suppress with a file-level comment at the top of this file. \
831                 The cycle is a self-loop, so the suppression covers the entire finding."
832                    .to_string()
833            }
834            ReExportCycleKind::MultiNode => {
835                "Suppress with a file-level comment at the top of this file. \
836                 One suppression on any member breaks the cycle for every member \
837                 (see the sibling `files` array)."
838                    .to_string()
839            }
840        };
841        let actions = vec![
842            IssueAction::Fix(FixAction {
843                kind: FixActionType::RefactorReExportCycle,
844                auto_fixable: false,
845                description: "Remove one `export * from` (or `export { ... } from`) \
846                              statement on any one member to break the cycle"
847                    .to_string(),
848                note: Some(
849                    "Re-export cycles are structurally a no-op: chain propagation through \
850                     the loop never reaches a terminating module, so imports from any member \
851                     may silently come up empty."
852                        .to_string(),
853                ),
854                available_in_catalogs: None,
855                suggested_target: None,
856            }),
857            IssueAction::SuppressFile(SuppressFileAction {
858                kind: SuppressFileKind::SuppressFile,
859                auto_fixable: false,
860                description: suppress_description,
861                comment: "// fallow-ignore-file re-export-cycle".to_string(),
862            }),
863        ];
864        Self {
865            finding_id: None,
866            cycle,
867            actions,
868            introduced: None,
869            effective_severity: None,
870        }
871    }
872}
873
874/// Wire-shape envelope for a [`PackageCycle`] finding. Mirrors
875/// [`CircularDependencyFinding`]: flattens the bare finding and carries a
876/// typed `actions` array (`refactor-cycle` primary plus `suppress-line`
877/// secondary).
878#[derive(Debug, Clone, Serialize, Deserialize)]
879#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
880pub struct PackageCycleFinding {
881    /// The underlying dead-code entry.
882    #[serde(flatten)]
883    pub cycle: PackageCycle,
884    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
885    /// `~<k>` suffix when several findings of one type share an identity.
886    /// Line and column are not inputs, so the id survives line shifts,
887    /// reformats and reorders. A rename of the file or the symbol gives a
888    /// new id. Absent in output from older versions.
889    #[serde(default, skip_serializing_if = "Option::is_none")]
890    pub finding_id: Option<String>,
891    /// Suggested next steps. Always emitted (possibly empty for
892    /// forward-compat).
893    pub actions: Vec<IssueAction>,
894    /// Set by the audit pass when this finding is introduced relative to
895    /// the merge-base.
896    #[serde(default, skip_serializing_if = "Option::is_none")]
897    pub introduced: Option<AuditIntroduced>,
898    /// Gate severity of this finding after `rules` and `overrides[].rules`
899    /// resolve for its path. CI formats read it for the annotation, SARIF
900    /// and CodeClimate level. Absent in output from older versions. Not
901    /// part of the finding identity, baseline keys or fingerprints.
902    #[serde(
903        default,
904        skip_serializing_if = "Option::is_none",
905        deserialize_with = "deserialize_effective_severity"
906    )]
907    pub effective_severity: Option<EffectiveSeverity>,
908}
909
910impl PackageCycleFinding {
911    /// Build the wrapper from a raw [`PackageCycle`].
912    #[must_use]
913    pub fn with_actions(cycle: PackageCycle) -> Self {
914        let actions = vec![
915            IssueAction::Fix(FixAction {
916                kind: FixActionType::RefactorCycle,
917                auto_fixable: false,
918                description: "Remove the imports on one hop of the cycle, for example by \
919                              moving the shared code to a package that both packages import"
920                    .to_string(),
921                note: Some(
922                    "Packages that import each other cannot be built in dependency order"
923                        .to_string(),
924                ),
925                available_in_catalogs: None,
926                suggested_target: None,
927            }),
928            IssueAction::SuppressLine(SuppressLineAction {
929                kind: SuppressLineKind::SuppressLine,
930                auto_fixable: false,
931                description: "Suppress with an inline comment above the import. The cycle \
932                              is gone when every import on one hop is suppressed"
933                    .to_string(),
934                comment: "// fallow-ignore-next-line package-cycle".to_string(),
935                scope: None,
936            }),
937        ];
938        Self {
939            cycle,
940            finding_id: None,
941            actions,
942            introduced: None,
943            effective_severity: None,
944        }
945    }
946}
947
948/// Wire-shape envelope for a [`BoundaryViolation`] finding. Mirrors
949/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
950/// `actions` array (`refactor-boundary` primary plus `suppress-line`
951/// secondary).
952#[derive(Debug, Clone, Serialize, Deserialize)]
953#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
954pub struct BoundaryViolationFinding {
955    /// The underlying dead-code entry.
956    #[serde(flatten)]
957    pub violation: BoundaryViolation,
958    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
959    /// `~<k>` suffix when several findings of one type share an identity.
960    /// Line and column are not inputs, so the id survives line shifts,
961    /// reformats and reorders. A rename of the file or the symbol gives a
962    /// new id. Absent in output from older versions.
963    #[serde(default, skip_serializing_if = "Option::is_none")]
964    pub finding_id: Option<String>,
965    /// Suggested next steps. Always emitted (possibly empty for
966    /// forward-compat).
967    pub actions: Vec<IssueAction>,
968    /// Set by the audit pass when this finding is introduced relative to
969    /// the merge-base.
970    #[serde(default, skip_serializing_if = "Option::is_none")]
971    pub introduced: Option<AuditIntroduced>,
972    /// Gate severity of this finding after `rules` and `overrides[].rules`
973    /// resolve for its path. CI formats read it for the annotation, SARIF
974    /// and CodeClimate level. Absent in output from older versions. Not
975    /// part of the finding identity, baseline keys or fingerprints.
976    #[serde(
977        default,
978        skip_serializing_if = "Option::is_none",
979        deserialize_with = "deserialize_effective_severity"
980    )]
981    pub effective_severity: Option<EffectiveSeverity>,
982}
983
984impl BoundaryViolationFinding {
985    /// Build the wrapper from a raw [`BoundaryViolation`].
986    #[must_use]
987    pub fn with_actions(violation: BoundaryViolation) -> Self {
988        let actions = vec![
989            IssueAction::Fix(FixAction {
990                kind: FixActionType::RefactorBoundary,
991                auto_fixable: false,
992                description: "Move the import through an allowed zone or restructure the dependency"
993                    .to_string(),
994                note: Some(
995                    "This import crosses an architecture boundary that is not permitted by the configured rules"
996                        .to_string(),
997                ),
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 [`AbsentComponentProp`] finding. There is no safe
2003/// auto-fix: removing a declared prop is judgement-bearing (the prop may be part
2004/// of a deliberately-stable public component API). Actions are manual
2005/// remediation guidance plus a line-level suppress at the prop declaration.
2006#[derive(Debug, Clone, Serialize, Deserialize)]
2007#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2008pub struct AbsentComponentPropFinding {
2009    /// The underlying finding.
2010    #[serde(flatten)]
2011    pub prop: AbsentComponentProp,
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 AbsentComponentPropFinding {
2039    /// Build the wrapper from a raw [`AbsentComponentProp`]. Emits a manual
2040    /// fix action plus a line-level suppress.
2041    #[must_use]
2042    pub fn with_actions(prop: AbsentComponentProp) -> Self {
2043        let actions = vec![
2044            manual_framework_fix(
2045                FixActionType::ReviewComponentProp,
2046                "Review inspected callers, defaults and API intent",
2047                "Retain or suppress intentional stable props, or update the component manually; static analysis does not prove runtime unreachability.",
2048            ),
2049            suppress_line("// fallow-ignore-next-line absent-component-prop"),
2050        ];
2051        Self {
2052            finding_id: None,
2053            prop,
2054            actions,
2055            introduced: None,
2056            effective_severity: None,
2057        }
2058    }
2059}
2060
2061/// Wire-shape envelope for an [`UnusedComponentEmit`] finding. There is no safe
2062/// auto-fix: removing a declared emit is judgement-bearing (the event may be
2063/// part of a deliberately-stable public component API). Actions are manual
2064/// remediation guidance plus a line-level suppress at the emit declaration.
2065#[derive(Debug, Clone, Serialize, Deserialize)]
2066#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2067pub struct UnusedComponentEmitFinding {
2068    /// The underlying finding.
2069    #[serde(flatten)]
2070    pub emit: UnusedComponentEmit,
2071    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2072    /// `~<k>` suffix when several findings of one type share an identity.
2073    /// Line and column are not inputs, so the id survives line shifts,
2074    /// reformats and reorders. A rename of the file or the symbol gives a
2075    /// new id. Absent in output from older versions.
2076    #[serde(default, skip_serializing_if = "Option::is_none")]
2077    pub finding_id: Option<String>,
2078    /// Suggested next steps. Always emitted (possibly empty for
2079    /// forward-compat).
2080    pub actions: Vec<IssueAction>,
2081    /// Set by the audit pass when this finding is introduced relative to
2082    /// the merge-base.
2083    #[serde(default, skip_serializing_if = "Option::is_none")]
2084    pub introduced: Option<AuditIntroduced>,
2085    /// Gate severity of this finding after `rules` and `overrides[].rules`
2086    /// resolve for its path. CI formats read it for the annotation, SARIF
2087    /// and CodeClimate level. Absent in output from older versions. Not
2088    /// part of the finding identity, baseline keys or fingerprints.
2089    #[serde(
2090        default,
2091        skip_serializing_if = "Option::is_none",
2092        deserialize_with = "deserialize_effective_severity"
2093    )]
2094    pub effective_severity: Option<EffectiveSeverity>,
2095}
2096
2097impl UnusedComponentEmitFinding {
2098    /// Build the wrapper from a raw [`UnusedComponentEmit`]. Emits a manual
2099    /// fix action plus a line-level suppress.
2100    #[must_use]
2101    pub fn with_actions(emit: UnusedComponentEmit) -> Self {
2102        let actions = vec![
2103            manual_framework_fix(
2104                FixActionType::EmitComponentEvent,
2105                "Emit the declared event from the component, or remove it from the component API",
2106                "Manual review required: public component APIs can intentionally keep stable events for external listeners.",
2107            ),
2108            suppress_line("// fallow-ignore-next-line unused-component-emit"),
2109        ];
2110        Self {
2111            finding_id: None,
2112            emit,
2113            actions,
2114            introduced: None,
2115            effective_severity: None,
2116        }
2117    }
2118}
2119
2120/// Wire-shape envelope for an [`UnusedSvelteEvent`] finding. There is no safe
2121/// auto-fix: removing a dispatched event is judgement-bearing (the event may be
2122/// part of a deliberately-stable public component API, or a listener may be
2123/// added later). Actions are manual remediation guidance plus a line-level
2124/// suppress at the `dispatch` call.
2125#[derive(Debug, Clone, Serialize, Deserialize)]
2126#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2127pub struct UnusedSvelteEventFinding {
2128    /// The underlying finding.
2129    #[serde(flatten)]
2130    pub event: UnusedSvelteEvent,
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 symbol 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 UnusedSvelteEventFinding {
2158    /// Build the wrapper from a raw [`UnusedSvelteEvent`]. Emits a manual fix
2159    /// action plus a line-level suppress.
2160    #[must_use]
2161    pub fn with_actions(event: UnusedSvelteEvent) -> Self {
2162        let actions = vec![
2163            manual_framework_fix(
2164                FixActionType::WireSvelteEvent,
2165                "Add or forward a listener for this custom event, or remove the dispatch",
2166                "Manual review required: public Svelte component APIs can intentionally dispatch events for package consumers outside this project.",
2167            ),
2168            suppress_line("// fallow-ignore-next-line unused-svelte-event"),
2169        ];
2170        Self {
2171            finding_id: None,
2172            event,
2173            actions,
2174            introduced: None,
2175            effective_severity: None,
2176        }
2177    }
2178}
2179
2180/// Wire-shape envelope for a [`DuplicateExportAlias`] finding. There is no
2181/// safe auto-fix: a consumer outside the project can import any of the
2182/// names. Actions are manual remediation guidance plus a line-level
2183/// suppress.
2184#[derive(Debug, Clone, Serialize, Deserialize)]
2185#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2186pub struct DuplicateExportAliasFinding {
2187    /// The underlying finding.
2188    #[serde(flatten)]
2189    pub alias: DuplicateExportAlias,
2190    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2191    /// `~<k>` suffix when several findings of one type share an identity.
2192    /// Line and column are not inputs, so the id survives line shifts,
2193    /// reformats and reorders. A rename of the file or the binding gives a
2194    /// new id. Absent in output from older versions.
2195    #[serde(default, skip_serializing_if = "Option::is_none")]
2196    pub finding_id: Option<String>,
2197    /// Suggested next steps. Always emitted (possibly empty for
2198    /// forward-compat).
2199    pub actions: Vec<IssueAction>,
2200    /// Set by the audit pass when this finding is introduced relative to
2201    /// the merge-base.
2202    #[serde(default, skip_serializing_if = "Option::is_none")]
2203    pub introduced: Option<AuditIntroduced>,
2204    /// Gate severity of this finding after `rules` and `overrides[].rules`
2205    /// resolve for its path. CI formats read it for the annotation, SARIF
2206    /// and CodeClimate level. Absent in output from older versions. Not
2207    /// part of the finding identity, baseline keys or fingerprints.
2208    #[serde(
2209        default,
2210        skip_serializing_if = "Option::is_none",
2211        deserialize_with = "deserialize_effective_severity"
2212    )]
2213    pub effective_severity: Option<EffectiveSeverity>,
2214}
2215
2216impl DuplicateExportAliasFinding {
2217    /// Build the wrapper from a raw [`DuplicateExportAlias`]. Emits a manual
2218    /// fix action plus a line-level suppress.
2219    #[must_use]
2220    pub fn with_actions(alias: DuplicateExportAlias) -> Self {
2221        let actions = vec![
2222            manual_framework_fix(
2223                FixActionType::RemoveDuplicate,
2224                "Keep one export name for the binding and remove the other names",
2225                "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.",
2226            ),
2227            suppress_line("// fallow-ignore-next-line duplicate-export-alias"),
2228        ];
2229        Self {
2230            finding_id: None,
2231            alias,
2232            actions,
2233            introduced: None,
2234            effective_severity: None,
2235        }
2236    }
2237}
2238
2239/// 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
2240/// remediation guidance plus a line-level suppress.
2241#[derive(Debug, Clone, Serialize, Deserialize)]
2242#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2243pub struct UnusedEffectLayerFinding {
2244    /// The underlying finding.
2245    #[serde(flatten)]
2246    pub layer: UnusedEffectLayer,
2247    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2248    /// `~<k>` suffix when several findings of one type share an identity.
2249    /// Line and column are not inputs, so the id survives line shifts,
2250    /// reformats and reorders. A rename of the file or the symbol gives a
2251    /// new id. Absent in output from older versions.
2252    #[serde(default, skip_serializing_if = "Option::is_none")]
2253    pub finding_id: Option<String>,
2254    /// Suggested next steps. Always emitted (possibly empty for
2255    /// forward-compat).
2256    pub actions: Vec<IssueAction>,
2257    /// Set by the audit pass when this finding is introduced relative to
2258    /// the merge-base.
2259    #[serde(default, skip_serializing_if = "Option::is_none")]
2260    pub introduced: Option<AuditIntroduced>,
2261    /// Gate severity of this finding after `rules` and `overrides[].rules`
2262    /// resolve for its path. CI formats read it for the annotation, SARIF
2263    /// and CodeClimate level. Absent in output from older versions. Not
2264    /// part of the finding identity, baseline keys or fingerprints.
2265    #[serde(
2266        default,
2267        skip_serializing_if = "Option::is_none",
2268        deserialize_with = "deserialize_effective_severity"
2269    )]
2270    pub effective_severity: Option<EffectiveSeverity>,
2271}
2272
2273impl UnusedEffectLayerFinding {
2274    /// Build the wrapper from a raw [`UnusedEffectLayer`]. Emits a manual fix action plus
2275    /// a line-level suppress.
2276    #[must_use]
2277    pub fn with_actions(layer: UnusedEffectLayer) -> Self {
2278        let actions = vec![
2279            manual_framework_fix(
2280                FixActionType::ComposeEffectLayer,
2281                "Compose the layer into a layer that reaches a runtime, or remove it with its unused consumers",
2282                "Manual review required: remove the unused consumer layers first, then this layer. Code outside the analyzed project can still compose it.",
2283            ),
2284            suppress_line("// fallow-ignore-next-line unused-effect-layer"),
2285        ];
2286        Self {
2287            finding_id: None,
2288            layer,
2289            actions,
2290            introduced: None,
2291            effective_severity: None,
2292        }
2293    }
2294}
2295
2296/// 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
2297/// remediation guidance plus a line-level suppress.
2298#[derive(Debug, Clone, Serialize, Deserialize)]
2299#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2300pub struct UnusedTaggedErrorFinding {
2301    /// The underlying finding.
2302    #[serde(flatten)]
2303    pub error: UnusedTaggedError,
2304    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2305    /// `~<k>` suffix when several findings of one type share an identity.
2306    /// Line and column are not inputs, so the id survives line shifts,
2307    /// reformats and reorders. A rename of the file or the symbol gives a
2308    /// new id. Absent in output from older versions.
2309    #[serde(default, skip_serializing_if = "Option::is_none")]
2310    pub finding_id: Option<String>,
2311    /// Suggested next steps. Always emitted (possibly empty for
2312    /// forward-compat).
2313    pub actions: Vec<IssueAction>,
2314    /// Set by the audit pass when this finding is introduced relative to
2315    /// the merge-base.
2316    #[serde(default, skip_serializing_if = "Option::is_none")]
2317    pub introduced: Option<AuditIntroduced>,
2318    /// Gate severity of this finding after `rules` and `overrides[].rules`
2319    /// resolve for its path. CI formats read it for the annotation, SARIF
2320    /// and CodeClimate level. Absent in output from older versions. Not
2321    /// part of the finding identity, baseline keys or fingerprints.
2322    #[serde(
2323        default,
2324        skip_serializing_if = "Option::is_none",
2325        deserialize_with = "deserialize_effective_severity"
2326    )]
2327    pub effective_severity: Option<EffectiveSeverity>,
2328}
2329
2330impl UnusedTaggedErrorFinding {
2331    /// Build the wrapper from a raw [`UnusedTaggedError`]. Emits a manual fix action plus
2332    /// a line-level suppress.
2333    #[must_use]
2334    pub fn with_actions(error: UnusedTaggedError) -> Self {
2335        let actions = vec![
2336            manual_framework_fix(
2337                FixActionType::FailTaggedError,
2338                "Fail with this error where the condition occurs, or remove the class and its catchTag handlers",
2339                "Manual review required: consumers outside the analyzed project can construct or decode the error.",
2340            ),
2341            suppress_line("// fallow-ignore-next-line unused-tagged-error"),
2342        ];
2343        Self {
2344            finding_id: None,
2345            error,
2346            actions,
2347            introduced: None,
2348            effective_severity: None,
2349        }
2350    }
2351}
2352
2353/// Wire-shape envelope for an [`UnproducedCatchTag`] finding. There is no safe auto-fix: the handler can guard against a future producer. Actions are manual
2354/// remediation guidance plus a line-level suppress.
2355#[derive(Debug, Clone, Serialize, Deserialize)]
2356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2357pub struct UnproducedCatchTagFinding {
2358    /// The underlying finding.
2359    #[serde(flatten)]
2360    pub catch_tag: UnproducedCatchTag,
2361    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2362    /// `~<k>` suffix when several findings of one type share an identity.
2363    /// Line and column are not inputs, so the id survives line shifts,
2364    /// reformats and reorders. A rename of the file or the symbol gives a
2365    /// new id. Absent in output from older versions.
2366    #[serde(default, skip_serializing_if = "Option::is_none")]
2367    pub finding_id: Option<String>,
2368    /// Suggested next steps. Always emitted (possibly empty for
2369    /// forward-compat).
2370    pub actions: Vec<IssueAction>,
2371    /// Set by the audit pass when this finding is introduced relative to
2372    /// the merge-base.
2373    #[serde(default, skip_serializing_if = "Option::is_none")]
2374    pub introduced: Option<AuditIntroduced>,
2375    /// Gate severity of this finding after `rules` and `overrides[].rules`
2376    /// resolve for its path. CI formats read it for the annotation, SARIF
2377    /// and CodeClimate level. Absent in output from older versions. Not
2378    /// part of the finding identity, baseline keys or fingerprints.
2379    #[serde(
2380        default,
2381        skip_serializing_if = "Option::is_none",
2382        deserialize_with = "deserialize_effective_severity"
2383    )]
2384    pub effective_severity: Option<EffectiveSeverity>,
2385}
2386
2387impl UnproducedCatchTagFinding {
2388    /// Build the wrapper from a raw [`UnproducedCatchTag`]. Emits a manual fix action plus
2389    /// a line-level suppress.
2390    #[must_use]
2391    pub fn with_actions(catch_tag: UnproducedCatchTag) -> Self {
2392        let actions = vec![
2393            manual_framework_fix(
2394                FixActionType::RemoveCatchTagHandler,
2395                "Remove the handler for this tag, or fail with the error where the condition occurs",
2396                "Manual review required: a package or code outside the analyzed project can produce the tag.",
2397            ),
2398            suppress_line("// fallow-ignore-next-line unproduced-catch-tag"),
2399        ];
2400        Self {
2401            finding_id: None,
2402            catch_tag,
2403            actions,
2404            introduced: None,
2405            effective_severity: None,
2406        }
2407    }
2408}
2409
2410/// Wire-shape envelope for a [`PropDrillingChain`] finding. There is no safe
2411/// auto-fix: collapsing a drilling chain (colocate the consumer, lift to a
2412/// context, or compose the component) is a design decision. The only action is a
2413/// line-level suppress at the source hop's prop declaration. The rule defaults
2414/// to `off` (opt-in health signal), so this finding is dormant by default.
2415#[derive(Debug, Clone, Serialize, Deserialize)]
2416#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2417pub struct PropDrillingChainFinding {
2418    /// The underlying located chain.
2419    #[serde(flatten)]
2420    pub chain: PropDrillingChain,
2421    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2422    /// `~<k>` suffix when several findings of one type share an identity.
2423    /// Line and column are not inputs, so the id survives line shifts,
2424    /// reformats and reorders. A rename of the file or the symbol gives a
2425    /// new id. Absent in output from older versions.
2426    #[serde(default, skip_serializing_if = "Option::is_none")]
2427    pub finding_id: Option<String>,
2428    /// Suggested next steps. Always emitted (possibly empty for
2429    /// forward-compat).
2430    pub actions: Vec<IssueAction>,
2431    /// Set by the audit pass when this finding is introduced relative to
2432    /// the merge-base.
2433    #[serde(default, skip_serializing_if = "Option::is_none")]
2434    pub introduced: Option<AuditIntroduced>,
2435    /// Rule severity after resolving overrides for the source hop. An explicit
2436    /// `error` enforces the chain; `warn` stays advisory under strict flags.
2437    /// Saved reports use this value for CI levels. Absent in older output.
2438    /// Not part of finding identity, baseline keys or fingerprints.
2439    #[serde(
2440        default,
2441        skip_serializing_if = "Option::is_none",
2442        deserialize_with = "deserialize_effective_severity"
2443    )]
2444    pub effective_severity: Option<EffectiveSeverity>,
2445}
2446
2447impl PropDrillingChainFinding {
2448    /// Build the wrapper from a raw [`PropDrillingChain`]. Emits only a
2449    /// line-level suppress action anchored at the source hop: there is no safe
2450    /// auto-fix because collapsing the chain is a design decision (colocate,
2451    /// lift to context, or compose).
2452    #[must_use]
2453    pub fn with_actions(chain: PropDrillingChain) -> Self {
2454        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2455            kind: SuppressLineKind::SuppressLine,
2456            auto_fixable: false,
2457            description: "Suppress with an inline comment above the source prop declaration"
2458                .to_string(),
2459            comment: "// fallow-ignore-next-line prop-drilling".to_string(),
2460            scope: None,
2461        })];
2462        Self {
2463            finding_id: None,
2464            chain,
2465            actions,
2466            introduced: None,
2467            effective_severity: None,
2468        }
2469    }
2470}
2471
2472/// Wire-shape envelope for a [`ThinWrapper`] finding. There is no safe
2473/// auto-fix: inlining a thin wrapper at its call sites (or deleting it) is a
2474/// design decision. The only action is a line-level suppress at the wrapper's
2475/// definition. The rule defaults to `off` (opt-in health signal), so this
2476/// finding is dormant by default.
2477#[derive(Debug, Clone, Serialize, Deserialize)]
2478#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2479pub struct ThinWrapperFinding {
2480    /// The underlying located thin wrapper.
2481    #[serde(flatten)]
2482    pub wrapper: ThinWrapper,
2483    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2484    /// `~<k>` suffix when several findings of one type share an identity.
2485    /// Line and column are not inputs, so the id survives line shifts,
2486    /// reformats and reorders. A rename of the file or the symbol gives a
2487    /// new id. Absent in output from older versions.
2488    #[serde(default, skip_serializing_if = "Option::is_none")]
2489    pub finding_id: Option<String>,
2490    /// Suggested next steps. Always emitted (possibly empty for
2491    /// forward-compat).
2492    pub actions: Vec<IssueAction>,
2493    /// Set by the audit pass when this finding is introduced relative to
2494    /// the merge-base.
2495    #[serde(default, skip_serializing_if = "Option::is_none")]
2496    pub introduced: Option<AuditIntroduced>,
2497    /// Rule severity of this finding. Explicit errors enforce analysis gates;
2498    /// warnings stay advisory, including under strict flags. Saved reports
2499    /// retain this value for CI levels without the original config. Absent
2500    /// in output from older versions. Not part of finding identity, baseline
2501    /// keys or fingerprints.
2502    #[serde(
2503        default,
2504        skip_serializing_if = "Option::is_none",
2505        deserialize_with = "deserialize_effective_severity"
2506    )]
2507    pub effective_severity: Option<EffectiveSeverity>,
2508}
2509
2510impl ThinWrapperFinding {
2511    /// Build the wrapper from a raw [`ThinWrapper`]. Emits only a line-level
2512    /// suppress action anchored at the wrapper definition: there is no safe
2513    /// auto-fix because inlining or deleting the wrapper is a design decision.
2514    #[must_use]
2515    pub fn with_actions(wrapper: ThinWrapper) -> Self {
2516        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2517            kind: SuppressLineKind::SuppressLine,
2518            auto_fixable: false,
2519            description: "Suppress with an inline comment above the component definition"
2520                .to_string(),
2521            comment: "// fallow-ignore-next-line thin-wrapper".to_string(),
2522            scope: None,
2523        })];
2524        Self {
2525            finding_id: None,
2526            wrapper,
2527            actions,
2528            introduced: None,
2529            effective_severity: None,
2530        }
2531    }
2532}
2533
2534/// Wire-shape envelope for a [`DuplicatePropShape`] finding. There is no safe
2535/// auto-fix: extracting a shared `Props` type or a base component for a group of
2536/// same-shaped components is a design decision. The actions are manual guidance
2537/// (extract the shared shape) plus a line-level suppress at the component
2538/// definition and a file-level suppress escape hatch (mirroring the
2539/// route-collision multi-file model). The rule defaults to `off` (opt-in health
2540/// signal), so this finding is dormant by default.
2541#[derive(Debug, Clone, Serialize, Deserialize)]
2542#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2543pub struct DuplicatePropShapeFinding {
2544    /// The underlying duplicate-prop-shape entry.
2545    #[serde(flatten)]
2546    pub shape: DuplicatePropShape,
2547    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2548    /// `~<k>` suffix when several findings of one type share an identity.
2549    /// Line and column are not inputs, so the id survives line shifts,
2550    /// reformats and reorders. A rename of the file or the symbol gives a
2551    /// new id. Absent in output from older versions.
2552    #[serde(default, skip_serializing_if = "Option::is_none")]
2553    pub finding_id: Option<String>,
2554    /// Suggested next steps. Always emitted (possibly empty for
2555    /// forward-compat).
2556    pub actions: Vec<IssueAction>,
2557    /// Set by the audit pass when this finding is introduced relative to
2558    /// the merge-base.
2559    #[serde(default, skip_serializing_if = "Option::is_none")]
2560    pub introduced: Option<AuditIntroduced>,
2561    /// Rule severity of this finding. Explicit errors enforce analysis gates;
2562    /// warnings stay advisory, including under strict flags. Saved reports
2563    /// retain this value for CI levels without the original config. Absent
2564    /// in output from older versions. Not part of finding identity, baseline
2565    /// keys or fingerprints.
2566    #[serde(
2567        default,
2568        skip_serializing_if = "Option::is_none",
2569        deserialize_with = "deserialize_effective_severity"
2570    )]
2571    pub effective_severity: Option<EffectiveSeverity>,
2572}
2573
2574impl DuplicatePropShapeFinding {
2575    /// Build the wrapper from a raw [`DuplicatePropShape`]. Manual guidance is
2576    /// the primary action (extract a shared shape); a line-level suppress at the
2577    /// component definition and a file-level suppress escape hatch follow,
2578    /// mirroring the multi-file route-collision suppress model. There is no safe
2579    /// auto-fix because extracting a shared type or base component is a design
2580    /// decision.
2581    #[must_use]
2582    pub fn with_actions(shape: DuplicatePropShape) -> Self {
2583        let actions = vec![
2584            IssueAction::SuppressLine(SuppressLineAction {
2585                kind: SuppressLineKind::SuppressLine,
2586                auto_fixable: false,
2587                description: "Three or more components share this exact prop shape. Extract one \
2588                              shared `Props` type (or a base component) that every member reuses, \
2589                              or keep them separate if a per-variant divergence is planned. \
2590                              Suppress one member with an inline comment above the component \
2591                              definition."
2592                    .to_string(),
2593                comment: "// fallow-ignore-next-line duplicate-prop-shape".to_string(),
2594                scope: None,
2595            }),
2596            IssueAction::SuppressFile(SuppressFileAction {
2597                kind: SuppressFileKind::SuppressFile,
2598                auto_fixable: false,
2599                description: "Escape hatch: a file-level suppress silences this member but it \
2600                              still appears in its siblings' `sharing_components` (the group is \
2601                              real regardless of suppression)."
2602                    .to_string(),
2603                comment: "// fallow-ignore-file duplicate-prop-shape".to_string(),
2604            }),
2605        ];
2606        Self {
2607            finding_id: None,
2608            shape,
2609            actions,
2610            introduced: None,
2611            effective_severity: None,
2612        }
2613    }
2614}
2615
2616/// Wire-shape envelope for an [`UnusedComponentInput`] finding. There is no safe
2617/// auto-fix: removing a declared input is judgement-bearing (the input may be
2618/// part of a deliberately-stable public component API). The only action is a
2619/// line-level suppress at the input declaration.
2620#[derive(Debug, Clone, Serialize, Deserialize)]
2621#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2622pub struct UnusedComponentInputFinding {
2623    /// The underlying finding.
2624    #[serde(flatten)]
2625    pub input: UnusedComponentInput,
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 UnusedComponentInputFinding {
2653    /// Build the wrapper from a raw [`UnusedComponentInput`]. Emits only a
2654    /// line-level suppress action: there is no safe auto-fix because removing an
2655    /// input is a human decision (it may be part of a stable component API).
2656    #[must_use]
2657    pub fn with_actions(input: UnusedComponentInput) -> 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-input".to_string(),
2663            scope: None,
2664        })];
2665        Self {
2666            finding_id: None,
2667            input,
2668            actions,
2669            introduced: None,
2670            effective_severity: None,
2671        }
2672    }
2673}
2674
2675/// Wire-shape envelope for an [`UnusedComponentOutput`] finding. There is no safe
2676/// auto-fix: removing a declared output is judgement-bearing (the event may be
2677/// part of a deliberately-stable public component API). The only action is a
2678/// line-level suppress at the output declaration.
2679#[derive(Debug, Clone, Serialize, Deserialize)]
2680#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2681pub struct UnusedComponentOutputFinding {
2682    /// The underlying finding.
2683    #[serde(flatten)]
2684    pub output: UnusedComponentOutput,
2685    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2686    /// `~<k>` suffix when several findings of one type share an identity.
2687    /// Line and column are not inputs, so the id survives line shifts,
2688    /// reformats and reorders. A rename of the file or the symbol gives a
2689    /// new id. Absent in output from older versions.
2690    #[serde(default, skip_serializing_if = "Option::is_none")]
2691    pub finding_id: Option<String>,
2692    /// Suggested next steps. Always emitted (possibly empty for
2693    /// forward-compat).
2694    pub actions: Vec<IssueAction>,
2695    /// Set by the audit pass when this finding is introduced relative to
2696    /// the merge-base.
2697    #[serde(default, skip_serializing_if = "Option::is_none")]
2698    pub introduced: Option<AuditIntroduced>,
2699    /// Gate severity of this finding after `rules` and `overrides[].rules`
2700    /// resolve for its path. CI formats read it for the annotation, SARIF
2701    /// and CodeClimate level. Absent in output from older versions. Not
2702    /// part of the finding identity, baseline keys or fingerprints.
2703    #[serde(
2704        default,
2705        skip_serializing_if = "Option::is_none",
2706        deserialize_with = "deserialize_effective_severity"
2707    )]
2708    pub effective_severity: Option<EffectiveSeverity>,
2709}
2710
2711impl UnusedComponentOutputFinding {
2712    /// Build the wrapper from a raw [`UnusedComponentOutput`]. Emits only a
2713    /// line-level suppress action: there is no safe auto-fix because removing an
2714    /// output is a human decision (it may be part of a stable component API).
2715    #[must_use]
2716    pub fn with_actions(output: UnusedComponentOutput) -> Self {
2717        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
2718            kind: SuppressLineKind::SuppressLine,
2719            auto_fixable: false,
2720            description: "Suppress with an inline comment above the line".to_string(),
2721            comment: "// fallow-ignore-next-line unused-component-output".to_string(),
2722            scope: None,
2723        })];
2724        Self {
2725            finding_id: None,
2726            output,
2727            actions,
2728            introduced: None,
2729            effective_severity: None,
2730        }
2731    }
2732}
2733
2734/// Wire-shape envelope for a [`RouteCollision`] finding. A route collision is a
2735/// guaranteed `next build` failure, so the PRIMARY action is manual guidance
2736/// (move or merge one of the colliding files), NOT a suppress: suppressing a
2737/// build error never makes the build pass. A file-level suppress is offered as
2738/// an escape hatch only.
2739#[derive(Debug, Clone, Serialize, Deserialize)]
2740#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2741pub struct RouteCollisionFinding {
2742    /// The underlying route-collision entry.
2743    #[serde(flatten)]
2744    pub collision: RouteCollision,
2745    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2746    /// `~<k>` suffix when several findings of one type share an identity.
2747    /// Line and column are not inputs, so the id survives line shifts,
2748    /// reformats and reorders. A rename of the file or the symbol gives a
2749    /// new id. Absent in output from older versions.
2750    #[serde(default, skip_serializing_if = "Option::is_none")]
2751    pub finding_id: Option<String>,
2752    /// Suggested next steps. Always emitted (possibly empty for
2753    /// forward-compat).
2754    pub actions: Vec<IssueAction>,
2755    /// Set by the audit pass when this finding is introduced relative to
2756    /// the merge-base.
2757    #[serde(default, skip_serializing_if = "Option::is_none")]
2758    pub introduced: Option<AuditIntroduced>,
2759    /// Gate severity of this finding after `rules` and `overrides[].rules`
2760    /// resolve for its path. CI formats read it for the annotation, SARIF
2761    /// and CodeClimate level. Absent in output from older versions. Not
2762    /// part of the finding identity, baseline keys or fingerprints.
2763    #[serde(
2764        default,
2765        skip_serializing_if = "Option::is_none",
2766        deserialize_with = "deserialize_effective_severity"
2767    )]
2768    pub effective_severity: Option<EffectiveSeverity>,
2769}
2770
2771impl RouteCollisionFinding {
2772    /// Build the wrapper from a raw [`RouteCollision`]. The primary action is
2773    /// manual guidance because suppressing a guaranteed build error is never
2774    /// the right fix; a file-level suppress is the escape hatch only.
2775    #[must_use]
2776    pub fn with_actions(collision: RouteCollision) -> Self {
2777        let actions = vec![
2778            IssueAction::Fix(FixAction {
2779                kind: FixActionType::ResolveRouteCollision,
2780                auto_fixable: false,
2781                description: "Two or more files resolve to the same URL. Move or merge one so \
2782                              each URL has a single owner. Route groups `(name)` and parallel \
2783                              slots `@name` are the only legal same-URL shapes."
2784                    .to_string(),
2785                note: Some(
2786                    "Next.js fails the build with \"You cannot have two parallel pages that \
2787                     resolve to the same path\". See the sibling `conflicting_paths` array for \
2788                     the other files that own this URL."
2789                        .to_string(),
2790                ),
2791                available_in_catalogs: None,
2792                suggested_target: None,
2793            }),
2794            IssueAction::SuppressFile(SuppressFileAction {
2795                kind: SuppressFileKind::SuppressFile,
2796                auto_fixable: false,
2797                description: "Escape hatch only: a file-level suppress silences the finding but \
2798                              does NOT make `next build` pass. Prefer moving or merging a file."
2799                    .to_string(),
2800                comment: "// fallow-ignore-file route-collision".to_string(),
2801            }),
2802        ];
2803        Self {
2804            finding_id: None,
2805            collision,
2806            actions,
2807            introduced: None,
2808            effective_severity: None,
2809        }
2810    }
2811}
2812
2813/// Wire-shape envelope for a [`DynamicSegmentNameConflict`] finding. The
2814/// conflict is a Next.js dev / runtime error (`next build` does NOT catch it),
2815/// so the primary action is manual guidance (rename the dynamic segments to a
2816/// single consistent slug name), with a file-level suppress as escape hatch.
2817#[derive(Debug, Clone, Serialize, Deserialize)]
2818#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2819pub struct DynamicSegmentNameConflictFinding {
2820    /// The underlying dynamic-segment-name-conflict entry.
2821    #[serde(flatten)]
2822    pub conflict: DynamicSegmentNameConflict,
2823    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2824    /// `~<k>` suffix when several findings of one type share an identity.
2825    /// Line and column are not inputs, so the id survives line shifts,
2826    /// reformats and reorders. A rename of the file or the symbol gives a
2827    /// new id. Absent in output from older versions.
2828    #[serde(default, skip_serializing_if = "Option::is_none")]
2829    pub finding_id: Option<String>,
2830    /// Suggested next steps. Always emitted (possibly empty for
2831    /// forward-compat).
2832    pub actions: Vec<IssueAction>,
2833    /// Set by the audit pass when this finding is introduced relative to
2834    /// the merge-base.
2835    #[serde(default, skip_serializing_if = "Option::is_none")]
2836    pub introduced: Option<AuditIntroduced>,
2837    /// Gate severity of this finding after `rules` and `overrides[].rules`
2838    /// resolve for its path. CI formats read it for the annotation, SARIF
2839    /// and CodeClimate level. Absent in output from older versions. Not
2840    /// part of the finding identity, baseline keys or fingerprints.
2841    #[serde(
2842        default,
2843        skip_serializing_if = "Option::is_none",
2844        deserialize_with = "deserialize_effective_severity"
2845    )]
2846    pub effective_severity: Option<EffectiveSeverity>,
2847}
2848
2849impl DynamicSegmentNameConflictFinding {
2850    /// Build the wrapper from a raw [`DynamicSegmentNameConflict`]. Manual
2851    /// guidance primary action; file-level suppress escape hatch only.
2852    #[must_use]
2853    pub fn with_actions(conflict: DynamicSegmentNameConflict) -> Self {
2854        let actions = vec![
2855            IssueAction::Fix(FixAction {
2856                kind: FixActionType::ResolveDynamicSegmentNameConflict,
2857                auto_fixable: false,
2858                description: "Sibling dynamic segments at the same position use different param \
2859                              names. Rename them to one consistent slug name (e.g. pick `[id]` \
2860                              or `[slug]` for both)."
2861                    .to_string(),
2862                note: Some(
2863                    "Next.js throws \"You cannot use different slug names for the same dynamic \
2864                     path\" at dev / runtime when the position is hit; `next build` does not \
2865                     catch it. See the sibling `conflicting_segments` array."
2866                        .to_string(),
2867                ),
2868                available_in_catalogs: None,
2869                suggested_target: None,
2870            }),
2871            IssueAction::SuppressFile(SuppressFileAction {
2872                kind: SuppressFileKind::SuppressFile,
2873                auto_fixable: false,
2874                description: "Escape hatch only: a file-level suppress silences the finding but \
2875                              does NOT stop Next.js from throwing at dev / runtime. Prefer \
2876                              renaming the segments."
2877                    .to_string(),
2878                comment: "// fallow-ignore-file dynamic-segment-name-conflict".to_string(),
2879            }),
2880        ];
2881        Self {
2882            finding_id: None,
2883            conflict,
2884            actions,
2885            introduced: None,
2886            effective_severity: None,
2887        }
2888    }
2889}
2890
2891/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
2892/// `unused_enum_members` key.
2893#[derive(Debug, Clone, Serialize, Deserialize)]
2894#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2895pub struct UnusedEnumMemberFinding {
2896    /// The underlying dead-code entry.
2897    #[serde(flatten)]
2898    pub member: UnusedMember,
2899    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2900    /// `~<k>` suffix when several findings of one type share an identity.
2901    /// Line and column are not inputs, so the id survives line shifts,
2902    /// reformats and reorders. A rename of the file or the symbol gives a
2903    /// new id. Absent in output from older versions.
2904    #[serde(default, skip_serializing_if = "Option::is_none")]
2905    pub finding_id: Option<String>,
2906    /// Suggested next steps. Always emitted (possibly empty for
2907    /// forward-compat).
2908    pub actions: Vec<IssueAction>,
2909    /// Set by the audit pass when this finding is introduced relative to
2910    /// the merge-base.
2911    #[serde(default, skip_serializing_if = "Option::is_none")]
2912    pub introduced: Option<AuditIntroduced>,
2913    /// Gate severity of this finding after `rules` and `overrides[].rules`
2914    /// resolve for its path. CI formats read it for the annotation, SARIF
2915    /// and CodeClimate level. Absent in output from older versions. Not
2916    /// part of the finding identity, baseline keys or fingerprints.
2917    #[serde(
2918        default,
2919        skip_serializing_if = "Option::is_none",
2920        deserialize_with = "deserialize_effective_severity"
2921    )]
2922    pub effective_severity: Option<EffectiveSeverity>,
2923    /// Advisory caveats on the verdict behind this finding. A member's usage
2924    /// is collected by walking the member accesses of every module the run
2925    /// parsed, so a member whose only reference lives in a file the run never
2926    /// read reads as unused exactly like an export does. Sorted,
2927    /// deduplicated, and omitted from the wire when empty. Never gates the
2928    /// finding; it does withhold the `remove-enum-member` mutation.
2929    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2930    pub reachability_caveats: Vec<ReachabilityCaveat>,
2931}
2932
2933impl UnusedEnumMemberFinding {
2934    /// Build the wrapper from a raw [`UnusedMember`].
2935    #[must_use]
2936    pub fn with_actions(member: UnusedMember) -> Self {
2937        let actions = vec![
2938            IssueAction::Fix(FixAction {
2939                kind: FixActionType::RemoveEnumMember,
2940                auto_fixable: true,
2941                description: "Remove this enum member".to_string(),
2942                note: None,
2943                available_in_catalogs: None,
2944                suggested_target: None,
2945            }),
2946            IssueAction::SuppressLine(SuppressLineAction {
2947                kind: SuppressLineKind::SuppressLine,
2948                auto_fixable: false,
2949                description: "Suppress with an inline comment above the line".to_string(),
2950                comment: "// fallow-ignore-next-line unused-enum-member".to_string(),
2951                scope: None,
2952            }),
2953        ];
2954        Self {
2955            finding_id: None,
2956            member,
2957            actions,
2958            introduced: None,
2959            effective_severity: None,
2960            reachability_caveats: Vec::new(),
2961        }
2962    }
2963}
2964
2965/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
2966/// `unused_class_members` key. Same Rust struct as
2967/// [`UnusedEnumMemberFinding`]; the fix action and suppress comment carry
2968/// the class-member kebab-case identifier instead.
2969#[derive(Debug, Clone, Serialize, Deserialize)]
2970#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2971pub struct UnusedClassMemberFinding {
2972    /// The underlying dead-code entry.
2973    #[serde(flatten)]
2974    pub member: UnusedMember,
2975    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
2976    /// `~<k>` suffix when several findings of one type share an identity.
2977    /// Line and column are not inputs, so the id survives line shifts,
2978    /// reformats and reorders. A rename of the file or the symbol gives a
2979    /// new id. Absent in output from older versions.
2980    #[serde(default, skip_serializing_if = "Option::is_none")]
2981    pub finding_id: Option<String>,
2982    /// Suggested next steps. Always emitted (possibly empty for
2983    /// forward-compat).
2984    pub actions: Vec<IssueAction>,
2985    /// Type-aware evidence for this exact candidate when requested.
2986    #[serde(default, skip_serializing_if = "Option::is_none")]
2987    pub semantic: Option<SemanticCandidateDecision>,
2988    /// Internal marker for a framework member that the syntactic analysis
2989    /// suppresses, but the semantic pass may promote after proving complete
2990    /// closed-world absence. Never serialized as part of the public finding.
2991    #[serde(skip)]
2992    #[cfg_attr(feature = "schema", schemars(skip))]
2993    pub semantic_only_candidate: bool,
2994    /// Set by the audit pass when this finding is introduced relative to
2995    /// the merge-base.
2996    #[serde(default, skip_serializing_if = "Option::is_none")]
2997    pub introduced: Option<AuditIntroduced>,
2998    /// Gate severity of this finding after `rules` and `overrides[].rules`
2999    /// resolve for its path. CI formats read it for the annotation, SARIF
3000    /// and CodeClimate level. Absent in output from older versions. Not
3001    /// part of the finding identity, baseline keys or fingerprints.
3002    #[serde(
3003        default,
3004        skip_serializing_if = "Option::is_none",
3005        deserialize_with = "deserialize_effective_severity"
3006    )]
3007    pub effective_severity: Option<EffectiveSeverity>,
3008    /// Advisory caveats on the verdict behind this finding. A class member's
3009    /// usage is collected by the same reachability-free member-access walk an
3010    /// enum member's is, so it takes the enum-member rule unchanged: any module
3011    /// this run analyzed incompletely can hold the access that credits it.
3012    /// Sorted, deduplicated, and omitted from the wire when empty. Never gates
3013    /// the finding; it does withhold the `remove-class-member` mutation that
3014    /// the type-aware pass would otherwise open.
3015    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3016    pub reachability_caveats: Vec<ReachabilityCaveat>,
3017}
3018
3019impl UnusedClassMemberFinding {
3020    /// Build the wrapper from a raw [`UnusedMember`]. Class-member fixes
3021    /// are not auto-applied (members can be used via dependency injection
3022    /// or decorators), so `auto_fixable` is `false` and a context note is
3023    /// attached.
3024    #[must_use]
3025    pub fn with_actions(member: UnusedMember) -> Self {
3026        let actions = vec![
3027            IssueAction::Fix(FixAction {
3028                kind: FixActionType::RemoveClassMember,
3029                auto_fixable: false,
3030                description: "Remove this class member".to_string(),
3031                note: Some(
3032                    "Class member may be used via dependency injection or decorators".to_string(),
3033                ),
3034                available_in_catalogs: None,
3035                suggested_target: None,
3036            }),
3037            IssueAction::SuppressLine(SuppressLineAction {
3038                kind: SuppressLineKind::SuppressLine,
3039                auto_fixable: false,
3040                description: "Suppress with an inline comment above the line".to_string(),
3041                comment: "// fallow-ignore-next-line unused-class-member".to_string(),
3042                scope: None,
3043            }),
3044        ];
3045        Self {
3046            finding_id: None,
3047            member,
3048            actions,
3049            semantic: None,
3050            semantic_only_candidate: false,
3051            introduced: None,
3052            effective_severity: None,
3053            reachability_caveats: Vec::new(),
3054        }
3055    }
3056
3057    /// Mark this finding as latent until semantic analysis proves that the
3058    /// framework contract does not apply and no static references exist.
3059    #[must_use]
3060    pub const fn semantic_only_candidate(mut self) -> Self {
3061        self.semantic_only_candidate = true;
3062        self
3063    }
3064
3065    /// Attach the canonical semantic decision and expose the class-member fix
3066    /// only when the API policy granted closed-world eligibility AND this run
3067    /// holds the evidence for the mutation.
3068    ///
3069    /// This is the one code path that RAISES `auto_fixable` on a class member,
3070    /// and it runs in the API layer AFTER the analysis layer stamped the run's
3071    /// caveats, so it asks the gate for the same reason
3072    /// `set_export_semantic_action` does: a closed-world verdict computed
3073    /// over a program the run never fully read must not re-open a removal the
3074    /// incomplete run already withheld. The withheld note names the evidence
3075    /// gap rather than the semantic explanation, which stays readable on the
3076    /// finding's own `semantic` object.
3077    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
3078        let evidence_complete = self.reachability_caveats.is_empty();
3079        if let Some(IssueAction::Fix(action)) = self.actions.first_mut() {
3080            action.auto_fixable = decision.closed_world_eligible && evidence_complete;
3081            action.note = Some(if evidence_complete {
3082                decision.explanation.clone()
3083            } else {
3084                INCOMPLETE_EVIDENCE_NOTE.to_string()
3085            });
3086        }
3087        self.semantic = Some(decision);
3088    }
3089}
3090
3091/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
3092/// `unused_store_members` key (a Pinia `state` / `getters` / `actions` key, or
3093/// a setup-store returned key, declared but never accessed by any consumer
3094/// project-wide). Same Rust struct as [`UnusedClassMemberFinding`]. Emits only
3095/// a line-level suppress action: there is no safe auto-fix because a store
3096/// member can be accessed reflectively (a Pinia plugin, `store.$onAction`, or
3097/// dynamic dispatch) in ways syntactic analysis cannot see, so removal is a
3098/// behavioral change the user must own.
3099#[derive(Debug, Clone, Serialize, Deserialize)]
3100#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3101pub struct UnusedStoreMemberFinding {
3102    /// The underlying dead-code entry.
3103    #[serde(flatten)]
3104    pub member: UnusedMember,
3105    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3106    /// `~<k>` suffix when several findings of one type share an identity.
3107    /// Line and column are not inputs, so the id survives line shifts,
3108    /// reformats and reorders. A rename of the file or the symbol gives a
3109    /// new id. Absent in output from older versions.
3110    #[serde(default, skip_serializing_if = "Option::is_none")]
3111    pub finding_id: Option<String>,
3112    /// Suggested next steps. Always emitted (possibly empty for
3113    /// forward-compat).
3114    pub actions: Vec<IssueAction>,
3115    /// Set by the audit pass when this finding is introduced relative to
3116    /// the merge-base.
3117    #[serde(default, skip_serializing_if = "Option::is_none")]
3118    pub introduced: Option<AuditIntroduced>,
3119    /// Gate severity of this finding after `rules` and `overrides[].rules`
3120    /// resolve for its path. CI formats read it for the annotation, SARIF
3121    /// and CodeClimate level. Absent in output from older versions. Not
3122    /// part of the finding identity, baseline keys or fingerprints.
3123    #[serde(
3124        default,
3125        skip_serializing_if = "Option::is_none",
3126        deserialize_with = "deserialize_effective_severity"
3127    )]
3128    pub effective_severity: Option<EffectiveSeverity>,
3129    /// Advisory caveats on the verdict behind this finding. A store member's
3130    /// usage is collected by the same reachability-free member-access walk a
3131    /// class member's is, so it takes the member rule unchanged: any module
3132    /// this run analyzed incompletely can hold the access that credits it.
3133    /// Sorted, deduplicated, and omitted from the wire when empty. There is no
3134    /// mutation here to withhold, because a store member offers none on any
3135    /// surface; this is disclosure only, so a reader deciding by hand is told
3136    /// what the run did not see.
3137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3138    pub reachability_caveats: Vec<ReachabilityCaveat>,
3139}
3140
3141impl UnusedStoreMemberFinding {
3142    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
3143    /// suppress action (no auto-fix: store members can be accessed
3144    /// reflectively, so removal is never provably safe).
3145    #[must_use]
3146    pub fn with_actions(member: UnusedMember) -> Self {
3147        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
3148            kind: SuppressLineKind::SuppressLine,
3149            auto_fixable: false,
3150            description: "Suppress with an inline comment above the line".to_string(),
3151            comment: "// fallow-ignore-next-line unused-store-member".to_string(),
3152            scope: None,
3153        })];
3154        Self {
3155            finding_id: None,
3156            member,
3157            actions,
3158            introduced: None,
3159            effective_severity: None,
3160            reachability_caveats: Vec::new(),
3161        }
3162    }
3163}
3164
3165/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
3166/// `unused_namespace_members` key (an exported member of an exported
3167/// TypeScript namespace that no code reads). `member_name` is the dotted path
3168/// from the exported namespace, for example `Inner.x`. Emits only a
3169/// line-level suppress action: a member can be a multi-line function, class
3170/// or nested namespace, so there is no safe one-line auto-fix.
3171#[derive(Debug, Clone, Serialize, Deserialize)]
3172#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3173pub struct UnusedNamespaceMemberFinding {
3174    /// The underlying dead-code entry.
3175    #[serde(flatten)]
3176    pub member: UnusedMember,
3177    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3178    /// `~<k>` suffix when several findings of one type share an identity.
3179    /// Line and column are not inputs, so the id survives line shifts,
3180    /// reformats and reorders. A rename of the file or the symbol gives a
3181    /// new id. Absent in output from older versions.
3182    #[serde(default, skip_serializing_if = "Option::is_none")]
3183    pub finding_id: Option<String>,
3184    /// Suggested next steps. Always emitted (possibly empty for
3185    /// forward-compat).
3186    pub actions: Vec<IssueAction>,
3187    /// Set by the audit pass when this finding is introduced relative to
3188    /// the merge-base.
3189    #[serde(default, skip_serializing_if = "Option::is_none")]
3190    pub introduced: Option<AuditIntroduced>,
3191    /// Gate severity of this finding after `rules` and `overrides[].rules`
3192    /// resolve for its path. CI formats read it for the annotation, SARIF
3193    /// and CodeClimate level. Absent in output from older versions. Not
3194    /// part of the finding identity, baseline keys or fingerprints.
3195    #[serde(
3196        default,
3197        skip_serializing_if = "Option::is_none",
3198        deserialize_with = "deserialize_effective_severity"
3199    )]
3200    pub effective_severity: Option<EffectiveSeverity>,
3201    /// Advisory caveats on the verdict behind this finding. A namespace
3202    /// member takes the member rule unchanged: any module this run analyzed
3203    /// incompletely can hold the access that credits it. Sorted,
3204    /// deduplicated, and omitted from the wire when empty. This is disclosure
3205    /// only, because a namespace member offers no mutation.
3206    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3207    pub reachability_caveats: Vec<ReachabilityCaveat>,
3208}
3209
3210impl UnusedNamespaceMemberFinding {
3211    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
3212    /// suppress action.
3213    #[must_use]
3214    pub fn with_actions(member: UnusedMember) -> Self {
3215        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
3216            kind: SuppressLineKind::SuppressLine,
3217            auto_fixable: false,
3218            description: "Suppress with an inline comment above the line".to_string(),
3219            comment: "// fallow-ignore-next-line unused-namespace-member".to_string(),
3220            scope: None,
3221        })];
3222        Self {
3223            finding_id: None,
3224            member,
3225            actions,
3226            introduced: None,
3227            effective_severity: None,
3228            reachability_caveats: Vec::new(),
3229        }
3230    }
3231}
3232
3233/// Build the `IssueAction` vec for the three `unused_dependencies`,
3234/// `unused_dev_dependencies`, `unused_optional_dependencies` views over the
3235/// same bare [`UnusedDependency`] struct. Each wrapper differs only in the
3236/// `package_json_location` string (`"dependencies"` / `"devDependencies"` /
3237/// `"optionalDependencies"`) baked into the fix-action description and in
3238/// the `suppress_issue_kind` used by the inline-suppress comment. All three
3239/// share the cross-workspace swap (when `dep.used_in_workspaces` is
3240/// non-empty the primary fix flips from `remove-dependency` to
3241/// `move-dependency` because the dep is imported by ANOTHER workspace and
3242/// `fallow fix` cannot safely remove it).
3243fn build_unused_dependency_actions(
3244    dep: &UnusedDependency,
3245    package_json_location: &str,
3246    suppress_issue_kind: &str,
3247) -> Vec<IssueAction> {
3248    let mut actions = Vec::with_capacity(2);
3249    let cross_workspace = !dep.used_in_workspaces.is_empty();
3250    actions.push(if cross_workspace {
3251        IssueAction::Fix(FixAction {
3252            kind: FixActionType::MoveDependency,
3253            auto_fixable: false,
3254            description: "Move this dependency to the workspace package.json that imports it"
3255                .to_string(),
3256            note: Some(
3257                "fallow fix will not remove dependencies that are imported by another workspace"
3258                    .to_string(),
3259            ),
3260            available_in_catalogs: None,
3261            suggested_target: None,
3262        })
3263    } else {
3264        IssueAction::Fix(FixAction {
3265            kind: FixActionType::RemoveDependency,
3266            auto_fixable: true,
3267            description: format!("Remove from {package_json_location} in package.json"),
3268            note: None,
3269            available_in_catalogs: None,
3270            suggested_target: None,
3271        })
3272    });
3273    actions.push(build_ignore_dependencies_suppress_action(
3274        &dep.package_name,
3275        suppress_issue_kind,
3276    ));
3277    actions
3278}
3279
3280/// Build the standard `add-to-config` `ignoreDependencies` suppress action
3281/// for any finding whose primary key is a package name. Used by the four
3282/// dependency-family wrappers (unused / unlisted / type-only / test-only).
3283/// The `_suppress_issue_kind` argument is currently unused; the pre-2.76
3284/// `inject_actions` post-pass also did not embed the issue kind in this
3285/// shape (no inline `// fallow-ignore-next-line ...` comment because the
3286/// finding is anchored at a package.json line, not at a source-file line).
3287fn build_ignore_dependencies_suppress_action(
3288    package_name: &str,
3289    _suppress_issue_kind: &str,
3290) -> IssueAction {
3291    IssueAction::AddToConfig(AddToConfigAction {
3292        kind: AddToConfigKind::AddToConfig,
3293        auto_fixable: false,
3294        description: format!("Add \"{package_name}\" to ignoreDependencies in fallow config"),
3295        config_key: "ignoreDependencies".to_string(),
3296        value: AddToConfigValue::Scalar(package_name.to_string()),
3297        value_schema: Some(
3298            "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencies/items"
3299                .to_string(),
3300        ),
3301    })
3302}
3303
3304/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3305/// the `unused_dependencies` key (production deps). Flattens the bare
3306/// finding; the typed `actions` array carries either a `remove-dependency`
3307/// or `move-dependency` primary depending on
3308/// `inner.used_in_workspaces`.
3309#[derive(Debug, Clone, Serialize, Deserialize)]
3310#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3311pub struct UnusedDependencyFinding {
3312    /// The underlying dead-code entry.
3313    #[serde(flatten)]
3314    pub dep: UnusedDependency,
3315    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3316    /// `~<k>` suffix when several findings of one type share an identity.
3317    /// Line and column are not inputs, so the id survives line shifts,
3318    /// reformats and reorders. A rename of the file or the symbol gives a
3319    /// new id. Absent in output from older versions.
3320    #[serde(default, skip_serializing_if = "Option::is_none")]
3321    pub finding_id: Option<String>,
3322    /// Suggested next steps. Always emitted (possibly empty for
3323    /// forward-compat).
3324    pub actions: Vec<IssueAction>,
3325    /// Set by the audit pass when this finding is introduced relative to
3326    /// the merge-base.
3327    #[serde(default, skip_serializing_if = "Option::is_none")]
3328    pub introduced: Option<AuditIntroduced>,
3329    /// Gate severity of this finding after `rules` and `overrides[].rules`
3330    /// resolve for its path. CI formats read it for the annotation, SARIF
3331    /// and CodeClimate level. Absent in output from older versions. Not
3332    /// part of the finding identity, baseline keys or fingerprints.
3333    #[serde(
3334        default,
3335        skip_serializing_if = "Option::is_none",
3336        deserialize_with = "deserialize_effective_severity"
3337    )]
3338    pub effective_severity: Option<EffectiveSeverity>,
3339    /// Advisory caveats on the verdict behind this finding. A dependency is
3340    /// reported unused when NO module in the project imports its specifier,
3341    /// so a module that parsed with errors can hide the import that would
3342    /// have credited the package. Sorted, deduplicated, and omitted from the
3343    /// wire when empty. Never gates the finding, though `fallow fix`
3344    /// withholds the `remove-dependency` write while a caveat stands.
3345    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3346    pub reachability_caveats: Vec<ReachabilityCaveat>,
3347}
3348
3349impl UnusedDependencyFinding {
3350    /// Build the wrapper. Switches the primary fix from `remove-dependency`
3351    /// to `move-dependency` when the dep is imported by another workspace.
3352    #[must_use]
3353    pub fn with_actions(dep: UnusedDependency) -> Self {
3354        let actions = build_unused_dependency_actions(&dep, "dependencies", "unused-dependency");
3355        Self {
3356            finding_id: None,
3357            dep,
3358            actions,
3359            introduced: None,
3360            effective_severity: None,
3361            reachability_caveats: Vec::new(),
3362        }
3363    }
3364}
3365
3366/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3367/// the `unused_dev_dependencies` key. Same bare struct as
3368/// [`UnusedDependencyFinding`]; the fix description points at
3369/// `devDependencies` and the suppress comment uses
3370/// `unused-dev-dependency`.
3371#[derive(Debug, Clone, Serialize, Deserialize)]
3372#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3373pub struct UnusedDevDependencyFinding {
3374    /// The underlying dead-code entry.
3375    #[serde(flatten)]
3376    pub dep: UnusedDependency,
3377    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3378    /// `~<k>` suffix when several findings of one type share an identity.
3379    /// Line and column are not inputs, so the id survives line shifts,
3380    /// reformats and reorders. A rename of the file or the symbol gives a
3381    /// new id. Absent in output from older versions.
3382    #[serde(default, skip_serializing_if = "Option::is_none")]
3383    pub finding_id: Option<String>,
3384    /// Suggested next steps. Always emitted (possibly empty for
3385    /// forward-compat).
3386    pub actions: Vec<IssueAction>,
3387    /// Set by the audit pass when this finding is introduced relative to
3388    /// the merge-base.
3389    #[serde(default, skip_serializing_if = "Option::is_none")]
3390    pub introduced: Option<AuditIntroduced>,
3391    /// Gate severity of this finding after `rules` and `overrides[].rules`
3392    /// resolve for its path. CI formats read it for the annotation, SARIF
3393    /// and CodeClimate level. Absent in output from older versions. Not
3394    /// part of the finding identity, baseline keys or fingerprints.
3395    #[serde(
3396        default,
3397        skip_serializing_if = "Option::is_none",
3398        deserialize_with = "deserialize_effective_severity"
3399    )]
3400    pub effective_severity: Option<EffectiveSeverity>,
3401    /// Advisory caveats on the verdict behind this finding. A dependency is
3402    /// reported unused when NO module in the project imports its specifier,
3403    /// so a module that parsed with errors can hide the import that would
3404    /// have credited the package. Sorted, deduplicated, and omitted from the
3405    /// wire when empty. Never gates the finding, though `fallow fix`
3406    /// withholds the `remove-dependency` write while a caveat stands.
3407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3408    pub reachability_caveats: Vec<ReachabilityCaveat>,
3409}
3410
3411impl UnusedDevDependencyFinding {
3412    /// Build the wrapper.
3413    #[must_use]
3414    pub fn with_actions(dep: UnusedDependency) -> Self {
3415        let actions =
3416            build_unused_dependency_actions(&dep, "devDependencies", "unused-dev-dependency");
3417        Self {
3418            finding_id: None,
3419            dep,
3420            actions,
3421            introduced: None,
3422            effective_severity: None,
3423            reachability_caveats: Vec::new(),
3424        }
3425    }
3426}
3427
3428/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
3429/// the `unused_optional_dependencies` key. Same bare struct as
3430/// [`UnusedDependencyFinding`]; the fix description points at
3431/// `optionalDependencies`. Reuses the `unused-dependency` suppress
3432/// `IssueKind` because there is no dedicated variant for optional deps.
3433#[derive(Debug, Clone, Serialize, Deserialize)]
3434#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3435pub struct UnusedOptionalDependencyFinding {
3436    /// The underlying dead-code entry.
3437    #[serde(flatten)]
3438    pub dep: UnusedDependency,
3439    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3440    /// `~<k>` suffix when several findings of one type share an identity.
3441    /// Line and column are not inputs, so the id survives line shifts,
3442    /// reformats and reorders. A rename of the file or the symbol gives a
3443    /// new id. Absent in output from older versions.
3444    #[serde(default, skip_serializing_if = "Option::is_none")]
3445    pub finding_id: Option<String>,
3446    /// Suggested next steps. Always emitted (possibly empty for
3447    /// forward-compat).
3448    pub actions: Vec<IssueAction>,
3449    /// Set by the audit pass when this finding is introduced relative to
3450    /// the merge-base.
3451    #[serde(default, skip_serializing_if = "Option::is_none")]
3452    pub introduced: Option<AuditIntroduced>,
3453    /// Gate severity of this finding after `rules` and `overrides[].rules`
3454    /// resolve for its path. CI formats read it for the annotation, SARIF
3455    /// and CodeClimate level. Absent in output from older versions. Not
3456    /// part of the finding identity, baseline keys or fingerprints.
3457    #[serde(
3458        default,
3459        skip_serializing_if = "Option::is_none",
3460        deserialize_with = "deserialize_effective_severity"
3461    )]
3462    pub effective_severity: Option<EffectiveSeverity>,
3463    /// Advisory caveats on the verdict behind this finding. A dependency is
3464    /// reported unused when NO module in the project imports its specifier,
3465    /// so a module that parsed with errors can hide the import that would
3466    /// have credited the package. Sorted, deduplicated, and omitted from the
3467    /// wire when empty. Never gates the finding, though `fallow fix`
3468    /// withholds the `remove-dependency` write while a caveat stands.
3469    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3470    pub reachability_caveats: Vec<ReachabilityCaveat>,
3471}
3472
3473impl UnusedOptionalDependencyFinding {
3474    /// Build the wrapper.
3475    #[must_use]
3476    pub fn with_actions(dep: UnusedDependency) -> Self {
3477        let actions =
3478            build_unused_dependency_actions(&dep, "optionalDependencies", "unused-dependency");
3479        Self {
3480            finding_id: None,
3481            dep,
3482            actions,
3483            introduced: None,
3484            effective_severity: None,
3485            reachability_caveats: Vec::new(),
3486        }
3487    }
3488}
3489
3490/// Wire-shape envelope for an [`UnlistedDependency`] finding. Carries an
3491/// `install-dependency` primary (non-auto-fixable) plus the standard
3492/// `ignoreDependencies` config suppress.
3493#[derive(Debug, Clone, Serialize, Deserialize)]
3494#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3495pub struct UnlistedDependencyFinding {
3496    /// The underlying dead-code entry.
3497    #[serde(flatten)]
3498    pub dep: UnlistedDependency,
3499    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3500    /// `~<k>` suffix when several findings of one type share an identity.
3501    /// Line and column are not inputs, so the id survives line shifts,
3502    /// reformats and reorders. A rename of the file or the symbol gives a
3503    /// new id. Absent in output from older versions.
3504    #[serde(default, skip_serializing_if = "Option::is_none")]
3505    pub finding_id: Option<String>,
3506    /// Suggested next steps. Always emitted (possibly empty for
3507    /// forward-compat).
3508    pub actions: Vec<IssueAction>,
3509    /// Set by the audit pass when this finding is introduced relative to
3510    /// the merge-base.
3511    #[serde(default, skip_serializing_if = "Option::is_none")]
3512    pub introduced: Option<AuditIntroduced>,
3513    /// Gate severity of this finding after `rules` and `overrides[].rules`
3514    /// resolve for its path. CI formats read it for the annotation, SARIF
3515    /// and CodeClimate level. Absent in output from older versions. Not
3516    /// part of the finding identity, baseline keys or fingerprints.
3517    #[serde(
3518        default,
3519        skip_serializing_if = "Option::is_none",
3520        deserialize_with = "deserialize_effective_severity"
3521    )]
3522    pub effective_severity: Option<EffectiveSeverity>,
3523}
3524
3525impl UnlistedDependencyFinding {
3526    /// Build the wrapper.
3527    #[must_use]
3528    pub fn with_actions(dep: UnlistedDependency) -> Self {
3529        let actions = vec![
3530            IssueAction::Fix(FixAction {
3531                kind: FixActionType::InstallDependency,
3532                auto_fixable: false,
3533                description: "Add this package to dependencies in package.json".to_string(),
3534                note: Some(
3535                    "Verify this package should be a direct dependency before adding".to_string(),
3536                ),
3537                available_in_catalogs: None,
3538                suggested_target: None,
3539            }),
3540            build_ignore_dependencies_suppress_action(&dep.package_name, "unlisted-dependency"),
3541        ];
3542        Self {
3543            finding_id: None,
3544            dep,
3545            actions,
3546            introduced: None,
3547            effective_severity: None,
3548        }
3549    }
3550}
3551
3552/// Wire-shape envelope for an [`UnlistedBinary`] finding. Carries an
3553/// `install-dependency` primary (non-auto-fixable) plus an `ignoreBinaries`
3554/// config suppress.
3555#[derive(Debug, Clone, Serialize, Deserialize)]
3556#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3557pub struct UnlistedBinaryFinding {
3558    /// The underlying dead-code entry.
3559    #[serde(flatten)]
3560    pub binary: UnlistedBinary,
3561    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3562    /// `~<k>` suffix when several findings of one type share an identity.
3563    /// Line and column are not inputs, so the id survives line shifts,
3564    /// reformats and reorders. Absent in output from older versions.
3565    #[serde(default, skip_serializing_if = "Option::is_none")]
3566    pub finding_id: Option<String>,
3567    /// Suggested next steps. Always emitted (possibly empty for
3568    /// forward-compat).
3569    pub actions: Vec<IssueAction>,
3570    /// Set by the audit pass when this finding is introduced relative to
3571    /// the merge-base.
3572    #[serde(default, skip_serializing_if = "Option::is_none")]
3573    pub introduced: Option<AuditIntroduced>,
3574    /// Gate severity of this finding after `rules` and `overrides[].rules`
3575    /// resolve for its path. CI formats read it for the annotation, SARIF
3576    /// and CodeClimate level. Absent in output from older versions. Not
3577    /// part of the finding identity, baseline keys or fingerprints.
3578    #[serde(
3579        default,
3580        skip_serializing_if = "Option::is_none",
3581        deserialize_with = "deserialize_effective_severity"
3582    )]
3583    pub effective_severity: Option<EffectiveSeverity>,
3584}
3585
3586impl UnlistedBinaryFinding {
3587    /// Build the wrapper.
3588    #[must_use]
3589    pub fn with_actions(binary: UnlistedBinary) -> Self {
3590        let name = &binary.binary_name;
3591        let actions = vec![
3592            IssueAction::Fix(FixAction {
3593                kind: FixActionType::InstallDependency,
3594                auto_fixable: false,
3595                description: "Add the package that provides this binary to devDependencies"
3596                    .to_string(),
3597                note: Some(
3598                    "If the operating system or the CI image provides this binary, add it to ignoreBinaries instead"
3599                        .to_string(),
3600                ),
3601                available_in_catalogs: None,
3602                suggested_target: None,
3603            }),
3604            IssueAction::AddToConfig(AddToConfigAction {
3605                kind: AddToConfigKind::AddToConfig,
3606                auto_fixable: false,
3607                description: format!("Add \"{name}\" to ignoreBinaries in fallow config"),
3608                config_key: "ignoreBinaries".to_string(),
3609                value: AddToConfigValue::Scalar(name.clone()),
3610                value_schema: Some(
3611                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreBinaries/items"
3612                        .to_string(),
3613                ),
3614            }),
3615        ];
3616        Self {
3617            finding_id: None,
3618            binary,
3619            actions,
3620            introduced: None,
3621            effective_severity: None,
3622        }
3623    }
3624}
3625
3626/// Wire-shape envelope for a [`TypeOnlyDependency`] finding. Carries a
3627/// `move-to-dev` primary plus the standard `ignoreDependencies` config
3628/// suppress.
3629#[derive(Debug, Clone, Serialize, Deserialize)]
3630#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3631pub struct TypeOnlyDependencyFinding {
3632    /// The underlying dead-code entry.
3633    #[serde(flatten)]
3634    pub dep: TypeOnlyDependency,
3635    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3636    /// `~<k>` suffix when several findings of one type share an identity.
3637    /// Line and column are not inputs, so the id survives line shifts,
3638    /// reformats and reorders. A rename of the file or the symbol gives a
3639    /// new id. Absent in output from older versions.
3640    #[serde(default, skip_serializing_if = "Option::is_none")]
3641    pub finding_id: Option<String>,
3642    /// Suggested next steps. Always emitted (possibly empty for
3643    /// forward-compat).
3644    pub actions: Vec<IssueAction>,
3645    /// Set by the audit pass when this finding is introduced relative to
3646    /// the merge-base.
3647    #[serde(default, skip_serializing_if = "Option::is_none")]
3648    pub introduced: Option<AuditIntroduced>,
3649    /// Gate severity of this finding after `rules` and `overrides[].rules`
3650    /// resolve for its path. CI formats read it for the annotation, SARIF
3651    /// and CodeClimate level. Absent in output from older versions. Not
3652    /// part of the finding identity, baseline keys or fingerprints.
3653    #[serde(
3654        default,
3655        skip_serializing_if = "Option::is_none",
3656        deserialize_with = "deserialize_effective_severity"
3657    )]
3658    pub effective_severity: Option<EffectiveSeverity>,
3659}
3660
3661impl TypeOnlyDependencyFinding {
3662    /// Build the wrapper.
3663    #[must_use]
3664    pub fn with_actions(dep: TypeOnlyDependency) -> Self {
3665        let actions = vec![
3666            IssueAction::Fix(FixAction {
3667                kind: FixActionType::MoveToDev,
3668                auto_fixable: false,
3669                description: "Move to devDependencies (only type imports are used)".to_string(),
3670                note: Some(
3671                    "Type imports are erased at runtime so this dependency is not needed in production"
3672                        .to_string(),
3673                ),
3674                available_in_catalogs: None,
3675                suggested_target: None,
3676            }),
3677            build_ignore_dependencies_suppress_action(&dep.package_name, "type-only-dependency"),
3678        ];
3679        Self {
3680            finding_id: None,
3681            dep,
3682            actions,
3683            introduced: None,
3684            effective_severity: None,
3685        }
3686    }
3687}
3688
3689/// Wire-shape envelope for a [`TestOnlyDependency`] finding. Carries a
3690/// `move-to-dev` primary (different prose than [`TypeOnlyDependencyFinding`])
3691/// plus the standard `ignoreDependencies` config suppress.
3692#[derive(Debug, Clone, Serialize, Deserialize)]
3693#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3694pub struct TestOnlyDependencyFinding {
3695    /// The underlying dead-code entry.
3696    #[serde(flatten)]
3697    pub dep: TestOnlyDependency,
3698    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3699    /// `~<k>` suffix when several findings of one type share an identity.
3700    /// Line and column are not inputs, so the id survives line shifts,
3701    /// reformats and reorders. A rename of the file or the symbol gives a
3702    /// new id. Absent in output from older versions.
3703    #[serde(default, skip_serializing_if = "Option::is_none")]
3704    pub finding_id: Option<String>,
3705    /// Suggested next steps. Always emitted (possibly empty for
3706    /// forward-compat).
3707    pub actions: Vec<IssueAction>,
3708    /// Set by the audit pass when this finding is introduced relative to
3709    /// the merge-base.
3710    #[serde(default, skip_serializing_if = "Option::is_none")]
3711    pub introduced: Option<AuditIntroduced>,
3712    /// Gate severity of this finding after `rules` and `overrides[].rules`
3713    /// resolve for its path. CI formats read it for the annotation, SARIF
3714    /// and CodeClimate level. Absent in output from older versions. Not
3715    /// part of the finding identity, baseline keys or fingerprints.
3716    #[serde(
3717        default,
3718        skip_serializing_if = "Option::is_none",
3719        deserialize_with = "deserialize_effective_severity"
3720    )]
3721    pub effective_severity: Option<EffectiveSeverity>,
3722}
3723
3724impl TestOnlyDependencyFinding {
3725    /// Build the wrapper.
3726    #[must_use]
3727    pub fn with_actions(dep: TestOnlyDependency) -> Self {
3728        let actions = vec![
3729            IssueAction::Fix(FixAction {
3730                kind: FixActionType::MoveToDev,
3731                auto_fixable: false,
3732                description: "Move to devDependencies (only test files import this)".to_string(),
3733                note: Some(
3734                    "Only test files import this package so it does not need to be a production dependency"
3735                        .to_string(),
3736                ),
3737                available_in_catalogs: None,
3738                suggested_target: None,
3739            }),
3740            build_ignore_dependencies_suppress_action(&dep.package_name, "test-only-dependency"),
3741        ];
3742        Self {
3743            finding_id: None,
3744            dep,
3745            actions,
3746            introduced: None,
3747            effective_severity: None,
3748        }
3749    }
3750}
3751
3752/// Wire-shape envelope for a [`DevDependencyInProduction`] finding. Carries a
3753/// `move-to-prod` primary (the promote-side mirror of
3754/// [`TestOnlyDependencyFinding`]'s `move-to-dev`) plus the standard
3755/// `ignoreDependencies` config suppress.
3756#[derive(Debug, Clone, Serialize, Deserialize)]
3757#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3758pub struct DevDependencyInProductionFinding {
3759    /// The underlying dead-code entry.
3760    #[serde(flatten)]
3761    pub dep: DevDependencyInProduction,
3762    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3763    /// `~<k>` suffix when several findings of one type share an identity.
3764    /// Line and column are not inputs, so the id survives line shifts,
3765    /// reformats and reorders. A rename of the file or the symbol gives a
3766    /// new id. Absent in output from older versions.
3767    #[serde(default, skip_serializing_if = "Option::is_none")]
3768    pub finding_id: Option<String>,
3769    /// Suggested next steps. Always emitted (possibly empty for
3770    /// forward-compat).
3771    pub actions: Vec<IssueAction>,
3772    /// Set by the audit pass when this finding is introduced relative to
3773    /// the merge-base.
3774    #[serde(default, skip_serializing_if = "Option::is_none")]
3775    pub introduced: Option<AuditIntroduced>,
3776    /// Gate severity of this finding after `rules` and `overrides[].rules`
3777    /// resolve for its path. CI formats read it for the annotation, SARIF
3778    /// and CodeClimate level. Absent in output from older versions. Not
3779    /// part of the finding identity, baseline keys or fingerprints.
3780    #[serde(
3781        default,
3782        skip_serializing_if = "Option::is_none",
3783        deserialize_with = "deserialize_effective_severity"
3784    )]
3785    pub effective_severity: Option<EffectiveSeverity>,
3786}
3787
3788impl DevDependencyInProductionFinding {
3789    /// Build the wrapper.
3790    #[must_use]
3791    pub fn with_actions(dep: DevDependencyInProduction) -> Self {
3792        let actions = vec![
3793            IssueAction::Fix(FixAction {
3794                kind: FixActionType::MoveToProd,
3795                auto_fixable: false,
3796                description:
3797                    "Move to dependencies if the deployment installs them (production code imports this)"
3798                        .to_string(),
3799                note: Some(
3800                    "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"
3801                        .to_string(),
3802                ),
3803                available_in_catalogs: None,
3804                suggested_target: None,
3805            }),
3806            build_ignore_dependencies_suppress_action(
3807                &dep.package_name,
3808                "dev-dependency-in-production",
3809            ),
3810        ];
3811        Self {
3812            finding_id: None,
3813            dep,
3814            actions,
3815            introduced: None,
3816            effective_severity: None,
3817        }
3818    }
3819}
3820
3821// ── Catalog / dep-override family ───────────────────────────────
3822//
3823// These six wrappers replace the legacy `inject_actions` post-pass in
3824// `crates/cli/src/report/json.rs` for the catalog and dependency-override
3825// findings. Each `with_actions(...)` builds the typed `actions` array
3826// directly from the inner struct (and any per-call context such as
3827// `config_fixable`), so the wire shape is identical to the pre-2.76
3828// post-pass output but the Rust compiler now owns the action contract.
3829
3830/// Wire-shape envelope for a [`DuplicateExport`] finding. Carries up to
3831/// three actions in position-locked order: an `add-to-config` `ignoreExports`
3832/// snippet (only when `locations[]` carries at least one path) followed by
3833/// the `remove-duplicate` fix and the multi-location suppress.
3834///
3835/// The `add-to-config` action sits at position 0 because the documented
3836/// primary slot points at the safe, non-destructive path: the shadcn /
3837/// Radix / bits-ui namespace-barrel case where every `index.*` reexports
3838/// the directory's neighbours. The `remove-duplicate` fix stays as the
3839/// secondary so consumers that pattern-match on `actions[0].type` for
3840/// "primary fix" never propose deletion of an intentional barrel surface.
3841#[derive(Debug, Clone, Serialize, Deserialize)]
3842#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3843pub struct DuplicateExportFinding {
3844    /// The underlying finding.
3845    #[serde(flatten)]
3846    pub export: DuplicateExport,
3847    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3848    /// `~<k>` suffix when several findings of one type share an identity.
3849    /// Line and column are not inputs, so the id survives line shifts,
3850    /// reformats and reorders. A rename of the file or the symbol gives a
3851    /// new id. Absent in output from older versions.
3852    #[serde(default, skip_serializing_if = "Option::is_none")]
3853    pub finding_id: Option<String>,
3854    /// Suggested next steps. Always emitted (possibly empty for
3855    /// forward-compat).
3856    pub actions: Vec<IssueAction>,
3857    /// Set by the audit pass when this finding is introduced relative to
3858    /// the merge-base.
3859    #[serde(default, skip_serializing_if = "Option::is_none")]
3860    pub introduced: Option<AuditIntroduced>,
3861    /// Gate severity of this finding after `rules` and `overrides[].rules`
3862    /// resolve for its path. CI formats read it for the annotation, SARIF
3863    /// and CodeClimate level. Absent in output from older versions. Not
3864    /// part of the finding identity, baseline keys or fingerprints.
3865    #[serde(
3866        default,
3867        skip_serializing_if = "Option::is_none",
3868        deserialize_with = "deserialize_effective_severity"
3869    )]
3870    pub effective_severity: Option<EffectiveSeverity>,
3871}
3872
3873impl DuplicateExportFinding {
3874    /// Build the wrapper with the `add-to-config` action's `auto_fixable`
3875    /// defaulting to `false`. The CLI's `build_json_with_config_fixable`
3876    /// path layers the actual `config_fixable` signal via
3877    /// [`Self::set_config_fixable`] right before serialization (the
3878    /// fix-applier readiness check lives in `fallow-cli::fix` and is not
3879    /// reachable from the analyzer layer where wrappers are first built).
3880    /// Embedders that build `AnalysisResults` directly and never route
3881    /// through the CLI's JSON path keep the conservative default.
3882    #[must_use]
3883    pub fn with_actions(export: DuplicateExport) -> Self {
3884        let mut actions: Vec<IssueAction> = Vec::with_capacity(3);
3885
3886        if let Some(rules) = build_duplicate_exports_ignore_rules(&export) {
3887            actions.push(IssueAction::AddToConfig(AddToConfigAction {
3888                kind: AddToConfigKind::AddToConfig,
3889                auto_fixable: false,
3890                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(),
3891                config_key: "ignoreExports".to_string(),
3892                value: AddToConfigValue::ExportsRules(rules),
3893                value_schema: Some(IGNORE_EXPORTS_VALUE_SCHEMA.to_string()),
3894            }));
3895        }
3896
3897        actions.push(IssueAction::Fix(FixAction {
3898            kind: FixActionType::RemoveDuplicate,
3899            auto_fixable: false,
3900            description: "Keep one canonical export location and remove the others".to_string(),
3901            note: Some(NAMESPACE_BARREL_HINT.to_string()),
3902            available_in_catalogs: None,
3903            suggested_target: None,
3904        }));
3905
3906        actions.push(IssueAction::SuppressLine(SuppressLineAction {
3907            kind: SuppressLineKind::SuppressLine,
3908            auto_fixable: false,
3909            description: "Suppress with an inline comment above the line".to_string(),
3910            comment: "// fallow-ignore-next-line duplicate-export".to_string(),
3911            scope: Some(SuppressLineScope::PerLocation),
3912        }));
3913
3914        Self {
3915            finding_id: None,
3916            export,
3917            actions,
3918            introduced: None,
3919            effective_severity: None,
3920        }
3921    }
3922
3923    /// Update the position-0 `add-to-config` action's `auto_fixable` flag.
3924    /// Idempotent and a no-op when position 0 is not an `add-to-config`
3925    /// action (happens when the finding has no locations). Called by the
3926    /// CLI's JSON serializer with the result of
3927    /// `crate::fix::is_config_fixable` before emitting bytes.
3928    pub fn set_config_fixable(&mut self, fixable: bool) {
3929        if let Some(IssueAction::AddToConfig(action)) = self.actions.first_mut() {
3930            action.auto_fixable = fixable;
3931        }
3932    }
3933}
3934
3935/// Build a paste-ready `ignoreExports` config value from a duplicate-export
3936/// finding's locations. Returns one `{ file, exports: ["*"] }` entry per
3937/// distinct file in insertion order. `None` when no locations carry a path.
3938fn build_duplicate_exports_ignore_rules(
3939    export: &DuplicateExport,
3940) -> Option<Vec<IgnoreExportsRule>> {
3941    let mut entries: Vec<IgnoreExportsRule> = Vec::with_capacity(export.locations.len());
3942    for loc in &export.locations {
3943        // Normalize separators to forward slashes so pasting the action value
3944        // into `.fallowrc.json` produces a portable rule. On Windows
3945        // `to_string_lossy` preserves backslashes, which the old
3946        // `inject_actions` post-pass implicitly normalized because it read
3947        // the path AFTER `strip_root_prefix` had already run through
3948        // `normalize_uri`; the typed wrapper builds the value before
3949        // serialization, so the normalization has to be explicit here.
3950        let path = loc.path.to_string_lossy().replace('\\', "/");
3951        if path.is_empty() {
3952            continue;
3953        }
3954        if entries.iter().any(|existing| existing.file == path) {
3955            continue;
3956        }
3957        entries.push(IgnoreExportsRule {
3958            file: path,
3959            exports: vec!["*".to_string()],
3960        });
3961    }
3962    if entries.is_empty() {
3963        None
3964    } else {
3965        Some(entries)
3966    }
3967}
3968
3969/// Wire-shape envelope for an [`UnusedCatalogEntry`] finding. Per-instance
3970/// `auto_fixable` flips to `false` when `hardcoded_consumers` is non-empty or
3971/// the source is not `pnpm-workspace.yaml`.
3972#[derive(Debug, Clone, Serialize, Deserialize)]
3973#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3974pub struct UnusedCatalogEntryFinding {
3975    /// The underlying finding.
3976    #[serde(flatten)]
3977    pub entry: UnusedCatalogEntry,
3978    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3979    /// `~<k>` suffix when several findings of one type share an identity.
3980    /// Line and column are not inputs, so the id survives line shifts,
3981    /// reformats and reorders. A rename of the file or the symbol gives a
3982    /// new id. Absent in output from older versions.
3983    #[serde(default, skip_serializing_if = "Option::is_none")]
3984    pub finding_id: Option<String>,
3985    /// Suggested next steps. Always emitted.
3986    pub actions: Vec<IssueAction>,
3987    /// Set by the audit pass when this finding is introduced relative to
3988    /// the merge-base.
3989    #[serde(default, skip_serializing_if = "Option::is_none")]
3990    pub introduced: Option<AuditIntroduced>,
3991    /// Gate severity of this finding after `rules` and `overrides[].rules`
3992    /// resolve for its path. CI formats read it for the annotation, SARIF
3993    /// and CodeClimate level. Absent in output from older versions. Not
3994    /// part of the finding identity, baseline keys or fingerprints.
3995    #[serde(
3996        default,
3997        skip_serializing_if = "Option::is_none",
3998        deserialize_with = "deserialize_effective_severity"
3999    )]
4000    pub effective_severity: Option<EffectiveSeverity>,
4001}
4002
4003impl UnusedCatalogEntryFinding {
4004    /// Build the wrapper. Per-instance `auto_fixable` is `true` only when
4005    /// `hardcoded_consumers` is empty and the source is `pnpm-workspace.yaml`;
4006    /// otherwise `fallow fix` skips the entry to avoid breaking installs or
4007    /// applying YAML edits to Bun `package.json` catalogs.
4008    #[must_use]
4009    pub fn with_actions(entry: UnusedCatalogEntry) -> Self {
4010        let is_pnpm_source = is_pnpm_catalog_source(&entry.path);
4011        let auto_fixable = entry.hardcoded_consumers.is_empty() && is_pnpm_source;
4012        let note = if is_pnpm_source {
4013            Some(
4014                "If any consumer declares the same package with a hardcoded version, switch the consumer to `catalog:` before removing"
4015                    .to_string(),
4016            )
4017        } else {
4018            Some(
4019                "fallow fix only edits pnpm-workspace.yaml catalog entries. Edit Bun package.json catalogs manually."
4020                    .to_string(),
4021            )
4022        };
4023        let mut actions = vec![IssueAction::Fix(FixAction {
4024            kind: FixActionType::RemoveCatalogEntry,
4025            auto_fixable,
4026            description: if is_pnpm_source {
4027                "Remove the entry from pnpm-workspace.yaml".to_string()
4028            } else {
4029                "Remove the entry from the catalog source file manually".to_string()
4030            },
4031            note,
4032            available_in_catalogs: None,
4033            suggested_target: None,
4034        })];
4035        if is_pnpm_source {
4036            actions.push(IssueAction::SuppressLine(SuppressLineAction {
4037                kind: SuppressLineKind::SuppressLine,
4038                auto_fixable: false,
4039                description: "Suppress with a YAML comment above the line".to_string(),
4040                comment: "# fallow-ignore-next-line unused-catalog-entry".to_string(),
4041                scope: None,
4042            }));
4043        }
4044        Self {
4045            finding_id: None,
4046            entry,
4047            actions,
4048            introduced: None,
4049            effective_severity: None,
4050        }
4051    }
4052}
4053
4054/// Wire-shape envelope for an [`EmptyCatalogGroup`] finding. Carries a
4055/// `remove-empty-catalog-group` primary. YAML-sourced findings also include a
4056/// YAML-comment suppress action.
4057#[derive(Debug, Clone, Serialize, Deserialize)]
4058#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4059pub struct EmptyCatalogGroupFinding {
4060    /// The underlying finding.
4061    #[serde(flatten)]
4062    pub group: EmptyCatalogGroup,
4063    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4064    /// `~<k>` suffix when several findings of one type share an identity.
4065    /// Line and column are not inputs, so the id survives line shifts,
4066    /// reformats and reorders. A rename of the file or the symbol gives a
4067    /// new id. Absent in output from older versions.
4068    #[serde(default, skip_serializing_if = "Option::is_none")]
4069    pub finding_id: Option<String>,
4070    /// Suggested next steps. Always emitted.
4071    pub actions: Vec<IssueAction>,
4072    /// Set by the audit pass when this finding is introduced relative to
4073    /// the merge-base.
4074    #[serde(default, skip_serializing_if = "Option::is_none")]
4075    pub introduced: Option<AuditIntroduced>,
4076    /// Gate severity of this finding after `rules` and `overrides[].rules`
4077    /// resolve for its path. CI formats read it for the annotation, SARIF
4078    /// and CodeClimate level. Absent in output from older versions. Not
4079    /// part of the finding identity, baseline keys or fingerprints.
4080    #[serde(
4081        default,
4082        skip_serializing_if = "Option::is_none",
4083        deserialize_with = "deserialize_effective_severity"
4084    )]
4085    pub effective_severity: Option<EffectiveSeverity>,
4086}
4087
4088impl EmptyCatalogGroupFinding {
4089    /// Build the wrapper.
4090    #[must_use]
4091    pub fn with_actions(group: EmptyCatalogGroup) -> Self {
4092        let auto_fixable = is_pnpm_catalog_source(&group.path);
4093        let mut actions = vec![IssueAction::Fix(FixAction {
4094            kind: FixActionType::RemoveEmptyCatalogGroup,
4095            auto_fixable,
4096            description: if auto_fixable {
4097                "Remove the empty named catalog group from pnpm-workspace.yaml".to_string()
4098            } else {
4099                "Remove the empty named catalog group from the catalog source file manually"
4100                    .to_string()
4101            },
4102            note: Some(if auto_fixable {
4103                "Only named groups under `catalogs:` are flagged; the top-level `catalog:` hook is intentionally ignored"
4104                    .to_string()
4105            } else {
4106                "fallow fix only edits pnpm-workspace.yaml catalog groups. Edit Bun package.json catalogs manually."
4107                    .to_string()
4108            }),
4109            available_in_catalogs: None,
4110            suggested_target: None,
4111        })];
4112        if auto_fixable {
4113            actions.push(IssueAction::SuppressLine(SuppressLineAction {
4114                kind: SuppressLineKind::SuppressLine,
4115                auto_fixable: false,
4116                description: "Suppress with a YAML comment above the line".to_string(),
4117                comment: "# fallow-ignore-next-line empty-catalog-group".to_string(),
4118                scope: None,
4119            }));
4120        }
4121        Self {
4122            finding_id: None,
4123            group,
4124            actions,
4125            introduced: None,
4126            effective_severity: None,
4127        }
4128    }
4129}
4130
4131fn is_pnpm_catalog_source(path: &Path) -> bool {
4132    path == Path::new(PNPM_WORKSPACE_FILE)
4133}
4134
4135/// Wire-shape envelope for an [`UnresolvedCatalogReference`] finding. The
4136/// primary action at position 0 discriminates on `available_in_catalogs`:
4137/// `add-catalog-entry` when the array is empty (no other catalog declares
4138/// the package), or `update-catalog-reference` when at least one
4139/// alternative exists. When exactly one alternative exists, the action
4140/// also carries `suggested_target` so deterministic agents can land the
4141/// edit without picking from a list.
4142#[derive(Debug, Clone, Serialize, Deserialize)]
4143#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4144pub struct UnresolvedCatalogReferenceFinding {
4145    /// The underlying finding.
4146    #[serde(flatten)]
4147    pub reference: UnresolvedCatalogReference,
4148    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4149    /// `~<k>` suffix when several findings of one type share an identity.
4150    /// Line and column are not inputs, so the id survives line shifts,
4151    /// reformats and reorders. A rename of the file or the symbol gives a
4152    /// new id. Absent in output from older versions.
4153    #[serde(default, skip_serializing_if = "Option::is_none")]
4154    pub finding_id: Option<String>,
4155    /// Suggested next steps. Always emitted; position 0 is the discriminated
4156    /// primary (see struct docs).
4157    pub actions: Vec<IssueAction>,
4158    /// Set by the audit pass when this finding is introduced relative to
4159    /// the merge-base.
4160    #[serde(default, skip_serializing_if = "Option::is_none")]
4161    pub introduced: Option<AuditIntroduced>,
4162    /// Gate severity of this finding after `rules` and `overrides[].rules`
4163    /// resolve for its path. CI formats read it for the annotation, SARIF
4164    /// and CodeClimate level. Absent in output from older versions. Not
4165    /// part of the finding identity, baseline keys or fingerprints.
4166    #[serde(
4167        default,
4168        skip_serializing_if = "Option::is_none",
4169        deserialize_with = "deserialize_effective_severity"
4170    )]
4171    pub effective_severity: Option<EffectiveSeverity>,
4172}
4173
4174impl UnresolvedCatalogReferenceFinding {
4175    /// Build the wrapper. The discriminator at position 0 is the
4176    /// `add-catalog-entry` vs `update-catalog-reference` pick documented on
4177    /// the struct.
4178    #[must_use]
4179    pub fn with_actions(reference: UnresolvedCatalogReference) -> Self {
4180        // Normalize separators to forward slashes so the
4181        // `ignoreCatalogReferences.consumer` action value is portable when
4182        // pasted into a Windows-authored config. See
4183        // `build_duplicate_exports_ignore_rules` for the same pattern.
4184        let consumer_path = reference.path.to_string_lossy().replace('\\', "/");
4185        let primary = catalog_reference_primary_action(&reference);
4186        let fallback = remove_catalog_reference_action();
4187        let suppress = suppress_catalog_reference_action(&reference, consumer_path);
4188
4189        Self {
4190            finding_id: None,
4191            reference,
4192            actions: vec![primary, fallback, suppress],
4193            introduced: None,
4194            effective_severity: None,
4195        }
4196    }
4197}
4198
4199fn catalog_reference_primary_action(reference: &UnresolvedCatalogReference) -> IssueAction {
4200    if reference.available_in_catalogs.is_empty() {
4201        return IssueAction::Fix(FixAction {
4202            kind: FixActionType::AddCatalogEntry,
4203            auto_fixable: false,
4204            description: format!(
4205                "Add `{}` to the `{}` catalog in pnpm-workspace.yaml",
4206                reference.entry_name, reference.catalog_name
4207            ),
4208            note: Some(
4209                "Pin a version that satisfies the consumer's import; no other catalog declares this package today"
4210                    .to_string(),
4211            ),
4212            available_in_catalogs: None,
4213            suggested_target: None,
4214        });
4215    }
4216
4217    let available = reference.available_in_catalogs.clone();
4218    let suggested_target = (available.len() == 1).then(|| available[0].clone());
4219    IssueAction::Fix(FixAction {
4220        kind: FixActionType::UpdateCatalogReference,
4221        auto_fixable: false,
4222        description: format!(
4223            "Switch the reference from `catalog:{}` to a catalog that declares `{}`",
4224            reference.catalog_name, reference.entry_name
4225        ),
4226        note: None,
4227        available_in_catalogs: Some(available),
4228        suggested_target,
4229    })
4230}
4231
4232fn remove_catalog_reference_action() -> IssueAction {
4233    IssueAction::Fix(FixAction {
4234        kind: FixActionType::RemoveCatalogReference,
4235        auto_fixable: false,
4236        description: "Remove the catalog reference and pin a hardcoded version in its place"
4237            .to_string(),
4238        note: Some(
4239            "Use only when neither another catalog declares the package nor the named catalog should grow to include it"
4240                .to_string(),
4241        ),
4242        available_in_catalogs: None,
4243        suggested_target: None,
4244    })
4245}
4246
4247fn suppress_catalog_reference_action(
4248    reference: &UnresolvedCatalogReference,
4249    consumer_path: String,
4250) -> IssueAction {
4251    let mut suppress_value = serde_json::Map::new();
4252    suppress_value.insert(
4253        "package".to_string(),
4254        serde_json::Value::String(reference.entry_name.clone()),
4255    );
4256    suppress_value.insert(
4257        "catalog".to_string(),
4258        serde_json::Value::String(reference.catalog_name.clone()),
4259    );
4260    suppress_value.insert(
4261        "consumer".to_string(),
4262        serde_json::Value::String(consumer_path),
4263    );
4264    IssueAction::AddToConfig(AddToConfigAction {
4265        kind: AddToConfigKind::AddToConfig,
4266        auto_fixable: false,
4267        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(),
4268        config_key: "ignoreCatalogReferences".to_string(),
4269        value: AddToConfigValue::RuleObject(suppress_value),
4270        value_schema: Some(IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA.to_string()),
4271    })
4272}
4273
4274/// Wire-shape envelope for an [`UnusedDependencyOverride`] finding. Carries
4275/// a `remove-dependency-override` primary plus an `add-to-config`
4276/// `ignoreDependencyOverrides` suppress scoped to the target package and
4277/// declaration source.
4278#[derive(Debug, Clone, Serialize, Deserialize)]
4279#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4280pub struct UnusedDependencyOverrideFinding {
4281    /// The underlying finding.
4282    #[serde(flatten)]
4283    pub entry: UnusedDependencyOverride,
4284    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4285    /// `~<k>` suffix when several findings of one type share an identity.
4286    /// Line and column are not inputs, so the id survives line shifts,
4287    /// reformats and reorders. A rename of the file or the symbol gives a
4288    /// new id. Absent in output from older versions.
4289    #[serde(default, skip_serializing_if = "Option::is_none")]
4290    pub finding_id: Option<String>,
4291    /// Suggested next steps. Always emitted.
4292    pub actions: Vec<IssueAction>,
4293    /// Set by the audit pass when this finding is introduced relative to
4294    /// the merge-base.
4295    #[serde(default, skip_serializing_if = "Option::is_none")]
4296    pub introduced: Option<AuditIntroduced>,
4297    /// Gate severity of this finding after `rules` and `overrides[].rules`
4298    /// resolve for its path. CI formats read it for the annotation, SARIF
4299    /// and CodeClimate level. Absent in output from older versions. Not
4300    /// part of the finding identity, baseline keys or fingerprints.
4301    #[serde(
4302        default,
4303        skip_serializing_if = "Option::is_none",
4304        deserialize_with = "deserialize_effective_severity"
4305    )]
4306    pub effective_severity: Option<EffectiveSeverity>,
4307}
4308
4309impl UnusedDependencyOverrideFinding {
4310    /// Build the wrapper.
4311    #[must_use]
4312    pub fn with_actions(entry: UnusedDependencyOverride) -> Self {
4313        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
4314        actions.push(IssueAction::Fix(FixAction {
4315            kind: FixActionType::RemoveDependencyOverride,
4316            auto_fixable: false,
4317            description: "Remove the package-manager override entry from its declaration source"
4318                .to_string(),
4319            note: Some(
4320                "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)"
4321                    .to_string(),
4322            ),
4323            available_in_catalogs: None,
4324            suggested_target: None,
4325        }));
4326
4327        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
4328            Some(&entry.target_package),
4329            &entry.raw_key,
4330            entry.source,
4331        ) {
4332            actions.push(suppress);
4333        }
4334
4335        Self {
4336            finding_id: None,
4337            entry,
4338            actions,
4339            introduced: None,
4340            effective_severity: None,
4341        }
4342    }
4343}
4344
4345/// Wire-shape envelope for a [`MisconfiguredDependencyOverride`] finding.
4346/// Carries a `fix-dependency-override` primary plus the conditional
4347/// `add-to-config` `ignoreDependencyOverrides` suppress (skipped when both
4348/// `target_package` and `raw_key` are empty, since the rule matcher keys on
4349/// a non-empty package name).
4350#[derive(Debug, Clone, Serialize, Deserialize)]
4351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4352pub struct MisconfiguredDependencyOverrideFinding {
4353    /// The underlying finding.
4354    #[serde(flatten)]
4355    pub entry: MisconfiguredDependencyOverride,
4356    /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
4357    /// `~<k>` suffix when several findings of one type share an identity.
4358    /// Line and column are not inputs, so the id survives line shifts,
4359    /// reformats and reorders. A rename of the file or the symbol gives a
4360    /// new id. Absent in output from older versions.
4361    #[serde(default, skip_serializing_if = "Option::is_none")]
4362    pub finding_id: Option<String>,
4363    /// Suggested next steps. Always emitted.
4364    pub actions: Vec<IssueAction>,
4365    /// Set by the audit pass when this finding is introduced relative to
4366    /// the merge-base.
4367    #[serde(default, skip_serializing_if = "Option::is_none")]
4368    pub introduced: Option<AuditIntroduced>,
4369    /// Gate severity of this finding after `rules` and `overrides[].rules`
4370    /// resolve for its path. CI formats read it for the annotation, SARIF
4371    /// and CodeClimate level. Absent in output from older versions. Not
4372    /// part of the finding identity, baseline keys or fingerprints.
4373    #[serde(
4374        default,
4375        skip_serializing_if = "Option::is_none",
4376        deserialize_with = "deserialize_effective_severity"
4377    )]
4378    pub effective_severity: Option<EffectiveSeverity>,
4379}
4380
4381impl MisconfiguredDependencyOverrideFinding {
4382    /// Build the wrapper. The suppress action is omitted when neither
4383    /// `target_package` (set on `EmptyValue` cases) nor `raw_key` provides a
4384    /// non-empty package name; an `ignoreDependencyOverrides` entry with
4385    /// `package: ""` would be silently ignored by the config parser.
4386    #[must_use]
4387    pub fn with_actions(entry: MisconfiguredDependencyOverride) -> Self {
4388        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
4389        actions.push(IssueAction::Fix(FixAction {
4390            kind: FixActionType::FixDependencyOverride,
4391            auto_fixable: false,
4392            description:
4393                "Fix the package-manager override key or value: invalid entries are rejected or ignored"
4394                    .to_string(),
4395            note: Some(
4396                "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`."
4397                    .to_string(),
4398            ),
4399            available_in_catalogs: None,
4400            suggested_target: None,
4401        }));
4402
4403        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
4404            entry.target_package.as_deref(),
4405            &entry.raw_key,
4406            entry.source,
4407        ) {
4408            actions.push(suppress);
4409        }
4410
4411        Self {
4412            finding_id: None,
4413            entry,
4414            actions,
4415            introduced: None,
4416            effective_severity: None,
4417        }
4418    }
4419}
4420
4421/// Shared `add-to-config` `ignoreDependencyOverrides` builder for the two
4422/// override findings. Returns `None` when no non-empty package name is
4423/// available; the config parser silently drops entries with an empty
4424/// `package` field, so emitting one would be a no-op that misleads agents.
4425fn build_ignore_dependency_overrides_suppress(
4426    target_package: Option<&str>,
4427    raw_key: &str,
4428    source: DependencyOverrideSource,
4429) -> Option<IssueAction> {
4430    let package = target_package
4431        .filter(|s| !s.is_empty())
4432        .or_else(|| Some(raw_key).filter(|s| !s.is_empty()))?
4433        .to_string();
4434    let mut value = serde_json::Map::new();
4435    value.insert("package".to_string(), serde_json::Value::String(package));
4436    value.insert(
4437        "source".to_string(),
4438        serde_json::Value::String(source.as_label().to_string()),
4439    );
4440    Some(IssueAction::AddToConfig(AddToConfigAction {
4441        kind: AddToConfigKind::AddToConfig,
4442        auto_fixable: false,
4443        description: "Suppress this override finding via ignoreDependencyOverrides in fallow config (use for CVE-fix overrides that target a purely-transitive package).".to_string(),
4444        config_key: "ignoreDependencyOverrides".to_string(),
4445        value: AddToConfigValue::RuleObject(value),
4446        value_schema: Some(IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA.to_string()),
4447    }))
4448}
4449
4450// ── The mutation gate, registered once ──────────────────────────
4451//
4452// Every finding whose reachability verdict a lost import edge can distort.
4453// The analysis layer stamps caveats through `set_reachability_caveats`, which
4454// enforces the gate on the finding's actions in the same call; every mutation
4455// surface reads the answer back through `may_auto_apply_mutation`.
4456impl_caveated_finding!(
4457    UnusedFileFinding,
4458    UnusedExportFinding,
4459    UnusedTypeFinding,
4460    UnusedEnumMemberFinding,
4461    UnusedClassMemberFinding,
4462    UnusedNamespaceMemberFinding,
4463    UnusedStoreMemberFinding,
4464    UnusedDependencyFinding,
4465    UnusedDevDependencyFinding,
4466    UnusedOptionalDependencyFinding,
4467);
4468
4469/// Gate severity of one finding after rule resolution.
4470///
4471/// It is the severity that `rules` and the matching `overrides[].rules` give
4472/// the finding for its path. `--fail-on-issues` raises `warn` to `error`. A
4473/// finding whose rule is `off` is not reported, so there is no `off` value.
4474/// The type is separate from the health `severity` band, which ranks a
4475/// finding and does not gate it.
4476///
4477/// The `fallow dead-code` findings gate fails when a finding is `error`.
4478/// Other gates (regression, stale baseline) decide on their own inputs. Two
4479/// commands differ: the `fallow audit` `new-only` gate fails only on introduced
4480/// findings, so an inherited `error` finding does not fail the audit, and the
4481/// combined command (`fallow` without a subcommand) exits 0 for machine
4482/// formats unless `--fail-on-issues` or `--ci` is set.
4483///
4484/// Complexity findings carry the same type. The `complexity-cyclomatic`,
4485/// `complexity-cognitive` and `complexity-crap` rules set it, and the
4486/// `fallow health` findings gate and the audit verdict read it.
4487#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4488#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4489#[serde(rename_all = "lowercase")]
4490pub enum EffectiveSeverity {
4491    /// The finding fails the run.
4492    Error,
4493    /// The finding is reported and does not fail the run.
4494    Warn,
4495}
4496
4497/// Read an optional [`EffectiveSeverity`] and treat an unknown value as absent.
4498///
4499/// A saved report from a newer version can carry a value this version does not
4500/// know. The renderers then use the rule-based level, as for a report without
4501/// the field, and the envelope still loads.
4502///
4503/// # Errors
4504///
4505/// Returns an error only when the input is not valid JSON-like data.
4506pub fn deserialize_effective_severity<'de, D>(
4507    deserializer: D,
4508) -> Result<Option<EffectiveSeverity>, D::Error>
4509where
4510    D: serde::Deserializer<'de>,
4511{
4512    #[derive(Deserialize)]
4513    #[serde(untagged)]
4514    enum Tolerant {
4515        Known(EffectiveSeverity),
4516        Unknown(serde::de::IgnoredAny),
4517    }
4518    Ok(match Option::<Tolerant>::deserialize(deserializer)? {
4519        Some(Tolerant::Known(severity)) => Some(severity),
4520        Some(Tolerant::Unknown(_)) | None => None,
4521    })
4522}
4523
4524/// A finding wrapper that carries an [`EffectiveSeverity`].
4525///
4526/// The analysis layer writes the value one time after rule resolution. CI
4527/// renderers read it and fall back to the rule-level severity when it is
4528/// absent, for example in a saved report from an older version.
4529pub trait GatedFinding {
4530    /// The gate severity, or `None` when no value was written.
4531    fn effective_severity(&self) -> Option<EffectiveSeverity>;
4532
4533    /// Write the gate severity.
4534    fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>);
4535}
4536
4537/// Implement [`GatedFinding`] for wrappers with an `effective_severity` field.
4538macro_rules! impl_gated_finding {
4539    ($($finding:ty),+ $(,)?) => {
4540        $(
4541            impl GatedFinding for $finding {
4542                fn effective_severity(&self) -> Option<EffectiveSeverity> {
4543                    self.effective_severity
4544                }
4545
4546                fn set_effective_severity(&mut self, severity: Option<EffectiveSeverity>) {
4547                    self.effective_severity = severity;
4548                }
4549            }
4550        )+
4551    };
4552}
4553
4554impl_gated_finding!(
4555    UnusedFileFinding,
4556    PrivateTypeLeakFinding,
4557    DeprecatedExportInUseFinding,
4558    UnresolvedImportFinding,
4559    CircularDependencyFinding,
4560    ReExportCycleFinding,
4561    PackageCycleFinding,
4562    BoundaryViolationFinding,
4563    BoundaryCoverageViolationFinding,
4564    BoundaryCallViolationFinding,
4565    UnusedExportFinding,
4566    UnusedTypeFinding,
4567    InvalidClientExportFinding,
4568    MixedClientServerBarrelFinding,
4569    MisplacedDirectiveFinding,
4570    UnprovidedInjectFinding,
4571    UnusedServerActionFinding,
4572    UnusedLoadDataKeyFinding,
4573    UnrenderedComponentFinding,
4574    UnusedComponentPropFinding,
4575    AbsentComponentPropFinding,
4576    UnusedComponentEmitFinding,
4577    UnusedSvelteEventFinding,
4578    UnusedEffectLayerFinding,
4579    UnusedTaggedErrorFinding,
4580    UnproducedCatchTagFinding,
4581    UnusedComponentInputFinding,
4582    UnusedComponentOutputFinding,
4583    RouteCollisionFinding,
4584    DynamicSegmentNameConflictFinding,
4585    UnusedEnumMemberFinding,
4586    UnusedClassMemberFinding,
4587    UnusedNamespaceMemberFinding,
4588    UnusedStoreMemberFinding,
4589    UnusedDependencyFinding,
4590    UnusedDevDependencyFinding,
4591    UnusedOptionalDependencyFinding,
4592    UnlistedDependencyFinding,
4593    UnlistedBinaryFinding,
4594    TypeOnlyDependencyFinding,
4595    TestOnlyDependencyFinding,
4596    DevDependencyInProductionFinding,
4597    DuplicateExportFinding,
4598    DuplicateExportAliasFinding,
4599    UnusedCatalogEntryFinding,
4600    EmptyCatalogGroupFinding,
4601    UnresolvedCatalogReferenceFinding,
4602    UnusedDependencyOverrideFinding,
4603    MisconfiguredDependencyOverrideFinding,
4604    PropDrillingChainFinding,
4605    ThinWrapperFinding,
4606    DuplicatePropShapeFinding,
4607    crate::results::StaleSuppression,
4608);
4609
4610// ── Position-0 invariant golden tests ───────────────────────────
4611//
4612// These tests document the load-bearing position-0 semantics that flow
4613// downstream into the GitHub Action / GitLab CI jq scripts, the MCP server
4614// `actions[0].type` pattern-match, and the VS Code LSP code-action
4615// rendering. Snapshot tests assert structural equality; these named tests
4616// document WHY position 0 has a specific value, so a future refactor that
4617// re-orders actions tells you what broke instead of just "the snapshot
4618// changed".
4619#[cfg(test)]
4620#[path = "output_dead_code_caveat_tokens.rs"]
4621mod caveat_tokens;
4622
4623/// The gate, pinned as one property across every finding type rather than as
4624/// one test per mutation surface.
4625///
4626/// Three separate reviewers found three separate mutation paths that had never
4627/// learned about the caveat, because each earlier round fixed the door it
4628/// found. These tests assert the invariant itself: for every dead-code finding
4629/// that can carry a caveat, a caveated finding exposes NO auto-fixable action,
4630/// and an uncaveated one is untouched. Adding a caveated finding type without
4631/// registering it in `impl_caveated_finding!` fails to compile at the
4632/// `set_reachability_caveats` call the annotation pass makes; adding one that
4633/// exposes an auto-fixable mutation and never gets annotated is what
4634/// `every_auto_fixable_dead_code_mutation_is_gated` catches.
4635#[cfg(test)]
4636#[path = "output_dead_code_mutation_gate.rs"]
4637mod mutation_gate;
4638
4639#[cfg(test)]
4640#[path = "output_dead_code_position_0_invariants.rs"]
4641mod position_0_invariants;