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    /// Imports that could not be resolved against the project's module graph.
106    pub unresolved_imports: usize,
107    /// Dependencies imported but absent from `package.json`.
108    pub unlisted_dependencies: usize,
109    /// Same-named exports declared in more than one module.
110    pub duplicate_exports: usize,
111    /// Production dependencies only used via type-only imports (could be
112    /// devDependencies). Only populated in production mode.
113    pub type_only_dependencies: usize,
114    /// Production dependencies only imported by test files (could be
115    /// devDependencies).
116    pub test_only_dependencies: usize,
117    /// Cycles detected in the import graph.
118    pub circular_dependencies: usize,
119    /// Cycles or self-loops in the re-export edge subgraph (barrel files
120    /// re-exporting from each other in a loop).
121    #[serde(default)]
122    pub re_export_cycles: usize,
123    /// Imports that cross architecture boundary rules.
124    pub boundary_violations: usize,
125    /// Files that match no architecture boundary zone.
126    #[serde(default)]
127    pub boundary_coverage_violations: usize,
128    /// Calls from zoned files to callees forbidden for that zone.
129    #[serde(default)]
130    pub boundary_call_violations: usize,
131    /// Banned calls and banned imports matched by declarative rule packs.
132    #[serde(default)]
133    pub policy_violations: usize,
134    /// Suppression comments that no longer match a finding.
135    pub stale_suppressions: usize,
136    /// Unused pnpm-workspace catalog entries.
137    pub unused_catalog_entries: usize,
138    /// Empty named catalog groups.
139    pub empty_catalog_groups: usize,
140    /// Workspace package.json catalog references the workspace catalogs
141    /// do not declare.
142    pub unresolved_catalog_references: usize,
143    /// Pnpm `overrides:` entries whose target package is not declared by any
144    /// workspace package and not present in the lockfile.
145    pub unused_dependency_overrides: usize,
146    /// Pnpm `overrides:` entries whose key or value cannot be parsed.
147    pub misconfigured_dependency_overrides: usize,
148}
149
150/// Per-category delta comparison against a saved baseline. Only present in
151/// `CheckOutput` when `--baseline` is used.
152#[derive(Debug, Clone, Default, Serialize)]
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154pub struct BaselineDeltas {
155    /// Net change in total issues vs baseline (positive = more issues).
156    pub total_delta: i64,
157    /// Per-category breakdown of current, baseline, and delta counts.
158    pub per_category: BTreeMap<String, BaselineCategoryDelta>,
159}
160
161/// Single-category baseline delta entry inside [`BaselineDeltas::per_category`].
162#[derive(Debug, Clone, Copy, Default, Serialize)]
163#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
164pub struct BaselineCategoryDelta {
165    /// Current issue count for this category.
166    pub current: usize,
167    /// Baseline issue count for this category.
168    pub baseline: usize,
169    /// Change from baseline (current - baseline).
170    pub delta: i64,
171}
172
173/// Baseline match statistics. Shows how many baseline entries existed and how
174/// many matched current issues. Useful for detecting stale baselines
175/// programmatically. Only present in `CheckOutput` when `--baseline` is used.
176#[derive(Debug, Clone, Copy, Default, Serialize)]
177#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
178pub struct BaselineMatch {
179    /// Total number of entries in the loaded baseline file.
180    pub entries: usize,
181    /// Number of baseline entries that matched current issues and were
182    /// filtered.
183    pub matched: usize,
184}
185
186/// Result of regression detection (`--fail-on-regression`). Compares current
187/// issue counts against a baseline from config or an explicit file.
188#[derive(Debug, Clone, Serialize)]
189#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
190pub struct RegressionResult {
191    /// Outcome of the regression check.
192    pub status: RegressionStatus,
193    /// Baseline total before the change. Absent when status is `skipped`.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub baseline_total: Option<i64>,
196    /// Current total after the change. Absent when status is `skipped`.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub current_total: Option<i64>,
199    /// Difference current - baseline. Absent when status is `skipped`.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub delta: Option<i64>,
202    /// Configured tolerance, interpreted per [`RegressionToleranceKind`].
203    /// Absent when status is `skipped`.
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub tolerance: Option<f64>,
206    /// Interpretation of the tolerance value.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub tolerance_kind: Option<RegressionToleranceKind>,
209    /// Whether the regression exceeded the tolerance.
210    pub exceeded: bool,
211    /// Only present when status is `skipped`.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub reason: Option<String>,
214}
215
216/// Status of a regression-check pass.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
218#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
219#[serde(rename_all = "lowercase")]
220pub enum RegressionStatus {
221    /// Issue count within tolerance.
222    Pass,
223    /// Issue count exceeded tolerance.
224    Exceeded,
225    /// Regression check did not run (missing baseline, etc.).
226    Skipped,
227}
228
229/// Interpretation of [`RegressionResult::tolerance`].
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
231#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
232#[serde(rename_all = "lowercase")]
233pub enum RegressionToleranceKind {
234    /// Tolerance is interpreted as an absolute issue-count delta.
235    Absolute,
236    /// Tolerance is interpreted as a percentage of the baseline total.
237    Percentage,
238}
239
240/// Metric and rule definitions emitted under `_meta` when `--explain` is
241/// passed (always present in MCP responses). Helps AI agents and CI systems
242/// interpret metric values without re-reading the docs site.
243#[derive(Debug, Clone, Default, Serialize)]
244#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
245pub struct Meta {
246    /// URL to the documentation page for this command.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub docs: Option<String>,
249    /// Local telemetry correlation metadata for agent follow-up runs.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub telemetry: Option<TelemetryMeta>,
252    /// Per-field definitions for envelope fields and action payload fields.
253    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
254    pub field_definitions: BTreeMap<String, String>,
255    /// Per-metric definitions: name, description, range, interpretation.
256    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
257    pub metrics: BTreeMap<String, MetaMetric>,
258    /// Per-rule definitions for check command output.
259    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
260    pub rules: BTreeMap<String, MetaRule>,
261}
262
263/// Privacy-safe local run metadata emitted for JSON consumers.
264#[derive(Debug, Clone, Default, Serialize)]
265#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
266pub struct TelemetryMeta {
267    /// Ephemeral local token that may be passed to the hidden `--parent-run`
268    /// flag on a later command. It is not derived from repository, path, user,
269    /// machine, project, or cloud data.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub analysis_run_id: Option<String>,
272}
273
274/// Single-metric definition inside [`Meta::metrics`].
275#[derive(Debug, Clone, Default, Serialize)]
276#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
277pub struct MetaMetric {
278    /// Human-readable metric name.
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub name: Option<String>,
281    /// What this metric measures and how it is computed.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub description: Option<String>,
284    /// Valid value range (e.g., `"[0, 100]"`).
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub range: Option<String>,
287    /// How to read the value (e.g., `"lower is better"`).
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub interpretation: Option<String>,
290}
291
292/// Single-rule definition inside [`Meta::rules`].
293#[derive(Debug, Clone, Default, Serialize)]
294#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
295pub struct MetaRule {
296    /// Human-readable rule name.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub name: Option<String>,
299    /// What this rule detects.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub description: Option<String>,
302    /// URL to the rule documentation.
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub docs: Option<String>,
305}