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