Skip to main content

fallow_types/
output.rs

1//! Types that describe fallow's JSON output contract.
2//!
3//! Today the JSON serialization layer (`crates/cli/src/report/json.rs`) builds
4//! its output via `serde_json::json!` macros. The types defined here are the
5//! schema-side counterpart of that output: they document, with Rust's type
6//! system, the augmentations the JSON layer adds to each per-finding struct
7//! (the `actions` array on every finding, the optional `introduced` flag in
8//! audit-mode sub-results).
9//!
10//! The `schema-emit` binary derives `JsonSchema` for these types (gated by the
11//! `schema` cargo feature) so the public `docs/output-schema.json` stays in
12//! sync with the Rust source of truth. A future refactor will route the JSON
13//! emission path through these types directly, eliminating the drift class
14//! between the augmentation list here and the `serde_json::json!` builders.
15
16use serde::{Deserialize, Serialize};
17
18/// A suggested action attached to a finding in the JSON output. Each finding
19/// carries an `actions` array; consumers (agents, IDE clients, CI bots) can
20/// dispatch on the `type` discriminant to choose the right remediation.
21///
22/// The discriminator is `type` (snake_case `type` field), the payload uses the
23/// matching kebab-case identifier per variant.
24///
25/// ## `auto_fixable` is per-finding, not per action type
26///
27/// Every action variant carries an `auto_fixable: bool` field. The value is
28/// evaluated per finding, not per action type: the same action type may
29/// appear with `auto_fixable: true` on one finding and `auto_fixable: false`
30/// on another, depending on per-instance guards in the `fallow fix` applier.
31/// Agents that filter on `auto_fixable: true` must branch on the bool of
32/// each individual finding's action, not on the action `type` alone.
33///
34/// Current per-instance flips:
35///
36/// - `remove-catalog-entry` (`unused-catalog-entries`): `true` only when the
37///   finding's `hardcoded_consumers` array is empty and the source is
38///   `pnpm-workspace.yaml`. When a workspace package still pins a hardcoded
39///   version of the same package, `fallow fix` skips the entry to avoid
40///   breaking `pnpm install`. Bun `package.json` catalog entries are also
41///   emitted with `auto_fixable: false` because the current fixer is
42///   YAML-only.
43/// - `remove-dependency` vs `move-dependency` (dependency findings): when the
44///   finding's `used_in_workspaces` array is non-empty, the primary action
45///   flips to `move-dependency` with `auto_fixable: false` (`fallow fix` will
46///   not remove a dependency that another workspace imports). On findings
47///   without cross-workspace consumers the action stays `remove-dependency`
48///   with `auto_fixable: true`.
49/// - `add-to-config` for `ignoreExports` (`duplicate-exports`): `true` when
50///   `fallow fix` can safely apply the action without further user setup.
51///   That is: a fallow config file exists on disk, OR no config exists AND
52///   the working directory is NOT inside a monorepo subpackage (in which
53///   case the applier creates `.fallowrc.json` from `fallow init`'s
54///   framework-aware scaffolding and layers the new rules on top).
55///   `false` inside a monorepo subpackage with no workspace-root config
56///   (the applier refuses to fragment per-package configs across the
57///   monorepo and points at the workspace root instead).
58/// - `remove-export` (`unused-exports`, `unused-types`) in a generated file:
59///   `false`, with
60///   the reason in `note`. A generator writes the file again, so `fallow fix`
61///   keeps the file. Such a finding has no `suppress-line` action, because
62///   the generator removes the comment too. It has an `add-to-config` action
63///   with the `ignoreExports` rule for the file.
64/// - `add-to-config` for `ignoreExports` (`unused-exports`, `unused-types`):
65///   always `false`. The action is present on a finding in a generated file,
66///   and on an unused export in a shadcn/ui folder that `components.json`
67///   names.
68/// - `update-catalog-reference` (`unresolved-catalog-references`): always
69///   `false` today (the catalog-switching applier is not wired in yet); the
70///   field is non-singleton so that future enablement does not require a
71///   schema change.
72///
73/// All `suppress-line` and `suppress-file` actions are uniformly
74/// `auto_fixable: false`. The field is non-singleton on the wire so that a
75/// future auto-applier (e.g. an LLM-driven suppression writer) can promote
76/// individual variants without a schema bump.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
79#[serde(untagged)]
80pub enum IssueAction {
81    /// A code-change fix the user can apply (auto-fixable by `fallow fix` for
82    /// some variants, manual for others).
83    Fix(FixAction),
84    /// Place a `// fallow-ignore-next-line ...` comment above the offending
85    /// line. Always manual.
86    SuppressLine(SuppressLineAction),
87    /// Place a `// fallow-ignore-file ...` comment at the top of the file.
88    /// Always manual.
89    SuppressFile(SuppressFileAction),
90    /// Add the offending finding to the fallow config (e.g.
91    /// `ignoreDependencies: ["lodash"]`). Auto-fixable for the array-shaped
92    /// `ignoreExports` variant when `fallow fix` can safely apply the
93    /// action (config file exists, or no config exists and the working
94    /// directory is not inside a monorepo subpackage); manual otherwise.
95    AddToConfig(AddToConfigAction),
96}
97
98impl IssueAction {
99    /// Whether the current finding-specific action can be applied by
100    /// `fallow fix`.
101    #[must_use]
102    pub const fn is_auto_fixable(&self) -> bool {
103        match self {
104            Self::Fix(action) => action.auto_fixable,
105            Self::SuppressLine(action) => action.auto_fixable,
106            Self::SuppressFile(action) => action.auto_fixable,
107            Self::AddToConfig(action) => action.auto_fixable,
108        }
109    }
110}
111
112/// A code-change fix. `type` is one of the kebab-case identifiers in
113/// [`FixActionType`].
114#[derive(Debug, Clone, Serialize, Deserialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116pub struct FixAction {
117    /// Kebab-case identifier for the fix action.
118    #[serde(rename = "type")]
119    pub kind: FixActionType,
120    /// Whether `fallow fix` can apply this fix automatically. Evaluated per
121    /// finding, not per action type: the same `type` may carry
122    /// `auto_fixable: true` on one finding and `auto_fixable: false` on
123    /// another when per-instance guards in the applier discriminate (e.g.
124    /// `remove-catalog-entry` flips on `hardcoded_consumers` and catalog
125    /// source file, the primary dependency action flips between
126    /// `remove-dependency` / `move-dependency` on `used_in_workspaces`).
127    /// Filter on this bool of each individual action, not on `type`. See the
128    /// [`IssueAction`] enum-level docs for the full list of per-instance
129    /// flips.
130    ///
131    /// One flip is RUN-level rather than finding-level: a dead-code finding
132    /// carrying `reachability_caveats` reports `false` here, because a file
133    /// this run never fully read may hold the reference that credits it. Every
134    /// mutation surface honours the same gate, so a plan built from this flag
135    /// never expects a write `fallow fix`, the MCP fix tools, or the LSP quick
136    /// fix will refuse. The action stays in the array at the same position and
137    /// names the reason in [`Self::note`].
138    pub auto_fixable: bool,
139    /// Human-readable description of the fix.
140    pub description: String,
141    /// Optional context note. Present on non-auto-fixable actions, and on
142    /// auto-fixable re-export findings to warn about public API surface.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub note: Option<String>,
145    /// Only present on `update-catalog-reference` actions: catalogs in the
146    /// same workspace that DO declare the package, sorted lexicographically.
147    /// Lets agents pick the catalog to switch to without re-reading the
148    /// source.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub available_in_catalogs: Option<Vec<String>>,
151    /// Only present on `update-catalog-reference` actions when exactly one
152    /// alternative catalog declares the package: the unambiguous switch
153    /// target. Lets deterministic (non-LLM) agents land the edit without
154    /// picking from a list. Absent when `available_in_catalogs` has zero
155    /// or more than one entry.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub suggested_target: Option<String>,
158}
159
160/// Discriminant string for [`FixAction`]. Kebab-case per the JSON output
161/// contract.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
163#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
164#[serde(rename_all = "kebab-case")]
165pub enum FixActionType {
166    /// Remove an export declaration from a source file.
167    RemoveExport,
168    /// Delete an entire unused file.
169    DeleteFile,
170    /// Remove an entry from `dependencies` / `devDependencies` in
171    /// `package.json`.
172    RemoveDependency,
173    /// Move an entry between `dependencies` and `devDependencies`.
174    MoveDependency,
175    /// Remove an enum member from a TypeScript enum.
176    RemoveEnumMember,
177    /// Remove a class member (method or property).
178    RemoveClassMember,
179    /// Resolve an unresolved import (manual).
180    ResolveImport,
181    /// Install a missing dependency.
182    InstallDependency,
183    /// Remove a duplicate export (the canonical action for
184    /// `duplicate-exports`).
185    RemoveDuplicate,
186    /// Move a production dependency to `devDependencies`
187    /// (used by type-only-dependency and test-only-dependency findings).
188    MoveToDev,
189    /// Move a `devDependencies` entry to `dependencies`
190    /// (used by dev-dependency-in-production findings; the promote-side mirror
191    /// of [`FixActionType::MoveToDev`]).
192    MoveToProd,
193    /// Break a circular dependency by refactoring imports.
194    RefactorCycle,
195    /// Break a re-export cycle by removing an `export * from` (or
196    /// `export { ... } from`) statement on any one member file. Re-export
197    /// cycles are structurally always bugs (chain propagation through the
198    /// loop is a no-op), so there is no auto-fix; the action is manual.
199    RefactorReExportCycle,
200    /// Resolve a boundary violation by refactoring the import.
201    RefactorBoundary,
202    /// Convert an import statement to a type-only import (used by
203    /// private-type-leak findings).
204    ExportType,
205    /// Move the consumers of a `@deprecated` export to its replacement, then
206    /// remove the export. Manual: fallow does not rewrite consumers.
207    MigrateDeprecatedExport,
208    /// Remove an unused catalog entry. Auto-fix only supports `pnpm-workspace.yaml`;
209    /// Bun `package.json` catalogs are manual.
210    RemoveCatalogEntry,
211    /// Remove an empty named catalog group. Auto-fix only supports
212    /// `pnpm-workspace.yaml`; Bun `package.json` catalogs are manual.
213    RemoveEmptyCatalogGroup,
214    /// Update an existing `catalog:` reference in a workspace `package.json`
215    /// to point at a different (declared) catalog.
216    UpdateCatalogReference,
217    /// Add the missing entry to the referenced catalog.
218    AddCatalogEntry,
219    /// Remove the catalog reference from the workspace `package.json` and
220    /// replace it with a hardcoded version.
221    RemoveCatalogReference,
222    /// Remove an unused dependency override entry.
223    RemoveDependencyOverride,
224    /// Fix a misconfigured dependency override entry (unparsable key or empty
225    /// value).
226    FixDependencyOverride,
227    /// Replace a banned call or banned import flagged by a rule-pack rule
228    /// (manual; the rule's message usually names the sanctioned alternative).
229    ResolvePolicyViolation,
230    /// Move a server-only export out of a `"use client"` file into a
231    /// non-client module (manual; used by invalid-client-export findings).
232    MoveToServerModule,
233    /// Split a barrel that re-exports both client and server-only modules
234    /// into separate client and server barrels (manual; used by
235    /// mixed-client-server-barrel findings).
236    SplitMixedBarrel,
237    /// Hoist a misplaced `"use client"` / `"use server"` directive to the
238    /// leading prologue of the file (manual; used by misplaced-directive
239    /// findings).
240    HoistDirective,
241    /// Wire a server action to a project consumer or remove the unused action
242    /// export (manual; used by unused-server-action findings).
243    WireServerAction,
244    /// Add a provider for an injected key or remove the dead inject call
245    /// (manual; used by unprovided-inject findings).
246    ProvideInject,
247    /// Use a SvelteKit load-data key from the route UI or remove the unused
248    /// returned key (manual; used by unused-load-data-key findings).
249    UseLoadData,
250    /// Render a reachable component from project code or remove the component
251    /// (manual; used by unrendered-component findings).
252    RenderComponent,
253    /// Use a declared component prop or remove it from the component API
254    /// (manual; used by unused-component-prop findings).
255    UseComponentProp,
256    /// Review caller evidence, defaults and component API intent manually.
257    ReviewComponentProp,
258    /// Review the calls, the default and the intent of a parameter that each
259    /// call passes in one way (manual; used by constant-parameter findings).
260    ReviewConstantParameter,
261    /// Emit a declared component event or remove it from the component API
262    /// (manual; used by unused-component-emit findings).
263    EmitComponentEvent,
264    /// Add or forward a Svelte custom-event listener, or remove the dispatch
265    /// (manual; used by unused-svelte-event findings).
266    WireSvelteEvent,
267    /// Compose an Effect layer into a layer that reaches a runtime, or remove
268    /// it (manual; used by unused-effect-layer findings).
269    ComposeEffectLayer,
270    /// Fail with an Effect tagged error from project code, or remove the class
271    /// and its handlers (manual; used by unused-tagged-error findings).
272    FailTaggedError,
273    /// Remove a `catchTag` handler for a tag that nothing produces, or add the
274    /// producer (manual; used by unproduced-catch-tag findings).
275    RemoveCatchTagHandler,
276    /// Resolve a Next.js App Router route collision by moving or merging one of
277    /// the files that own the same URL (manual; suppressing a guaranteed build
278    /// error is never the right fix, so this is the primary action).
279    ResolveRouteCollision,
280    /// Resolve a Next.js dynamic-segment name conflict by renaming the dynamic
281    /// segments at the conflicting position to a single consistent slug name
282    /// (manual).
283    ResolveDynamicSegmentNameConflict,
284    /// Add a human-authored reason to a suppression that requires one.
285    AddSuppressionReason,
286    /// Remove or update a suppression that no longer matches a finding.
287    RemoveStaleSuppression,
288}
289
290/// Inline-comment suppression for a single finding line.
291#[derive(Debug, Clone, Serialize, Deserialize)]
292#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
293pub struct SuppressLineAction {
294    /// Action type identifier.
295    #[serde(rename = "type")]
296    pub kind: SuppressLineKind,
297    /// Always false for suppress actions.
298    pub auto_fixable: bool,
299    /// Human-readable description of the suppression.
300    pub description: String,
301    /// The inline comment to place above the line (e.g.,
302    /// `// fallow-ignore-next-line unused-export`). When multiple
303    /// suppressible findings share the same path and line, this may contain a
304    /// comma-separated issue-kind list such as
305    /// `// fallow-ignore-next-line unused-export, complexity`.
306    pub comment: String,
307    /// Present on multi-location issue types (e.g., `duplicate_exports`) to
308    /// indicate the comment must be applied at each location.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub scope: Option<SuppressLineScope>,
311}
312
313/// Singleton discriminant for [`SuppressLineAction`].
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
315#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
316#[serde(rename_all = "kebab-case")]
317pub enum SuppressLineKind {
318    /// `// fallow-ignore-next-line <kind>` directive.
319    SuppressLine,
320}
321
322/// Scope marker for line suppressions that span multiple locations.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
324#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
325#[serde(rename_all = "kebab-case")]
326pub enum SuppressLineScope {
327    /// Apply the suppression comment at each location of the multi-location
328    /// finding (e.g., every `duplicate_exports` site).
329    PerLocation,
330}
331
332/// File-wide suppression placed at the top of the source file.
333#[derive(Debug, Clone, Serialize, Deserialize)]
334#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
335pub struct SuppressFileAction {
336    /// Action type identifier.
337    #[serde(rename = "type")]
338    pub kind: SuppressFileKind,
339    /// Always false for suppress actions.
340    pub auto_fixable: bool,
341    /// Human-readable description of the suppression.
342    pub description: String,
343    /// The file-level comment to place at the top of the file (e.g.,
344    /// `// fallow-ignore-file unused-file`).
345    pub comment: String,
346}
347
348/// Singleton discriminant for [`SuppressFileAction`].
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
350#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
351#[serde(rename_all = "kebab-case")]
352pub enum SuppressFileKind {
353    /// `// fallow-ignore-file <kind>` directive.
354    SuppressFile,
355}
356
357/// Edit a fallow config file (`.fallowrc.json`, `fallow.toml`, etc.) to
358/// add the offending value to an `ignore*` rule.
359#[derive(Debug, Clone, Serialize, Deserialize)]
360#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
361pub struct AddToConfigAction {
362    /// Action type identifier.
363    #[serde(rename = "type")]
364    pub kind: AddToConfigKind,
365    /// True when `fallow fix` can apply this config action automatically.
366    /// Evaluated per finding, not per action type: `ignoreExports`
367    /// duplicate-export actions are auto-fixable when `fallow fix` can
368    /// safely write the rule, which today means either a fallow config
369    /// file already exists OR no config exists and the working directory
370    /// is NOT inside a monorepo subpackage (in which case the applier
371    /// creates `.fallowrc.json` from `fallow init`'s framework-aware
372    /// scaffolding). The action is `false` inside a monorepo subpackage
373    /// with no workspace-root config because the applier refuses to
374    /// fragment per-package configs across the monorepo. Older scalar
375    /// config-ignore actions (e.g. `ignoreDependencies` on dependency
376    /// findings) are always manual today. Filter on this bool of each
377    /// individual action, not on the `type` alone. See the [`IssueAction`]
378    /// enum-level docs for the full list of per-instance flips.
379    pub auto_fixable: bool,
380    /// Human-readable description of the config change.
381    pub description: String,
382    /// The fallow config key to add the value to (e.g.,
383    /// `ignoreDependencies`).
384    pub config_key: String,
385    /// Value to add to the config key. Shape depends on `config_key`. For
386    /// scalar config keys (`ignoreDependencies`, others) this is a string
387    /// such as `"lodash"`. For `ignoreExports` this is an array of
388    /// `{ file, exports }` rule objects so the snippet can be merged into
389    /// the user's config verbatim. For `ignoreCatalogReferences` and
390    /// `ignoreDependencyOverrides` this is an object whose shape matches the
391    /// rule entry users add to their fallow config.
392    pub value: AddToConfigValue,
393    /// Optional URL pointing at a stable JSON Schema fragment that describes
394    /// the shape of `value`. Agents that intend to validate `value` before
395    /// writing it into a user's config can fetch the linked schema and run
396    /// it against `value`. The URL is a JSON Pointer fragment into fallow's
397    /// main config schema (e.g.
398    /// `schema.json#/properties/ignoreExports` for the ignoreExports
399    /// action, or `schema.json#/properties/ignoreDependencies/items` for
400    /// the per-package ignoreDependencies action). Strictly additive:
401    /// consumers that ignore the field keep working unchanged.
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub value_schema: Option<String>,
404}
405
406/// Singleton discriminant for [`AddToConfigAction`].
407#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
408#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
409#[serde(rename_all = "kebab-case")]
410pub enum AddToConfigKind {
411    /// Append a value into a fallow config `ignore*` list.
412    AddToConfig,
413}
414
415/// Value payload for [`AddToConfigAction::value`]. The variants line up with
416/// the documented per-`config_key` shapes; deserialization is untagged so
417/// downstream consumers can switch on the JSON value's type.
418#[derive(Debug, Clone, Serialize, Deserialize)]
419#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
420#[serde(untagged)]
421pub enum AddToConfigValue {
422    /// Scalar string value (e.g., a package name for
423    /// `ignoreDependencies: ["lodash"]`).
424    Scalar(String),
425    /// Array of file+export rule objects for `ignoreExports`.
426    ExportsRules(Vec<IgnoreExportsRule>),
427    /// Free-form object for rule-shaped keys like
428    /// `ignoreCatalogReferences` / `ignoreDependencyOverrides`. The shape
429    /// matches the rule entry users add to their fallow config; consumers
430    /// validate against the per-key schema referenced by `value_schema`.
431    RuleObject(serde_json::Map<String, serde_json::Value>),
432}
433
434/// Single `ignoreExports` rule entry. The fallow config accepts an array of
435/// these under the `ignoreExports` key.
436#[derive(Debug, Clone, Serialize, Deserialize)]
437#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
438pub struct IgnoreExportsRule {
439    /// File path (forward slashes, relative to project root) to which this
440    /// rule applies. Globs are accepted.
441    pub file: String,
442    /// Names of exports inside `file` to silently treat as used.
443    pub exports: Vec<String>,
444}
445
446/// A read-only follow-up command fallow surfaces from the current findings,
447/// emitted as the top-level `next_steps` array on each command's JSON envelope.
448///
449/// `next_steps` exists to point agents and humans sideways to fallow's adjacent
450/// verification capabilities (trace, complexity breakdown, audit, workspace
451/// scoping) that telemetry shows agents rarely discover, because they act on the
452/// output in front of them rather than on reference docs.
453///
454/// ## Two hard contracts
455///
456/// 1. **Read-only.** A `next_step` never suggests `fallow fix` or any mutating
457///    command. Fallow surfaces evidence and verification paths; deciding and
458///    applying the remediation is the agent's job.
459/// 2. **Runnable, placeholder-free.** `command` is always runnable as-is. It
460///    never contains an angle-bracket placeholder (`<...>`); finding-derived
461///    values are filled in from a real, deterministically-selected finding, and
462///    any environment- or user-specific value that cannot be made concrete lives
463///    in `reason` instead. An agent can copy `command` and run it without edits.
464///
465/// Both contracts are enforced by unit tests in
466/// `crates/cli/src/report/suggestions.rs`.
467///
468/// Note: a separate, unrelated `next_steps` field exists on the
469/// `coverage setup` envelope (`CoverageSetupOutput.next_steps`) as a plain
470/// `Vec<String>` of human onboarding steps. Consumers that read multiple
471/// envelope kinds must route on the envelope's `kind` before interpreting a
472/// `next_steps` field: on analysis envelopes it is `Vec<NextStep>` objects, on
473/// `coverage setup` it is `Vec<String>`.
474#[derive(Debug, Clone, Serialize)]
475#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
476pub struct NextStep {
477    /// Stable kebab-case key for machine dispatch and de-duplication
478    /// (for example `"trace-unused-export"`). Identity is stable across runs;
479    /// the `command` and `reason` strings may vary with the findings.
480    pub id: String,
481    /// A runnable, read-only command string. Placeholder-free by contract.
482    pub command: String,
483    /// One short phrase explaining why this helps. Carries any value that
484    /// cannot be made concrete in `command`.
485    pub reason: String,
486}
487
488/// Description of the `add-to-config` action on an unused export in a
489/// generated file. The human report groups the findings by this text.
490pub const GENERATED_FILE_EXPORTS_HINT: &str = "This file is generated code. Its generator writes the file again, so an edit of the file does not last. Change the input of the generator, or add this `ignoreExports` rule to hide the findings of the file.";
491
492/// Description of the `add-to-config` action on an unused export in a
493/// shadcn/ui component folder. The human report groups the findings by this
494/// text.
495pub const UI_FOLDER_EXPORTS_HINT: &str = "This file is in the shadcn/ui folder that `components.json` names. Add this `ignoreExports` rule to keep each part of a copied component, also before it has a consumer.";