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