Skip to main content

fallow_types/
output_health.rs

1//! Per-action types attached to each health finding by the JSON output
2//! layer.
3//!
4//! These types are the typed wire shape for health output data shared outside
5//! the CLI crate, including `actions[]` arrays and refactoring target
6//! evidence. The JSON emission path constructs action entries through typed
7//! wrappers (for example `UntestedFileFinding` in
8//! `crates/output/src/health_coverage_gaps.rs`) and serializes them via serde;
9//! the schemars derive renders matching shapes in `docs/output-schema.json`.
10//!
11//! Whenever a new action variant or optional field is added, update the
12//! matching type here so the drift gate flags the divergence before review.
13
14use std::path::PathBuf;
15
16use serde::{Deserialize, Serialize};
17
18/// Evidence linking a refactoring target back to specific analysis data.
19#[derive(Debug, Clone, Default, Serialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub struct TargetEvidence {
22    /// Names of unused exports.
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub unused_exports: Vec<String>,
25    /// Complex functions with line numbers and cognitive scores.
26    #[serde(default, skip_serializing_if = "Vec::is_empty")]
27    pub complex_functions: Vec<EvidenceFunction>,
28    /// Files forming the import cycle.
29    #[serde(default, skip_serializing_if = "Vec::is_empty")]
30    pub cycle_path: Vec<String>,
31    /// Files that directly import this target, with imported and local symbols.
32    #[serde(default, skip_serializing_if = "Vec::is_empty")]
33    pub direct_callers: Vec<DirectCallerEvidence>,
34    /// Other duplicate-code instances that share a clone group with this target.
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub clone_siblings: Vec<CloneSiblingEvidence>,
37}
38
39/// A function referenced in target evidence.
40#[derive(Debug, Clone, Serialize)]
41#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
42pub struct EvidenceFunction {
43    /// Function name.
44    pub name: String,
45    /// 1-based line number.
46    pub line: u32,
47    /// Cognitive complexity score.
48    pub cognitive: u16,
49}
50
51/// A direct importer referenced in target evidence.
52#[derive(Debug, Clone, Serialize)]
53#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54pub struct DirectCallerEvidence {
55    /// File that directly imports the target.
56    #[serde(serialize_with = "crate::serde_path::serialize")]
57    pub path: PathBuf,
58    /// Symbols imported from the target by this file.
59    #[serde(default, skip_serializing_if = "Vec::is_empty")]
60    pub symbols: Vec<DirectCallerSymbolEvidence>,
61}
62
63/// Symbol details for a direct importer.
64#[derive(Debug, Clone, Serialize)]
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66pub struct DirectCallerSymbolEvidence {
67    /// Imported binding name.
68    pub imported: String,
69    /// Local binding name in the importing file.
70    pub local: String,
71    /// Whether the import is type-only.
72    pub type_only: bool,
73}
74
75/// A duplicate-code sibling referenced in target evidence.
76#[derive(Debug, Clone, Serialize)]
77#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
78pub struct CloneSiblingEvidence {
79    /// File containing the sibling clone instance.
80    #[serde(serialize_with = "crate::serde_path::serialize")]
81    pub path: PathBuf,
82    /// 1-based start line of the sibling clone.
83    pub start_line: usize,
84    /// 1-based end line of the sibling clone.
85    pub end_line: usize,
86    /// Stable duplicate-group handle, matching `dupes --trace dup:<id>`.
87    pub fingerprint: String,
88}
89
90/// Suggested action attached to a [`ComplexityViolation`].
91///
92/// Each complexity finding carries an array of these on the JSON wire
93/// (`findings[].actions[]`). The action selector in
94/// `crates/cli/src/report/json.rs::build_health_finding_actions` picks the
95/// primary action based on which thresholds triggered the finding and the
96/// bucketed coverage tier. See [`HealthFindingActionType`] for the full
97/// discriminant list.
98///
99/// `note`, `comment`, and `placement` are populated per-variant: refactor
100/// actions carry a `note`, suppress-line / suppress-file actions carry
101/// `comment` plus `placement`, and the coverage-leaning actions
102/// (`add-tests`, `increase-coverage`) carry only `note`.
103///
104/// [`ComplexityViolation`]: ../../fallow-output/src/health_scores.rs
105#[derive(Debug, Clone, Serialize, Deserialize)]
106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
107pub struct HealthFindingAction {
108    /// Action type identifier. A single finding's `actions` array can carry
109    /// MULTIPLE entries of different types: e.g., a finding that exceeded
110    /// both cyclomatic and CRAP at `coverage_tier`: partial will get BOTH
111    /// `increase-coverage` AND `refactor-function`, plus `suppress-line`.
112    /// Consumers that select a single action should treat the FIRST
113    /// non-`suppress-{line,file}` action as primary. `add-tests` is emitted
114    /// when CRAP triggered the finding, the function has no test coverage
115    /// (`coverage_tier`: none), and full coverage can bring CRAP below
116    /// `max_crap_threshold` (cyclomatic < threshold, since CRAP bottoms out
117    /// at CC at 100% coverage). `increase-coverage` is emitted when CRAP
118    /// triggered the finding, some coverage exists (`coverage_tier`: partial
119    /// or high), and full coverage can bring CRAP below `max_crap_threshold`;
120    /// the description steers toward targeted branch coverage rather than
121    /// scaffolding new tests. `refactor-function` is emitted when
122    /// cyclomatic/cognitive triggered the finding, when full coverage still
123    /// cannot bring CRAP below `max_crap_threshold` (cyclomatic >=
124    /// threshold), or as a secondary action when cyclomatic is within the
125    /// configured `health.crapRefactorBand` of the cyclomatic threshold AND
126    /// cognitive is at or above `max_cognitive_threshold / 2` (the cognitive
127    /// floor suppresses false positives on flat type-tag dispatchers and JSX
128    /// render maps where high cyclomatic comes from a single switch with
129    /// near-zero cognitive load). `suppress-file` is emitted instead of
130    /// `suppress-line` for
131    /// synthetic Angular `<template>` findings on `.html` files, because
132    /// line-suppression comments cannot be expressed in HTML; the `comment`
133    /// field carries `<!-- fallow-ignore-file complexity -->` and
134    /// `placement` is `top-of-template`.
135    #[serde(rename = "type")]
136    pub kind: HealthFindingActionType,
137    /// Whether `fallow fix` can auto-apply this action. Today every health
138    /// finding action is manual, but the field is non-singleton so a future
139    /// auto-applier (e.g., an LLM-driven `refactor-function` worker) does
140    /// not need a schema change.
141    pub auto_fixable: bool,
142    /// Human-readable description of the action.
143    pub description: String,
144    /// Additional context (e.g., the canonical CRAP formula, or a hint
145    /// about which branch type to extract). Present on most action types;
146    /// dropped only when the description carries the full ask.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub note: Option<String>,
149    /// The inline comment to insert (e.g.,
150    /// `// fallow-ignore-next-line complexity` or
151    /// `<!-- fallow-ignore-file complexity -->`). Present on
152    /// `suppress-line` and `suppress-file` action variants.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub comment: Option<String>,
155    /// Where to insert the suppress comment
156    /// (e.g., `above-function-declaration`, `above-angular-decorator`,
157    /// `above-template-anchor-line`, `above-component-worst-method`, or
158    /// `top-of-template`). Present on `suppress-line` and `suppress-file`
159    /// action variants. `above-template-anchor-line` is used for
160    /// single-file-component markup (`.svelte`, `.vue`, `.astro`), where the
161    /// synthetic `<template>` unit is anchored at its first contributing
162    /// construct rather than at the top of the file, so the comment belongs on
163    /// the line immediately preceding the reported line.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub placement: Option<String>,
166    /// Project-relative path the action should target when the finding's
167    /// remediation lives in a different file from where the finding is
168    /// anchored. Currently populated on the `increase-coverage` action for
169    /// synthetic Angular `<template>` findings whose CRAP is inherited from
170    /// the owning `.component.ts`: the action points at the component file
171    /// (where the user actually adds tests) rather than the `.html` template
172    /// (where the finding is anchored but which is not directly testable).
173    /// Absent when the action's target is the finding's own file.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub target_path: Option<String>,
176}
177
178/// Discriminant for [`HealthFindingAction::kind`]. Mirrors the action types
179/// emitted by `build_health_finding_actions`. A single finding's `actions`
180/// array may carry multiple entries of different types: a finding that
181/// exceeded both cyclomatic and CRAP at `coverage_tier: partial` will get
182/// BOTH `increase-coverage` AND `refactor-function`, plus the trailing
183/// `suppress-line`.
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
185#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
186#[serde(rename_all = "kebab-case")]
187pub enum HealthFindingActionType {
188    /// Refactor the function to reduce complexity. Emitted when
189    /// cyclomatic/cognitive triggered the finding, when full coverage
190    /// still cannot bring CRAP below `max_crap_threshold`, or as a
191    /// secondary action when cyclomatic is within the configured
192    /// `health.crapRefactorBand` of the cyclomatic threshold AND cognitive
193    /// is at or above the cognitive floor.
194    RefactorFunction,
195    /// Add tests for a CRAP-triggered finding whose coverage tier is
196    /// `none` (no test path reaches the function).
197    AddTests,
198    /// Increase test coverage for a CRAP-triggered finding whose coverage
199    /// tier is `partial` or `high` (some test path exists; add targeted
200    /// assertions for uncovered branches).
201    IncreaseCoverage,
202    /// Suppress for the whole file. Used for synthetic Angular `<template>`
203    /// findings on `.html` files where a line suppression cannot be
204    /// expressed (an HTML comment at the top of the template), and for
205    /// file-length findings (`// fallow-ignore-file complexity` at the top of
206    /// the file).
207    SuppressFile,
208    /// Suppress with a next-line comment above the reported line: the
209    /// inline `// fallow-ignore-next-line complexity` form above a function
210    /// or Angular decorator, or the markup
211    /// `<!-- fallow-ignore-next-line complexity -->` form for synthetic
212    /// `<template>` findings in `.svelte`, `.vue`, and `.astro` files.
213    SuppressLine,
214    /// Split a file that exceeds `health.maxFileLines` into smaller modules.
215    /// Emitted only on a file-length finding (`exceeded: "file_lines"`).
216    SplitFile,
217}
218
219/// Suggested action attached to a [`HotspotEntry`].
220///
221/// The action list always begins with `refactor-file` plus `add-tests`.
222/// Ownership-derived variants (`low-bus-factor`, `unowned-hotspot`,
223/// `ownership-drift`) are appended only when `--ownership` is active AND
224/// the corresponding signal fires for the hotspot.
225///
226/// [`HotspotEntry`]: ../../fallow-output/src/health_scores.rs
227#[derive(Debug, Clone, Serialize, Deserialize)]
228#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229pub struct HotspotAction {
230    /// Action type identifier.
231    #[serde(rename = "type")]
232    pub kind: HotspotActionType,
233    /// Whether `fallow fix` can auto-apply this action. Today every
234    /// hotspot action is manual.
235    pub auto_fixable: bool,
236    /// Human-readable description of the action.
237    pub description: String,
238    /// Additional context for the action. Absent on `low-bus-factor` when
239    /// the finding's description already carries the full ask (no
240    /// suggested reviewers and not a low-commit file).
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub note: Option<String>,
243    /// Suggested CODEOWNERS pattern. Present only on `unowned-hotspot`
244    /// actions. Derived per the [`heuristic`](Self::heuristic) field;
245    /// consumers should branch on [`heuristic`](Self::heuristic) rather
246    /// than assume a stable algorithm.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub suggested_pattern: Option<String>,
249    /// Strategy used to derive [`suggested_pattern`](Self::suggested_pattern).
250    /// Reserved for future evolution (`codeowners-cluster`, etc.).
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub heuristic: Option<HotspotActionHeuristic>,
253}
254
255/// Discriminant for [`HotspotAction::kind`].
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
257#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
258#[serde(rename_all = "kebab-case")]
259pub enum HotspotActionType {
260    /// Refactor the hotspot file (high complexity plus frequent change).
261    RefactorFile,
262    /// Add test coverage to reduce change risk on the hotspot file.
263    AddTests,
264    /// Bus factor of 1: a single recent contributor owns the file.
265    /// Emitted only with `--ownership`.
266    LowBusFactor,
267    /// Hotspot matches no CODEOWNERS rule (a rules file exists but no
268    /// pattern matches). Emitted only with `--ownership`.
269    UnownedHotspot,
270    /// Ownership has drifted from the original author to a new top
271    /// contributor. Emitted only with `--ownership`.
272    OwnershipDrift,
273}
274
275/// Strategy discriminant for the suggested CODEOWNERS pattern attached to
276/// an `unowned-hotspot` action.
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
278#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
279#[serde(rename_all = "kebab-case")]
280pub enum HotspotActionHeuristic {
281    /// Suggest the deepest directory containing the file (e.g.,
282    /// `/src/api/users/`). Keeps the suggestion reviewable while staying
283    /// a directory pattern rather than a per-file rule.
284    DirectoryDeepest,
285}
286
287/// Suggested action attached to a [`RefactoringTarget`].
288///
289/// The list always begins with `apply-refactoring`. A trailing
290/// `suppress-line` is appended only when the target carries `evidence`
291/// linking to specific functions (e.g., `extract_complex_functions`,
292/// `add_test_coverage`).
293///
294/// Unlike [`HealthFindingAction`], the `suppress-line` variant emitted
295/// here does NOT carry a `placement` field: the parent
296/// [`RefactoringTarget`] points at a file (not a specific function
297/// declaration site), so a per-line placement hint would have no
298/// referent. Consumers that want the placement metadata should follow
299/// the target's `evidence.complex_functions` back to the matching
300/// `ComplexityViolation` and read placement from THAT action instead.
301///
302/// [`RefactoringTarget`]: ../../fallow-output/src/health_targets.rs
303#[derive(Debug, Clone, Serialize, Deserialize)]
304#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
305pub struct RefactoringTargetAction {
306    /// Action type identifier.
307    #[serde(rename = "type")]
308    pub kind: RefactoringTargetActionType,
309    /// Whether `fallow fix` can auto-apply this action. Today both
310    /// variants are manual.
311    pub auto_fixable: bool,
312    /// Human-readable description of the action. For `apply-refactoring`
313    /// this is the target's own `recommendation` string; for
314    /// `suppress-line` it is the suppression prompt.
315    pub description: String,
316    /// Recommendation category for `apply-refactoring` actions. Mirrors
317    /// the parent target's
318    /// [`category`](../../fallow-output/src/health_targets.rs.html)
319    /// field so consumers can route on the action alone.
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub category: Option<String>,
322    /// The inline comment to insert. Present on `suppress-line` actions
323    /// when evidence exists.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub comment: Option<String>,
326}
327
328/// Discriminant for [`RefactoringTargetAction::kind`].
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
330#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
331#[serde(rename_all = "kebab-case")]
332pub enum RefactoringTargetActionType {
333    /// Apply the recommended refactoring (extract, split, decouple, etc.).
334    ApplyRefactoring,
335    /// Suppress the underlying complexity finding with an inline comment.
336    SuppressLine,
337}
338
339/// Suggested action attached to an [`UntestedFile`] coverage-gap finding.
340///
341/// `build_untested_file_actions` emits a two-entry array on every
342/// untested-file item: an `add-tests` primary action (scaffold tests for
343/// the runtime file) and a `suppress-file` action
344/// (`// fallow-ignore-file coverage-gaps`). Both variants share the same
345/// struct shape; the field that is populated (`note` for `add-tests`,
346/// `comment` for `suppress-file`) depends on the `kind`.
347///
348/// [`UntestedFile`]: ../../fallow-output/src/health_coverage_gaps.rs
349#[derive(Debug, Clone, Serialize, Deserialize)]
350#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
351pub struct UntestedFileAction {
352    /// Action type identifier.
353    #[serde(rename = "type")]
354    pub kind: UntestedFileActionType,
355    /// Whether `fallow fix` can auto-apply this action. Today both
356    /// variants are manual.
357    pub auto_fixable: bool,
358    /// Human-readable description of the action.
359    pub description: String,
360    /// Additional context for the `add-tests` variant (explains why no
361    /// test path reaches this file). Absent on `suppress-file`.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub note: Option<String>,
364    /// The file-level comment to insert. Present on `suppress-file`
365    /// (`// fallow-ignore-file coverage-gaps`). Absent on `add-tests`.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub comment: Option<String>,
368}
369
370/// Discriminant for [`UntestedFileAction::kind`]. Mirrors the action types
371/// emitted by `build_untested_file_actions`.
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 UntestedFileActionType {
376    /// Scaffold tests that exercise the runtime file.
377    AddTests,
378    /// Suppress coverage-gap reporting for this file with a file-level
379    /// comment.
380    SuppressFile,
381}
382
383/// Suggested action attached to an [`UntestedExport`] coverage-gap
384/// finding.
385///
386/// `build_untested_export_actions` emits a two-entry array on every
387/// untested-export item: an `add-test-import` primary action (import the
388/// export from a test-reachable module) and a `suppress-file` action
389/// (`// fallow-ignore-file coverage-gaps`). The export-specific variant
390/// `add-test-import` reflects that a test-reachable reference chain, not
391/// just any test coverage, is what closes the gap.
392///
393/// [`UntestedExport`]: ../../fallow-output/src/health_coverage_gaps.rs
394#[derive(Debug, Clone, Serialize, Deserialize)]
395#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
396pub struct UntestedExportAction {
397    /// Action type identifier.
398    #[serde(rename = "type")]
399    pub kind: UntestedExportActionType,
400    /// Whether `fallow fix` can auto-apply this action. Today both
401    /// variants are manual.
402    pub auto_fixable: bool,
403    /// Human-readable description of the action.
404    pub description: String,
405    /// Additional context for the `add-test-import` variant (explains the
406    /// runtime-reachable / test-unreachable asymmetry). Absent on
407    /// `suppress-file`.
408    #[serde(default, skip_serializing_if = "Option::is_none")]
409    pub note: Option<String>,
410    /// The file-level comment to insert. Present on `suppress-file`
411    /// (`// fallow-ignore-file coverage-gaps`). Absent on
412    /// `add-test-import`.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub comment: Option<String>,
415}
416
417/// Discriminant for [`UntestedExportAction::kind`]. Mirrors the action
418/// types emitted by `build_untested_export_actions`.
419#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
420#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
421#[serde(rename_all = "kebab-case")]
422pub enum UntestedExportActionType {
423    /// Import and exercise the export from a test-reachable module.
424    AddTestImport,
425    /// Suppress coverage-gap reporting for the export's file with a
426    /// file-level comment.
427    SuppressFile,
428}