Skip to main content

fallow_types/
envelope.rs

1//! Typed envelope and utility-shape structs for the JSON output contract.
2//!
3//! Today the JSON serialization layer (`crates/cli/src/report/json.rs`) builds
4//! its envelopes (`CheckOutput`, `HealthOutput`, ...) via `serde_json::json!`
5//! macros and ad-hoc map merging. The types in this module are the schema-side
6//! counterpart of those envelopes plus a small set of utility shapes
7//! (`SchemaVersion`, `Meta`, `BaselineDeltas`, ...) that the envelopes
8//! reference.
9//!
10//! Gated on the `schema` cargo feature so consumers that do not need the
11//! `schemars::JsonSchema` derive (every crate except `fallow-cli` with
12//! `--features schema-emit`) skip the schemars compile cost.
13
14use std::collections::BTreeMap;
15
16use serde::Serialize;
17
18/// Schema version for this output format (independent of tool version). Bump
19/// policy: ADDITIVE changes (new optional top-level fields, new optional struct
20/// fields, new array entries, new MCP tools, new CLI flags that map to new
21/// optional fields) do NOT bump the version; consumers receive new fields
22/// without breaking. BREAKING changes (renamed fields, removed fields, type
23/// changes, enum-variant removals, semantic changes to existing fields) DO
24/// bump. To detect newly-added fields without a bump, check field presence via
25/// JSON-key existence rather than gating on the version. v4 was introduced
26/// alongside fallow-cov-protocol 0.2 (per-finding verdict, stable IDs, evidence
27/// block, renamed summary fields); v5 introduced health_score formula_version 2
28/// with scale-invariant scoring semantics; v6 widened `AddToConfigAction.value`
29/// from a scalar string to `oneOf: [string, array]` so the new `ignoreExports`
30/// action can carry a paste-ready array of `{ file, exports }` rule objects
31/// (the legacy `ignoreDependencies` etc. variants still emit strings, so
32/// consumers that switch on `config_key` keep working unchanged). The
33/// runtime-coverage block is extended additively as the protocol evolves
34/// (currently 0.3, which adds an optional capture_quality summary field). Other
35/// additive examples: dupes --group-by adds optional grouped_by, total_issues,
36/// groups fields without bumping.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
38#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
39#[serde(transparent)]
40pub struct SchemaVersion(pub u32);
41
42/// Fallow CLI version that produced this envelope. Renders to the JSON wire as
43/// a bare string (e.g. `"2.74.0"`).
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46#[serde(transparent)]
47pub struct ToolVersion(pub String);
48
49/// Analysis duration in milliseconds. Renders to the JSON wire as a bare
50/// integer.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
52#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
53#[serde(transparent)]
54pub struct ElapsedMs(pub u64);
55
56/// Audit-mode marker emitted on each finding when `fallow audit --format json`
57/// runs with a base ref. `true` means the finding's structural key was not
58/// present at the base ref (introduced by the current changeset); `false`
59/// means it was inherited.
60///
61/// Outside of audit sub-results the field is omitted, so call sites typically
62/// hold `Option<AuditIntroduced>`. Renders to the JSON wire as a bare boolean.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
65#[serde(transparent)]
66pub struct AuditIntroduced(pub bool);
67
68/// Entry-point detection summary embedded in `CheckOutput` and the combined
69/// envelope.
70#[derive(Debug, Clone, Default, Serialize)]
71#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
72pub struct EntryPoints {
73    /// Total number of detected entry points.
74    pub total: usize,
75    /// Breakdown of entry points by detection source (e.g., `"package.json"`,
76    /// `"next.js"`, `"config entry"`). Underscored keys so dashboards can
77    /// drill into individual sources.
78    pub sources: BTreeMap<String, usize>,
79}
80
81/// Per-category issue counts for dead-code analysis. Always present in
82/// `CheckOutput`; when `--summary` is used the individual issue arrays are
83/// omitted but this object stays populated.
84#[derive(Debug, Clone, Default, Serialize)]
85#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
86pub struct CheckSummary {
87    /// Total number of issues across all categories.
88    pub total_issues: usize,
89    /// Unused source files.
90    pub unused_files: usize,
91    /// Unused value exports.
92    pub unused_exports: usize,
93    /// Unused type exports.
94    pub unused_types: usize,
95    /// Public exports whose signature references same-file private types.
96    pub private_type_leaks: usize,
97    /// Combined count of unused entries across `dependencies`,
98    /// `devDependencies`, and `optionalDependencies`. The per-section
99    /// breakdown lives in the individual issue arrays on `CheckOutput`.
100    pub unused_dependencies: usize,
101    /// Unused enum members.
102    pub unused_enum_members: usize,
103    /// Unused class members.
104    pub unused_class_members: usize,
105    /// Unused store members.
106    #[serde(default)]
107    pub unused_store_members: usize,
108    /// Vue/Svelte injects whose key is provided nowhere in the project.
109    #[serde(default)]
110    pub unprovided_injects: usize,
111    /// Vue/Svelte components reachable but rendered nowhere in the project.
112    #[serde(default)]
113    pub unrendered_components: usize,
114    /// Vue `<script setup>` props referenced nowhere inside their own SFC.
115    #[serde(default)]
116    pub unused_component_props: usize,
117    /// Vue `<script setup>` emits emitted nowhere inside their own SFC.
118    #[serde(default)]
119    pub unused_component_emits: usize,
120    /// Angular `@Input()` bindings referenced nowhere inside their own component.
121    #[serde(default)]
122    pub unused_component_inputs: usize,
123    /// Angular `@Output()` bindings emitted nowhere inside their own component.
124    #[serde(default)]
125    pub unused_component_outputs: usize,
126    /// Svelte components dispatching a custom event via `createEventDispatcher`
127    /// whose name is listened to nowhere in the project.
128    #[serde(default)]
129    pub unused_svelte_events: usize,
130    /// Next.js Server Actions (exports of `"use server"` files) referenced by no
131    /// code in the project.
132    #[serde(default)]
133    pub unused_server_actions: usize,
134    /// SvelteKit `load()` return-object keys read by no consumer.
135    #[serde(default)]
136    pub unused_load_data_keys: usize,
137    /// Imports that could not be resolved against the project's module graph.
138    pub unresolved_imports: usize,
139    /// Dependencies imported but absent from `package.json`.
140    pub unlisted_dependencies: usize,
141    /// Same-named exports declared in more than one module.
142    pub duplicate_exports: usize,
143    /// Production dependencies only used via type-only imports (could be
144    /// devDependencies). Only populated in production mode.
145    pub type_only_dependencies: usize,
146    /// Production dependencies only imported by test files (could be
147    /// devDependencies).
148    pub test_only_dependencies: usize,
149    /// Cycles detected in the import graph.
150    pub circular_dependencies: usize,
151    /// Cycles or self-loops in the re-export edge subgraph (barrel files
152    /// re-exporting from each other in a loop).
153    #[serde(default)]
154    pub re_export_cycles: usize,
155    /// Imports that cross architecture boundary rules.
156    pub boundary_violations: usize,
157    /// Files that match no architecture boundary zone.
158    #[serde(default)]
159    pub boundary_coverage_violations: usize,
160    /// Calls from zoned files to callees forbidden for that zone.
161    #[serde(default)]
162    pub boundary_call_violations: usize,
163    /// Banned calls and banned imports matched by declarative rule packs.
164    #[serde(default)]
165    pub policy_violations: usize,
166    /// Suppression comments that no longer match a finding.
167    pub stale_suppressions: usize,
168    /// Unused pnpm-workspace catalog entries.
169    pub unused_catalog_entries: usize,
170    /// Empty named catalog groups.
171    pub empty_catalog_groups: usize,
172    /// Workspace package.json catalog references the workspace catalogs
173    /// do not declare.
174    pub unresolved_catalog_references: usize,
175    /// Pnpm `overrides:` entries whose target package is not declared by any
176    /// workspace package and not present in the lockfile.
177    pub unused_dependency_overrides: usize,
178    /// Pnpm `overrides:` entries whose key or value cannot be parsed.
179    pub misconfigured_dependency_overrides: usize,
180    /// `"use client"` files that export a Next.js server-only / route-config name.
181    #[serde(default)]
182    pub invalid_client_exports: usize,
183    /// Barrel files that re-export both a `"use client"` origin and a
184    /// server-only origin.
185    #[serde(default)]
186    pub mixed_client_server_barrels: usize,
187    /// Misplaced `"use client"` / `"use server"` directives written as
188    /// expression statements after a non-directive statement.
189    #[serde(default)]
190    pub misplaced_directives: usize,
191    /// Next.js App Router route files that resolve to the same URL within one
192    /// app-root.
193    #[serde(default)]
194    pub route_collisions: usize,
195    /// Sibling Next.js dynamic route segments at one position using different
196    /// param spellings.
197    #[serde(default)]
198    pub dynamic_segment_name_conflicts: usize,
199}
200
201/// Per-category delta comparison against a saved baseline. Only present in
202/// `CheckOutput` when `--baseline` is used.
203#[derive(Debug, Clone, Default, Serialize)]
204#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
205pub struct BaselineDeltas {
206    /// Net change in total issues vs baseline (positive = more issues).
207    pub total_delta: i64,
208    /// Per-category breakdown of current, baseline, and delta counts.
209    pub per_category: BTreeMap<String, BaselineCategoryDelta>,
210}
211
212/// Single-category baseline delta entry inside [`BaselineDeltas::per_category`].
213#[derive(Debug, Clone, Copy, Default, Serialize)]
214#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
215pub struct BaselineCategoryDelta {
216    /// Current issue count for this category.
217    pub current: usize,
218    /// Baseline issue count for this category.
219    pub baseline: usize,
220    /// Change from baseline (current - baseline).
221    pub delta: i64,
222}
223
224/// Baseline match statistics. Shows how many baseline entries existed and how
225/// many matched current issues. Useful for detecting stale baselines
226/// programmatically. Only present in `CheckOutput` when `--baseline` is used.
227#[derive(Debug, Clone, Copy, Default, Serialize)]
228#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229pub struct BaselineMatch {
230    /// Total number of entries in the loaded baseline file.
231    pub entries: usize,
232    /// Number of baseline entries that matched current issues and were
233    /// filtered.
234    pub matched: usize,
235}
236
237/// Result of regression detection (`--fail-on-regression`). Compares current
238/// issue counts against a baseline from config or an explicit file.
239#[derive(Debug, Clone, Serialize)]
240#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
241pub struct RegressionResult {
242    /// Outcome of the regression check.
243    pub status: RegressionStatus,
244    /// Baseline total before the change. Absent when status is `skipped`.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub baseline_total: Option<i64>,
247    /// Current total after the change. Absent when status is `skipped`.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub current_total: Option<i64>,
250    /// Difference current - baseline. Absent when status is `skipped`.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub delta: Option<i64>,
253    /// Configured tolerance, interpreted per [`RegressionToleranceKind`].
254    /// Absent when status is `skipped`.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub tolerance: Option<f64>,
257    /// Interpretation of the tolerance value.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub tolerance_kind: Option<RegressionToleranceKind>,
260    /// Whether the regression exceeded the tolerance.
261    pub exceeded: bool,
262    /// Only present when status is `skipped`.
263    #[serde(default, skip_serializing_if = "Option::is_none")]
264    pub reason: Option<String>,
265}
266
267/// Status of a regression-check pass.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
269#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
270#[serde(rename_all = "lowercase")]
271pub enum RegressionStatus {
272    /// Issue count within tolerance.
273    Pass,
274    /// Issue count exceeded tolerance.
275    Exceeded,
276    /// Regression check did not run (missing baseline, etc.).
277    Skipped,
278}
279
280/// Interpretation of [`RegressionResult::tolerance`].
281#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
282#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
283#[serde(rename_all = "lowercase")]
284pub enum RegressionToleranceKind {
285    /// Tolerance is interpreted as an absolute issue-count delta.
286    Absolute,
287    /// Tolerance is interpreted as a percentage of the baseline total.
288    Percentage,
289}
290
291/// Metric and rule definitions emitted under `_meta` when `--explain` is
292/// passed (always present in MCP responses). Helps AI agents and CI systems
293/// interpret metric values without re-reading the docs site.
294#[derive(Debug, Clone, Default, Serialize)]
295#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
296pub struct Meta {
297    /// URL to the documentation page for this command.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub docs: Option<String>,
300    /// Local telemetry correlation metadata for agent follow-up runs.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub telemetry: Option<TelemetryMeta>,
303    /// Per-field definitions for envelope fields and action payload fields.
304    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
305    pub field_definitions: BTreeMap<String, String>,
306    /// Per-metric definitions: name, description, range, interpretation.
307    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
308    pub metrics: BTreeMap<String, MetaMetric>,
309    /// Per-rule definitions for check command output.
310    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
311    pub rules: BTreeMap<String, MetaRule>,
312}
313
314/// Privacy-safe local run metadata emitted for JSON consumers.
315#[derive(Debug, Clone, Default, Serialize)]
316#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
317pub struct TelemetryMeta {
318    /// Ephemeral local token that may be passed to the hidden `--parent-run`
319    /// flag on a later command. It is not derived from repository, path, user,
320    /// machine, project, or cloud data.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub analysis_run_id: Option<String>,
323}
324
325/// Single-metric definition inside [`Meta::metrics`].
326#[derive(Debug, Clone, Default, Serialize)]
327#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
328pub struct MetaMetric {
329    /// Human-readable metric name.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub name: Option<String>,
332    /// What this metric measures and how it is computed.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub description: Option<String>,
335    /// Valid value range (e.g., `"[0, 100]"`).
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub range: Option<String>,
338    /// How to read the value (e.g., `"lower is better"`).
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub interpretation: Option<String>,
341}
342
343/// Single-rule definition inside [`Meta::rules`].
344#[derive(Debug, Clone, Default, Serialize)]
345#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
346pub struct MetaRule {
347    /// Human-readable rule name.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub name: Option<String>,
350    /// What this rule detects.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub description: Option<String>,
353    /// URL to the rule documentation.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub docs: Option<String>,
356}