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