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