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