Skip to main content

fallow_config/config/
mod.rs

1mod boundaries;
2mod duplicates_config;
3mod finding_ignore;
4mod flags;
5mod format;
6pub mod glob_validation;
7mod health;
8mod parsing;
9mod resolution;
10mod resolve;
11mod rules;
12mod similar_code;
13mod used_class_members;
14
15#[expect(
16    clippy::redundant_pub_crate,
17    reason = "this module is glob re-exported from lib.rs, so `pub` would leak the helper into the public API; pub(crate) keeps it internal to the crate"
18)]
19pub(crate) use boundaries::wildcard_placement_error;
20pub use boundaries::{
21    AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
22    BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
23    LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
24    ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
25    ZoneReferenceKind, ZoneValidationError,
26};
27pub use duplicates_config::{
28    DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
29};
30pub use finding_ignore::FindingIgnoreMatcher;
31pub use flags::{FlagsConfig, SdkPattern};
32pub use format::OutputFormat;
33pub use health::{EmailMode, HealthConfig, HealthThresholdOverride, OwnershipConfig};
34pub use parsing::{CONFIG_FILE_NAMES, ConfigLoadOptions};
35pub use resolution::{
36    AnalysisSnapshot, CompiledIgnoreCatalogReferenceRule, CompiledIgnoreDependencyOverrideRule,
37    CompiledIgnoreExportRule, ConfigOverride, DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_FILE_SIZE_BYTES,
38    DEFAULT_MAX_FILE_SIZE_MB, IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule,
39    IgnoreExportRule, ResolvedConfig, ResolvedOverride, cache_config_hash,
40    resolve_max_file_size_bytes,
41};
42pub use resolve::ResolveConfig;
43pub use rules::{
44    KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, Severity, closest_known_rule_name,
45    default_severity_for_kind, is_opt_in_kind,
46};
47pub use similar_code::SimilarCodeConfig;
48pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
49
50use schemars::JsonSchema;
51use serde::{Deserialize, Deserializer, Serialize};
52use std::ops::Not;
53use std::path::PathBuf;
54
55use crate::external_plugin::ExternalPluginDef;
56use crate::workspace::WorkspaceConfig;
57
58/// Value of the `ignoreExportsUsedInFile` config key: whether an export
59/// referenced elsewhere in its own file is suppressed from `unused-export`.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
61#[serde(untagged, rename_all = "camelCase")]
62pub enum IgnoreExportsUsedInFileConfig {
63    /// Blanket toggle: `true` suppresses any export with a same-file use,
64    /// regardless of kind. The default is `false`.
65    Bool(bool),
66    /// Knip-parity object form restricting the suppression to type-only
67    /// exports.
68    ByKind(IgnoreExportsUsedInFileByKind),
69}
70
71impl Default for IgnoreExportsUsedInFileConfig {
72    fn default() -> Self {
73        Self::Bool(false)
74    }
75}
76
77impl From<bool> for IgnoreExportsUsedInFileConfig {
78    fn from(value: bool) -> Self {
79        Self::Bool(value)
80    }
81}
82
83impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
84    fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
85        Self::ByKind(value)
86    }
87}
88
89impl IgnoreExportsUsedInFileConfig {
90    /// Whether any form of the same-file-use suppression is active (the bool
91    /// form is `true`, or either by-kind field is set).
92    #[must_use]
93    pub const fn is_enabled(self) -> bool {
94        match self {
95            Self::Bool(value) => value,
96            Self::ByKind(kind) => kind.type_ || kind.interface,
97        }
98    }
99
100    /// Whether an export with a same-file use should be suppressed, given
101    /// whether fallow classified it as type-only. The bool form suppresses
102    /// regardless of kind; the by-kind form suppresses type-only exports only.
103    #[must_use]
104    pub const fn suppresses(self, is_type_only: bool) -> bool {
105        match self {
106            Self::Bool(value) => value,
107            Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
108        }
109    }
110}
111
112/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
113/// restricting the same-file-use suppression to type-only exports.
114#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
115#[serde(rename_all = "camelCase")]
116pub struct IgnoreExportsUsedInFileByKind {
117    /// When `true`, enables the same-file-use suppression for type-only exports (serialized as `type`; part of the object form of `ignoreExportsUsedInFile`). Because fallow groups type aliases and interfaces under one issue kind, setting either `type` or `interface` enables the identical type-only suppression, applied only to exports fallow classifies as type-only.
118    #[serde(default, rename = "type")]
119    pub type_: bool,
120    /// When `true`, enables the same-file-use suppression for type-only exports (part of the object form of `ignoreExportsUsedInFile`). Fallow does not distinguish interfaces from type aliases in this issue kind, so `interface` behaves identically to `type`: setting either one turns on the type-only same-file suppression.
121    #[serde(default)]
122    pub interface: bool,
123}
124
125/// Options for the `unused-component-props` rule.
126///
127/// Lets a project exempt component props whose local destructure binding name
128/// matches a regex from `unused-component-props`, honoring the
129/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
130/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
131/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
132/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
133/// behavior unchanged.
134#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
135#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
136pub struct UnusedComponentPropsConfig {
137    /// Regex matched against each declared prop's LOCAL destructure binding name
138    /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
139    /// to the public prop name when there is no alias. A prop whose local name
140    /// matches is treated as intentionally unused and never reported as
141    /// `unused-component-props`. Matching is unanchored (substring), like
142    /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
143    /// underscore. Compiled and validated at config load (an invalid regex fails
144    /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub ignore_pattern: Option<String>,
147}
148
149impl UnusedComponentPropsConfig {
150    /// True when no option is set, so serialization can omit the section.
151    #[must_use]
152    pub fn is_default(&self) -> bool {
153        self.ignore_pattern.is_none()
154    }
155}
156
157/// The `fix` config section: settings for `fallow fix` apply behavior.
158#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
159#[serde(rename_all = "camelCase")]
160pub struct FixConfig {
161    /// Groups `fallow fix` settings for pnpm workspace catalog cleanup. Its only key, `deletePrecedingComments` (`auto` default, `always`, `never`), controls whether a comment block directly above a removed unused `pnpm-workspace.yaml` catalog entry is deleted with the entry.
162    #[serde(default)]
163    pub catalog: CatalogFixConfig,
164}
165
166/// The `fix.catalog` section: how `fallow fix` cleans up unused
167/// `pnpm-workspace.yaml` catalog entries.
168#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
169#[serde(rename_all = "camelCase")]
170pub struct CatalogFixConfig {
171    /// Controls whether comment lines immediately above an unused `pnpm-workspace.yaml` catalog entry are removed when `fallow fix` deletes that entry: `auto` (default: delete only when the comment block is preceded by a blank line or sits directly under the parent catalog header, and never when it is a section banner like `# ====`), `always` (always remove the adjacent comment block), or `never` (leave all preceding comments). A `fallow-keep` marker anywhere in the block always preserves it regardless of this setting. Set `never` for teams that keep hand-authored notes above catalog pins.
172    #[serde(default)]
173    pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
174}
175
176/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
177/// lines directly above a catalog entry that `fallow fix` removes. A
178/// `fallow-keep` marker in the block always preserves it regardless of policy.
179#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
180#[serde(rename_all = "lowercase")]
181pub enum CatalogPrecedingCommentPolicy {
182    /// Delete the adjacent comment block only when heuristics attribute it to
183    /// the entry (preceded by a blank line or directly under the catalog
184    /// header) and it is not a section banner. The default.
185    #[default]
186    Auto,
187    /// Always delete the adjacent comment block with the entry.
188    Always,
189    /// Never delete preceding comments.
190    Never,
191}
192
193/// Completeness policy for opt-in TypeScript semantic analysis.
194#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
195#[serde(rename_all = "kebab-case")]
196pub enum TypeAwareRequire {
197    /// Keep conservative findings and report semantic gaps without failing.
198    #[default]
199    BestEffort,
200    /// Fail the quality gate when any requested semantic query is incomplete.
201    Complete,
202}
203
204impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
205    fn from(value: TypeAwareRequire) -> Self {
206        match value {
207            TypeAwareRequire::BestEffort => Self::BestEffort,
208            TypeAwareRequire::Complete => Self::Complete,
209        }
210    }
211}
212
213/// Shared opt-in configuration for TypeScript semantic analysis.
214#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
215#[serde(deny_unknown_fields, rename_all = "camelCase")]
216pub struct TypeAwareConfig {
217    /// Enable the optional TypeScript semantic pass. Disabled by default.
218    #[serde(default)]
219    pub enabled: bool,
220    /// TypeScript project config paths, resolved relative to the project root.
221    #[serde(default, skip_serializing_if = "Vec::is_empty")]
222    pub projects: Vec<String>,
223    /// Decide whether partial semantic analysis is advisory or gating.
224    #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
225    pub require: TypeAwareRequire,
226}
227
228#[expect(
229    clippy::trivially_copy_pass_by_ref,
230    reason = "serde skip_serializing_if callbacks receive field values by reference"
231)]
232fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
233    matches!(value, TypeAwareRequire::BestEffort)
234}
235
236impl TypeAwareConfig {
237    /// True when the section equals its default (disabled, no projects,
238    /// best-effort), so serialization can omit it.
239    #[must_use]
240    pub fn is_default(&self) -> bool {
241        !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
242    }
243}
244
245/// The user-facing fallow configuration as authored in `.fallowrc.json` /
246/// `.fallowrc.jsonc` / `fallow.toml` (or the `fallow` key of `package.json`).
247///
248/// Every field documents its serialized meaning, default, and precedence
249/// against CLI flags and environment variables where they exist.
250/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
251/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
252/// Unknown keys are rejected at load so typos fail loud.
253#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
254#[serde(deny_unknown_fields, rename_all = "camelCase")]
255// Both `.fallowrc.json` and `.fallowrc.jsonc` are read with the JSONC dialect
256// from `crate::jsonc::parse_options`, so the schema declares the same dialect.
257// JSON language service clients (VS Code, Zed) read these two keywords off the
258// root object and otherwise flag syntax the loader accepts. They are
259// annotations only: nothing in fallow reads them back.
260#[schemars(extend("allowComments" = true, "allowTrailingCommas" = true))]
261pub struct FallowConfig {
262    /// A string pointing at fallow's JSON Schema URL, used only by editors for autocomplete and validation of the config file; it has no effect on analysis and is stripped before serialization (serde skip_serializing, writeOnly in the schema). Set it to `./node_modules/fallow/schema.json` for npm installs (version-aligned, offline, avoids VS Code's untrusted-remote-schema prompt), or `https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json` for non-npm installs; any other value is ignored by fallow.
263    #[serde(rename = "$schema", default, skip_serializing)]
264    pub schema: Option<String>,
265
266    /// The lowest fallow version this config is written for, as `MAJOR.MINOR.PATCH`. An older binary stops with a message naming both versions instead of failing on the first field it does not recognize, so a config committed to a shared repository says which upgrade it needs rather than reading like a typo. Optional and unset by default; set it in the same change that adds a field introduced in a newer version. It gates nothing on its own: an unknown key still fails on a binary at or above this version, because there the key really is a typo.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub minimum_version: Option<String>,
269
270    /// An ordered array of parent config sources to inherit before this file's own keys apply; each entry is a file-relative path, an `npm:<package>` specifier, or an `https://` URL (`http://` is rejected), deep-merged in order so objects merge field-by-field while arrays and scalars in this file replace the parent's, with cycle and depth guards. Set it to share a base config across a monorepo or team; it is consumed at load and stripped before serialization (serde skip_serializing).
271    #[serde(default, skip_serializing)]
272    pub extends: Vec<String>,
273
274    /// An array of project-root-relative glob patterns whose matching files are seeded as manual entry points, on top of the framework and package.json entries fallow discovers automatically, so their transitive imports are not reported as unused. Set it (e.g. `["src/main.ts"]`) when a file is a real runtime root that no plugin or manifest declares; patterns are validated at load and matched against discovered files.
275    #[serde(default)]
276    pub entry: Vec<String>,
277
278    /// An array of project-root-relative glob patterns for files to exclude from analysis entirely; entries are unioned with fallow's built-in defaults (**/node_modules/**, **/dist/**, **/build/**, **/.git/**, **/coverage/**, **/*.min.js, **/*.min.mjs, **/*.min.cjs, **/*.bundle.js), so custom globs add to rather than replace them. Set it (e.g. `["generated/**"]`) to drop generated or vendored trees from every detector; patterns are validated at load.
279    #[serde(default)]
280    pub ignore_patterns: Vec<String>,
281
282    /// An array of project-root-relative glob patterns whose source-owned dead-code findings are hidden after analysis without excluding matching files from discovery, parsing, resolution, or the module graph. Use `/` as the path separator on every platform. Positive patterns select paths to hide; `!`-prefixed patterns keep matching paths reportable, and a negated-only array reports only those exception paths. A finding with multiple source owners is hidden only when every owner matches, so a cycle, duplicate-export group, or unlisted dependency with any reportable location remains visible. Architecture, policy, suppression-hygiene, and framework-correctness findings remain visible even when a referenced path matches, as do manifest-owned findings that no source file owns: unused dependencies, unused dev and optional dependencies, catalog entries, and dependency overrides. Use `ignorePatterns` instead when a generated or vendored file must not be analyzed at all.
283    #[serde(default, skip_serializing_if = "Vec::is_empty")]
284    pub ignore_findings: Vec<String>,
285
286    /// Declares inline external framework plugins as data (array of plugin objects), each with `name` plus optional `enablers` (package names that activate it) or richer `detection` (dependency/file-existence/`all`/`any` checks, taking priority over `enablers`), `entryPoints` (+ `entryPointRole` runtime/support/test), `configPatterns`, `alwaysUsed`, `toolingDependencies`, `usedExports` (`{ pattern, exports }`), and `usedClassMembers`. Set it to keep a custom or in-house framework's entry points, config files, and conventions reachable without a Rust plugin; these definitions are appended to plugins discovered via `plugins`, `.fallow/plugins/`, and root `fallow-plugin-*` files (first occurrence of a name wins), and cannot do AST-based config parsing.
287    #[serde(default)]
288    pub framework: Vec<ExternalPluginDef>,
289
290    /// Monorepo workspace configuration whose sole sub-key patterns (array of globs) adds workspace package roots beyond those discovered from package.json workspaces, pnpm-workspace.yaml, and tsconfig references. Optional and absent by default (discovery uses the manifests alone); set it only when workspaces live in directories the standard manifests do not declare.
291    #[serde(default)]
292    pub workspaces: Option<WorkspaceConfig>,
293
294    /// A list of exact package names excluded from BOTH unused-dependency and unlisted-dependency detection, so a runtime-provided or otherwise-untracked package (e.g. `bun:sqlite`, a peer supplied at deploy time) is never flagged as unused when declared nor as unlisted when imported. Set it for packages fallow cannot observe being used and cannot observe being declared; matching is exact string equality against the package name, not a glob.
295    #[serde(default)]
296    pub ignore_dependencies: Vec<String>,
297
298    /// A list of glob patterns that suppress only `unresolved-import` findings whose raw import specifier matches; it does not change dependency usage accounting or resolver behavior. Patterns match the import string as written (not a filesystem path), so list both `@example/icons` and `@example/icons/**` to cover a bare package and its subpaths; parent-relative generated specifiers like `../generated/**` are valid, and broad values like `**` can hide real missing modules.
299    #[serde(default)]
300    pub ignore_unresolved_imports: Vec<String>,
301
302    /// A list of per-file rules that exempt named exports from `unused-export` and from duplicate-exports grouping for files matching a glob. Each entry is `{ file: <glob>, exports: [<name>, ...] }` where `exports: ["*"]` exempts every export in the file and a name list exempts only those names; built for component-library barrels (shadcn/Radix/bits-ui `index.ts`) that intentionally re-export the same short names across many files.
303    #[serde(default)]
304    pub ignore_exports: Vec<IgnoreExportRule>,
305
306    /// A list of rules that suppress `unresolved-catalog-reference` findings (a workspace `package.json` referencing a `catalog:` or `catalog:<name>` that the catalog does not declare); config-only because `package.json` has no inline-suppression comment surface. Each entry needs a `package` (exact match) plus optional `catalog` (exact catalog-name match) and `consumer` (glob on the consuming package.json path); use it for staged catalog migrations where the catalog edit lands in a separate change.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
309
310    /// A list of rules that suppress `unused-dependency-override` and `misconfigured-dependency-override` findings for pnpm `overrides` entries; config-only, matched against the override's target package. Each entry needs a `package` (exact match) plus an optional `source` to scope the suppression to `"pnpm-workspace.yaml"` or `"package.json"`.
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
313
314    /// Controls whether an export referenced only by another symbol in the same file is treated as used (suppressed from `unused-export`) until it becomes completely unreferenced; references inside an export specifier itself (`export { foo }`, `export default foo`) do not count as same-file uses. Accepts `true`/`false` (default `false`, suppress nothing) or the knip-parity object `{ "type": true, "interface": true }`, which restricts the suppression to type-only exports; fallow groups type aliases and interfaces under one kind, so both object fields behave identically.
315    #[serde(default)]
316    pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
317
318    /// A list of decorator names that no longer grant a class member automatic exemption from `unused-class-member`: a member whose every decorator is in this set is checked normally, while a member carrying any decorator NOT listed here stays skipped (frameworks consume decorated members reflectively). Dotted entries match the full decorator path (`ns.foo`) and bare entries match the leftmost segment (so `"decorators"` collapses every `@decorators.*`); both `"@step"` and `"step"` are accepted (leading `@` stripped), and an unmatched entry emits a one-time warning.
319    #[serde(default, skip_serializing_if = "Vec::is_empty")]
320    pub ignore_decorators: Vec<String>,
321
322    /// A list of class-member names or glob patterns treated as framework-used, so a method a library invokes reflectively (ag-Grid `agInit`/`refresh`, Web Component `connectedCallback`) is not reported as `unused-class-member`; it applies to class members only, not enum members. Each entry is either a plain string/glob (`"agInit"`, `"enter*"`, `"*"`) applied to every class, or a scoped object `{ extends?, implements?, members: [...] }` that applies only when the class matches that heritage clause (a scoped rule requires `extends` or `implements`); patterns matching zero members warn once.
323    #[serde(default)]
324    pub used_class_members: Vec<UsedClassMemberRule>,
325
326    /// Configures clone detection: `enabled` (default true), `mode` (`strict`, `mild` default, `weak`, `semantic`, from least to most identifier/literal blinding; `strict` and `mild` are equivalent under fallow's AST tokenizer, `weak` blinds string literals, `semantic` blinds all identifiers and literals for Type-2 renamed-variable detection), `near` (false, add bounded function-scoped near-miss detection), `minTokens` (50), `minLines` (5), `minOccurrences` (integer >= 2, deserialization fails below 2), `threshold` (max duplication percentage, 0 = no limit), `ignore` globs, `ignoredClones` (reviewed clone keys to hide until their content or occurrence count changes), `ignoreDefaults` (true, merge built-in generated-file ignores), `skipLocal` (only report cross-directory clones), `crossLanguage` (strip TS type annotations to match .ts against .js), `ignoreImports` (true, strip ES import/re-export/top-level require wiring from the token stream), and `normalization` (per-flag `ignoreIdentifiers`/`ignoreStringValues`/`ignoreNumericValues` overrides on top of `mode`). Raise `minOccurrences` to focus on widespread copy-paste, enable `near` for gapped structural clones, or set `mode` to `semantic` to catch renamed-variable exact clones.
327    #[serde(default)]
328    pub duplicates: DuplicatesConfig,
329
330    /// Configures the explicit local `similar-code` candidate workflow:
331    /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
332    /// additional `ignore` globs. Provider identity, setup, executables,
333    /// endpoints, credentials, and consent cannot be set by project config.
334    #[serde(default)]
335    pub similar_code: SimilarCodeConfig,
336
337    /// Sets complexity and health thresholds for `fallow health` (also applied in combined `fallow` and `fallow audit`): `maxCyclomatic` (20), `maxCognitive` (15), `maxCrap` (30.0, findings at or above this are reported), `crapRefactorBand` (5, cyclomatic band below `maxCyclomatic` where a secondary refactor action is added), `maxUnitSize` (max function lines before a large-function finding, 60), `coverage`/`coverageRoot` (Istanbul coverage path and path-prefix strip for accurate CRAP), `ignore` globs (remove files from findings AND the health score), `thresholdOverrides` (per-file/per-function ceilings via `files`/`functions`/`maxCyclomatic`/`maxCognitive`/`maxCrap`/`maxUnitSize`/`reason`), `ownership` (`botPatterns` and `emailMode` for `--ownership`), and `suggestInlineSuppression` (true, emit `suppress-line` action hints in JSON). Raise thresholds to relax which functions are flagged, wire `coverage` for real CRAP scores, or exempt generated/test files via `ignore` (drops them from the score too) or `thresholdOverrides` (keeps them visible under a higher ceiling). The four `max*` thresholds govern findings only and never move `health_score`: its penalties use fixed calibration so grades stay comparable across projects, and `ignore` is the lever that removes files from the score.
338    #[serde(default)]
339    pub health: HealthConfig,
340
341    /// Opts into TypeScript semantic analysis for project-wide symbol use,
342    /// provenance, API surface, symbol impact, and public-signature coupling.
343    /// This does not surface compiler diagnostics or typed lint rules.
344    #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
345    pub type_aware: TypeAwareConfig,
346
347    /// Sets per-issue-type severity, keyed by kebab-case rule id: `error` reports and fails CI (non-zero exit), `warn` reports without failing, `off` disables detection and reporting entirely (e.g. `{ "unused-files": "error", "unused-exports": "warn", "private-type-leaks": "off" }`). Set a rule `off` to silence it, `warn` to demote below CI gating, or `error` to promote a warn/off-default rule to gating; most rules default to `error`, dev/optional-dependency and component/store/inject/CSS/catalog rules default to `warn`, and opt-in rules (`private-type-leaks`, `deprecated-exports-in-use`, `security-*`, `prop-drilling`, `thin-wrapper`, `duplicate-prop-shape`, `coverage-gaps`, `feature-flags`, `require-suppression-reason`) default to `off`. Singular aliases (`unused-file`) and `warning`/`none` severity spellings are accepted.
348    #[serde(default)]
349    pub rules: RulesConfig,
350
351    #[serde(
352        default,
353        skip_serializing_if = "UnusedComponentPropsConfig::is_default"
354    )]
355    /// Options for the `unused-component-props` rule, currently only `ignorePattern`: a regex matched against each declared prop's local destructure binding name (falling back to the public prop name when unaliased) to exempt intentionally-unused props such as the leading-underscore convention. Set `{ "ignorePattern": "^_" }` to skip props like `_stage`; matching is unanchored (substring, like ESLint's `RegExp.test`) so anchor with `^`, the pattern is validated at config load (invalid regex fails load), and it applies to Vue, Svelte, Astro, and React/Preact props (unset leaves the rule unchanged).
356    pub unused_component_props: UnusedComponentPropsConfig,
357
358    /// Configures architecture boundary enforcement: which source directories belong to which named zone and which zones may import which others, reported as boundary-violation, boundary-coverage-violation, and boundary-call-violation findings (severity via rules.boundary-violation, default error). Set to enforce a layered/module architecture; the object holds `preset` (one of layered, hexagonal, feature-sliced, bulletproof, whose default zones/rules are merged in with the user-declared zones/rules taking precedence), `zones` (each with `name`, `patterns`, `autoDiscover`, optional `root`), `rules` (each with `from`, `allow`, `allowTypeOnly` target-zone lists), `coverage` (`requireAllFiles` plus `allowUnmatched` globs for files matching no zone), and `calls` (a `forbidden` list of `{from, callee}` banned-call rules per zone).
359    #[serde(default)]
360    pub boundaries: BoundaryConfig,
361
362    /// Configures feature-flag detection: `sdkPatterns` (custom flag-evaluating call signatures, each `{ function, nameArg (zero-based arg index of the flag name, default 0), provider? }`, merged with built-ins for LaunchDarkly, Statsig, Unleash, GrowthBook, Split, PostHog, Vercel Flags, ConfigCat, Flagsmith, Optimizely, and Eppo), `envPrefixes` (env-var prefixes marking `process.env.*` accesses as flags, merged with built-ins), and `configObjectHeuristics` (default false; when true, property accesses on objects whose name contains `feature`/`flag`/`toggle` are reported as low-confidence flags). Set `sdkPatterns`/`envPrefixes` to teach fallow a proprietary flag SDK or naming convention, or enable `configObjectHeuristics` for projects that read flags off config objects (higher false-positive rate). Feature-flag findings surface only when the `feature-flags` rule is enabled (default `off`).
363    #[serde(default)]
364    pub flags: FlagsConfig,
365
366    /// Scopes the opt-in `fallow security` catalogue: which candidate categories run and which extra local identifiers count as HTTP request objects. Set when tuning security-candidate detection; the object holds `categories` (an object with `include` and/or `exclude` string arrays of catalogue category ids, where `include` restricts to a whitelist and `exclude` removes from the admitted set, both unset admits all ordinary categories) and `requestReceivers` (a string array of project-local names that extend, not replace, the built-in `*.query`/`*.params`/`*.body` source-receiver allowlist). The `hardcoded-secret` and `secret-to-network` categories are include-required: they fire only when explicitly listed in `categories.include`, even when no include list is otherwise set. The valid category ids are enumerated (with title, CWE, and include-required flag) in the `security_categories` block of `fallow schema`, and also listed by `fallow security --help`; they are not in this config-schema.
367    #[serde(default)]
368    pub security: SecurityConfig,
369
370    /// Configures `fallow fix` behavior. Currently holds one nested section, `catalog` (a `CatalogFixConfig`), whose only key `deletePrecedingComments` (`auto` default, `always`, `never`) governs whether comment lines directly above a removed unused `pnpm-workspace.yaml` catalog entry are deleted with it.
371    #[serde(default)]
372    pub fix: FixConfig,
373
374    /// Configures the module resolver. Its one key `conditions` is a list of additional package.json `exports`/`imports` condition names to honor, matched at higher priority than fallow's built-ins (`development`, `import`, `require`, `default`, `types`, `node`, plus `react-native`/`browser` when the React Native or Expo plugin is active). Set it when a package's `exports` map has custom branches (e.g. `worker`, `deno`, `edge`) that fallow should follow instead of the default branch.
375    #[serde(default)]
376    pub resolve: ResolveConfig,
377
378    /// Enables production mode, which excludes test/spec/story/dev files from discovery and forces `unused-dev-dependencies` and `unused-optional-dependencies` to `off`. Accepts a boolean (default false) applied to all analyses, or a per-analysis object `{ deadCode?, health?, dupes? }` (each boolean, default false) that scopes production mode to individual analyses in combined `fallow` and `fallow audit`. Set it to analyze only shipped code; the `--production`/`--no-production` and `--production-{dead-code,health,dupes}` CLI flags and `FALLOW_PRODUCTION*` env vars override this value (CLI flags win, then per-analysis env, then global env, then config).
379    #[serde(default)]
380    pub production: ProductionConfig,
381
382    /// List of paths (relative to the project root, must resolve within it) to external plugin definition files or directories in JSONC/JSON/TOML, loaded in addition to the auto-discovered `.fallow/plugins/` directory and root `fallow-plugin-*` files. Set it to load plugin definitions kept outside those default locations; a path resolving outside the project root is skipped with a `tracing::warn`, and paths listed here are searched before the auto-discovered locations (first occurrence of a plugin name wins).
383    #[serde(default)]
384    pub plugins: Vec<String>,
385
386    /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
387    /// project root. Each pack declares `banned-call`, `banned-import`, or
388    /// `banned-effect` rules that report as `policy-violation` findings. Packs
389    /// are pure data: no project code is executed. Invalid or missing packs
390    /// fail config load.
391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
392    pub rule_packs: Vec<String>,
393
394    /// An array of project-root-relative glob patterns for files loaded at runtime by a mechanism the static graph cannot see (dynamic path resolution, config-driven loading); matching files are seeded as entry points so they and their imports stay reachable. Empty by default; set it (e.g. `["plugins/**/*.ts", "locales/**/*.json"]`) for plugin or locale trees pulled in dynamically.
395    #[serde(default)]
396    pub dynamically_loaded: Vec<String>,
397
398    /// An ordered list of per-file rule-severity overrides: each entry re-severities specific analysis rules for files its globs match, layered on top of the top-level `rules` defaults. Set to relax or tighten rules for a subset of paths (e.g. downgrade unused-exports to warn under a generated directory); each entry has `files` (glob-pattern array) and `rules` (a partial per-rule severity map of error/warn/off). Entries apply in list order and a file matched by several entries takes every matching entry's overrides (later entries win on conflict); inter-file rules (duplicate-exports, circular-dependencies, re-export-cycle) have no effect in an override (fallow warns during analysis and points to the right mechanism: top-level `ignoreExports` for duplicate-exports, a file-level `// fallow-ignore-file` comment for the others).
399    #[serde(default)]
400    pub overrides: Vec<ConfigOverride>,
401
402    /// A project-root-relative path to a CODEOWNERS file, used by fallow health --hotspots --ownership to attribute declared owners and compute unowned/drifting ownership state; setting it overrides the default probe order (CODEOWNERS, .github/CODEOWNERS, .gitlab/CODEOWNERS, docs/CODEOWNERS). String, defaults to null (auto-probe the standard locations); set it only when the CODEOWNERS file lives at a non-standard location.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub codeowners: Option<String>,
405
406    /// An array of internal workspace package names (or globs matched against workspace package names) whose public API is intentionally consumed outside the analyzed graph; their entry points and re-export surface become reachability roots, so their exported files, exports, and class members are not reported as unused. Set it (e.g. `["@myorg/shared-lib", "@myorg/*"]`) for library packages in a monorepo that ship an API to external consumers; only meaningful when workspaces are present (an empty list or no workspaces is a no-op).
407    #[serde(default)]
408    pub public_packages: Vec<String>,
409
410    /// Holds a saved issue-count baseline that the `--fail-on-regression` gate compares the current run against, failing only when counts grow beyond tolerance relative to the baseline. Usually written by `--save-baseline` rather than hand-authored; the object has a single `baseline` sub-key holding per-issue-type counts (total_issues plus per-kind fields like unused_exports, boundary_violations, policy_violations, each defaulting to 0). Absent means no baseline is embedded in config.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub regression: Option<RegressionConfig>,
413
414    /// Sets in-repo defaults for `fallow audit` (the changed-files quality gate) so CLI flags need not repeat per run. Set to pin audit behavior; the object holds `gate` (`new-only` or `all`, which findings drive the verdict), `css`/`cssDeep` (booleans toggling styling analysis and the project-wide CSS reachability pass), `deadCodeBaseline`/`healthBaseline`/`dupesBaseline` (per-sub-analysis baseline file paths), and `cacheMaxAgeDays` (GC window in days for the reusable base-snapshot worktree cache). The matching CLI flag overrides each field.
415    #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
416    pub audit: AuditConfig,
417
418    /// When true, restricts this config's extends entries to file-relative paths that resolve inside the config file's own directory; any https:// URL, npm: package, or relative path escaping that directory is rejected at load with a hard error. Boolean, defaults to false (URL, npm, and any-relative extends are permitted); set it to true to harden a config against pulling in remote or out-of-tree bases.
419    #[serde(default)]
420    pub sealed: bool,
421
422    /// When true, exports of entry-point files are subject to unused-export detection instead of being auto-credited as used, so a typo'd or stray export in a framework route or package entry (e.g. meatdata for metadata) is flagged; plugin used_exports allowlists are still honored. Boolean, defaults to false; the CLI flag --include-entry-exports applies the same behavior for one run.
423    #[serde(default)]
424    pub include_entry_exports: bool,
425
426    /// When true, drops Nuxt convention-based entry-pattern fallbacks so genuinely-unreferenced convention files surface as unused-file. Component fallbacks are kept when nuxt.config customizes components: in a way fallow does not model, and composable/util fallbacks are kept when it customizes imports:; a config that scans no more than the Nuxt defaults (components: false, components: [], components: { dirs: [] }, components: true, imports: { scan: false }, imports: {}, imports: { dirs: [] }) is treated like the default and its fallbacks are dropped; imports: { autoImport: false } on its own is not, because it only switches the injection off while the same directories stay registered behind #imports. A nuxt.config that carries any top-level key fallow cannot read statically, a computed key, an accessor, or a spread such as { ...base, devtools: {} }, keeps both surfaces' fallbacks for that root, because the spread may hold the keys that decide. Only top-level keys count when the config object is readable: a nested key such as a routeRules path ending in components does not keep a fallback. Nested components or imports keys in $production, $development, $test or `$env.<name>`, and components or imports hooks (a components:* key or a nested components object in hooks, also inside those overrides), count as that surface's key; such an override object or hooks object that fallow cannot read statically falls back to a text match for the keys. Each root is classified on its own config plus the configs of its local layers, so one custom nuxt.config in a monorepo does not keep every other workspace's fallbacks. A local layer is a directory named in extends, or a `layers/<name>` directory, that holds a nuxt.config; its convention files are entry points with the flag off and auto-import sources with it on, and `#layers/<name>/` resolves to it by its $meta.name (a `layers/<name>` directory without one uses its directory name). A remote or package layer is only a dependency reference. Component names follow Nuxt: a component under components/global or components/islands is named after its own directory (components/global/Foo.vue is `<Foo>`), and .client, .server, .global and .island suffixes are stripped. A name imported or re-exported by hand from #components or #imports credits its convention file just like a template tag or a bare call; a namespace import names nothing and credits nothing. Boolean, defaults to false; set it for a Nuxt project that has explicitly configured its auto-import directories. Synthesis of auto-import graph edges (resolving `<Card />` or `useUserStore()` to their convention files) happens regardless of this flag.
427    #[serde(default)]
428    pub auto_imports: bool,
429
430    /// When true, the run fails with exit code 1 if fallow could not parse a source file cleanly (a `source-parse-degraded` entry in `workspace_diagnostics[]`), and the `parse-error` entry of `gate_outcomes` names each such file. Boolean, defaults to false, so a file the parser rejects only warns. Applies to `fallow dead-code`, `fallow health`, `fallow audit` and the bare `fallow` run; the CLI flag `--fail-on-parse-error` arms the same gate for one run. Older fallow versions reject this key as unknown, so pair it with `minimumVersion` set to the release that added it.
431    #[serde(default)]
432    pub fail_on_parse_error: bool,
433
434    /// Overrides the location and size ceiling of fallow's persistent extraction cache (default `.fallow/cache.bin` under the project root). Set to relocate the cache or cap its footprint; the object holds `dir` (cache directory, relative paths resolve from the project root) and `maxSizeMb` (extraction-cache size limit in megabytes). The `FALLOW_CACHE_MAX_SIZE` environment variable overrides `maxSizeMb`.
435    #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
436    pub cache: CacheConfig,
437}
438
439/// Scopes `fallow security` catalogue behavior. An absent category block admits
440/// every catalogue category. `hardcoded-secret` is include-required and only
441/// runs when explicitly listed in `security.categories.include`.
442#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
443#[serde(deny_unknown_fields, rename_all = "camelCase")]
444pub struct SecurityConfig {
445    /// Include/exclude filter over category ids (e.g. `dangerous-html`).
446    #[serde(default, skip_serializing_if = "Option::is_none")]
447    pub categories: Option<SecurityCategories>,
448    /// Additional project-local names for HTTP request objects. These names
449    /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
450    /// `*.body` source patterns. They do not replace the built-ins and do not
451    /// gate `*.searchParams`, which intentionally stays ungated.
452    #[serde(default, skip_serializing_if = "Vec::is_empty")]
453    pub request_receivers: Vec<String>,
454}
455
456impl SecurityConfig {
457    /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
458    /// in first-seen order, with empty entries dropped; the form the matcher
459    /// compares receiver names against (matching is case-insensitive).
460    #[must_use]
461    pub fn normalized_request_receivers(&self) -> Vec<String> {
462        let mut receivers = Vec::new();
463        for receiver in &self.request_receivers {
464            let normalized = receiver.trim().to_ascii_lowercase();
465            if !normalized.is_empty() && !receivers.contains(&normalized) {
466                receivers.push(normalized);
467            }
468        }
469        receivers
470    }
471
472    /// False when any configured receiver is empty or whitespace-only, which
473    /// config validation reports as an error instead of silently dropping it.
474    #[must_use]
475    pub fn request_receivers_are_valid(&self) -> bool {
476        self.request_receivers
477            .iter()
478            .all(|receiver| !receiver.trim().is_empty())
479    }
480}
481
482/// Include/exclude lists scoping the active security categories. When `include`
483/// is set, only those categories are active; `exclude` removes categories from
484/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
485/// still requires explicit inclusion.
486#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
487#[serde(deny_unknown_fields, rename_all = "camelCase")]
488pub struct SecurityCategories {
489    /// Catalogue category ids to admit. When set, all others are excluded.
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub include: Option<Vec<String>>,
492    /// Catalogue category ids to remove from the admitted set.
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub exclude: Option<Vec<String>>,
495}
496
497/// The `cache` config section: location and size ceiling of fallow's
498/// persistent caches (default directory `<root>/.fallow`).
499#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
500#[serde(deny_unknown_fields, rename_all = "camelCase")]
501pub struct CacheConfig {
502    /// Directory for fallow's persistent analysis cache. Relative paths resolve
503    /// from the project root.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub dir: Option<PathBuf>,
506    /// Maximum size of the persistent extraction cache, in megabytes.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub max_size_mb: Option<u32>,
509}
510
511impl CacheConfig {
512    /// True when neither field is set, so serialization can omit the section.
513    #[must_use]
514    pub fn is_default(&self) -> bool {
515        self.dir.is_none() && self.max_size_mb.is_none()
516    }
517}
518
519/// The analysis families production mode can be scoped to independently via
520/// the object form of the `production` config key.
521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
522pub enum ProductionAnalysis {
523    /// Unused files/exports/dependencies detection.
524    DeadCode,
525    /// Complexity and health scoring.
526    Health,
527    /// Clone detection.
528    Dupes,
529}
530
531/// Value of the `production` config key: excludes test/spec/story/dev files
532/// from discovery, either globally or per analysis family.
533#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
534#[serde(untagged)]
535pub enum ProductionConfig {
536    /// Boolean form applying to every analysis. The default is `false`.
537    Global(bool),
538    /// Object form (`{ deadCode?, health?, dupes? }`) scoping production mode
539    /// per analysis family.
540    PerAnalysis(PerAnalysisProductionConfig),
541}
542
543impl<'de> Deserialize<'de> for ProductionConfig {
544    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
545    where
546        D: Deserializer<'de>,
547    {
548        struct ProductionConfigVisitor;
549
550        impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
551            type Value = ProductionConfig;
552
553            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
554                formatter.write_str("a boolean or per-analysis production config object")
555            }
556
557            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
558            where
559                E: serde::de::Error,
560            {
561                Ok(ProductionConfig::Global(value))
562            }
563
564            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
565            where
566                A: serde::de::MapAccess<'de>,
567            {
568                PerAnalysisProductionConfig::deserialize(
569                    serde::de::value::MapAccessDeserializer::new(map),
570                )
571                .map(ProductionConfig::PerAnalysis)
572            }
573        }
574
575        deserializer.deserialize_any(ProductionConfigVisitor)
576    }
577}
578
579impl Default for ProductionConfig {
580    fn default() -> Self {
581        Self::Global(false)
582    }
583}
584
585impl From<bool> for ProductionConfig {
586    fn from(value: bool) -> Self {
587        Self::Global(value)
588    }
589}
590
591impl Not for ProductionConfig {
592    type Output = bool;
593
594    fn not(self) -> Self::Output {
595        !self.any_enabled()
596    }
597}
598
599impl ProductionConfig {
600    /// Whether production mode applies to `analysis` under this config.
601    #[must_use]
602    pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
603        match self {
604            Self::Global(value) => value,
605            Self::PerAnalysis(config) => match analysis {
606                ProductionAnalysis::DeadCode => config.dead_code,
607                ProductionAnalysis::Health => config.health,
608                ProductionAnalysis::Dupes => config.dupes,
609            },
610        }
611    }
612
613    /// The boolean form's value; `false` for the per-analysis form, which has
614    /// no global toggle.
615    #[must_use]
616    pub const fn global(self) -> bool {
617        match self {
618            Self::Global(value) => value,
619            Self::PerAnalysis(_) => false,
620        }
621    }
622
623    /// Whether production mode is enabled for at least one analysis family.
624    #[must_use]
625    pub const fn any_enabled(self) -> bool {
626        match self {
627            Self::Global(value) => value,
628            Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
629        }
630    }
631}
632
633/// Object form of the `production` config key, scoping production mode to
634/// individual analysis families in combined `fallow` and `fallow audit`.
635#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
636#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
637pub struct PerAnalysisProductionConfig {
638    /// When `production` is a per-analysis object, enables production mode for dead-code analysis only (boolean, default false): unused-files/exports/dependencies detection excludes test/spec/story/dev files and forces `unused-dev-dependencies`/`unused-optional-dependencies` to `off`, while health and dupes stay on the full tree. Set it to scope production analysis to dead code independently.
639    pub dead_code: bool,
640    /// When `production` is a per-analysis object, enables production mode for the health/complexity analysis only (boolean, default false), so `fallow health` in combined `fallow` and `fallow audit` scores only shipped code (test/spec/story/dev files excluded) while dead-code and dupes stay on the full tree. Set it to scope production analysis to health independently.
641    pub health: bool,
642    /// When `production` is a per-analysis object, enables production mode for duplication analysis only (boolean, default false), so clone detection runs on shipped code only (test/spec/story/dev files excluded) while dead-code and health stay on the full tree. Set it to scope production analysis to dupes independently.
643    pub dupes: bool,
644}
645
646/// The `audit` config section: in-repo defaults for `fallow audit`, each
647/// overridable by its matching CLI flag.
648#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
649#[serde(rename_all = "camelCase")]
650pub struct AuditConfig {
651    /// Selects which findings affect the `fallow audit` verdict: `new-only` (default) fails only on findings introduced by the current changeset (running a base-snapshot attribution pass), while `all` fails on every finding in changed files and skips that pass. Set to `all` to gate the full backlog in changed files; the `--gate` CLI flag overrides this.
652    #[serde(default, skip_serializing_if = "AuditGate::is_default")]
653    pub gate: AuditGate,
654
655    /// Toggles styling analytics (CSS and CSS-in-JS) in the `fallow audit` health sub-pass; these findings are descriptive and verdict-neutral by default (they change the exit code only when a css-* rule is set to error). Defaults to on when unset; set `false` to skip styling analysis. The `--no-css` CLI flag forces it off regardless.
656    #[serde(default, skip_serializing_if = "Option::is_none")]
657    pub css: Option<bool>,
658
659    /// Toggles the project-wide CSS reachability pass in `fallow audit`, whose cross-file findings are narrowed back to changed anchors. Defaults to on when unset and runs only when css analytics are enabled; set `false` to keep local styling analytics but skip the whole-project scan. The `--css-deep` flag re-enables it and `--no-css-deep` forces it off.
660    #[serde(default, skip_serializing_if = "Option::is_none")]
661    pub css_deep: Option<bool>,
662
663    /// Path to a saved dead-code baseline file (produced by `fallow dead-code --save-baseline`) that the audit's dead-code sub-analysis compares against, suppressing pre-existing dead-code issues. The `--dead-code-baseline` CLI flag overrides it and both resolve relative to the project root; each sub-analysis uses a distinct baseline format, so this is separate from `healthBaseline` and `dupesBaseline`.
664    #[serde(default, skip_serializing_if = "Option::is_none")]
665    pub dead_code_baseline: Option<String>,
666
667    /// Path to a saved health/complexity baseline file (produced by `fallow health --save-baseline`) that the audit's health sub-analysis compares against, suppressing pre-existing complexity/health findings. The `--health-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and dupes baselines.
668    #[serde(default, skip_serializing_if = "Option::is_none")]
669    pub health_baseline: Option<String>,
670
671    /// Path to a saved duplication baseline file (produced by `fallow dupes --save-baseline`) that the audit's duplication sub-analysis compares clone groups against, suppressing pre-existing duplicate clones. The `--dupes-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and health baselines.
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub dupes_baseline: Option<String>,
674
675    /// Garbage-collection threshold, in whole days, for the persistent reusable base-snapshot worktree caches `fallow audit` creates: entries older than this window are swept on each audit run. Set to control cache accumulation; `0` disables the sweep and unset defaults to 30 days. Each sweep also reclaims abandoned entries minted under other repo identities (deleted or moved repos, other git worktrees) once they age past this repo's threshold; entries whose recorded owner root still exists are skipped and stay governed by that repo's own setting. The `FALLOW_AUDIT_CACHE_MAX_AGE_DAYS` environment variable overrides this field.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub cache_max_age_days: Option<u32>,
678
679    /// Overrides the top-level `typeAware.enabled` opt-in for `fallow audit` only: set `false` to keep persistent type-aware analysis on for cleanup commands (`dead-code`, `fix`, `health`) while the audit gate stays syntactic, or `true` to enable it for audit alone. Unset inherits `typeAware.enabled`. The `--type-aware`/`--no-type-aware` CLI flags and the `FALLOW_TYPE_AWARE` environment variable both take precedence over this field.
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub type_aware: Option<bool>,
682}
683
684impl AuditConfig {
685    /// True when every field is unset, so serialization can omit the section.
686    #[must_use]
687    pub fn is_empty(&self) -> bool {
688        self.gate.is_default()
689            && self.css.is_none()
690            && self.css_deep.is_none()
691            && self.dead_code_baseline.is_none()
692            && self.health_baseline.is_none()
693            && self.dupes_baseline.is_none()
694            && self.cache_max_age_days.is_none()
695            && self.type_aware.is_none()
696    }
697}
698
699/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
700#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
701#[serde(rename_all = "kebab-case")]
702pub enum AuditGate {
703    /// Fail only on findings the current changeset introduced, determined by
704    /// a base-snapshot attribution pass. The default.
705    #[default]
706    NewOnly,
707    /// Fail on every finding in changed files, skipping the attribution pass.
708    All,
709}
710
711impl AuditGate {
712    /// True for the default `new-only` gate, so serialization can omit it.
713    #[must_use]
714    pub const fn is_default(&self) -> bool {
715        matches!(self, Self::NewOnly)
716    }
717}
718
719/// The `regression` config section holding the saved issue-count baseline for
720/// the `--fail-on-regression` gate.
721#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
722#[serde(rename_all = "camelCase")]
723pub struct RegressionConfig {
724    /// The saved per-issue-type issue counts that `--fail-on-regression` compares the current run against; the gate fails only when counts grow beyond the configured tolerance. Typically written by `--save-baseline` rather than hand-authored; each field (total_issues plus per-kind counts like unused_exports, boundary_violations, policy_violations) is an integer defaulting to 0 when omitted. Absent means no baseline is embedded.
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub baseline: Option<RegressionBaseline>,
727}
728
729/// Saved per-issue-type counts written by `--save-baseline` and compared by
730/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
731/// so hand-trimmed baselines stay loadable.
732#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
733#[serde(rename_all = "camelCase")]
734pub struct RegressionBaseline {
735    /// Compatibility identity for the analysis that produced these counts.
736    /// Missing values in existing configs are treated as syntactic.
737    #[serde(default)]
738    pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
739    /// Baseline count across all issue types.
740    #[serde(default)]
741    pub total_issues: usize,
742    /// Baseline count of `unused-files` findings.
743    #[serde(default)]
744    pub unused_files: usize,
745    /// Baseline count of `unused-exports` findings.
746    #[serde(default)]
747    pub unused_exports: usize,
748    /// Baseline count of `unused-types` findings.
749    #[serde(default)]
750    pub unused_types: usize,
751    /// Baseline count of `unused-dependencies` findings.
752    #[serde(default)]
753    pub unused_dependencies: usize,
754    /// Baseline count of `unused-dev-dependencies` findings.
755    #[serde(default)]
756    pub unused_dev_dependencies: usize,
757    /// Baseline count of `unused-optional-dependencies` findings.
758    #[serde(default)]
759    pub unused_optional_dependencies: usize,
760    /// Baseline count of `unused-enum-members` findings.
761    #[serde(default)]
762    pub unused_enum_members: usize,
763    /// Baseline count of `unused-class-members` findings.
764    #[serde(default)]
765    pub unused_class_members: usize,
766    /// Baseline count of `unresolved-imports` findings.
767    #[serde(default)]
768    pub unresolved_imports: usize,
769    /// Baseline count of `unlisted-dependencies` findings.
770    #[serde(default)]
771    pub unlisted_dependencies: usize,
772    /// Baseline count of `duplicate-exports` findings.
773    #[serde(default)]
774    pub duplicate_exports: usize,
775    /// Baseline count of `circular-dependencies` findings.
776    #[serde(default)]
777    pub circular_dependencies: usize,
778    /// Baseline count of `re-export-cycle` findings.
779    #[serde(default)]
780    pub re_export_cycles: usize,
781    /// Baseline count of `type-only-dependencies` findings.
782    #[serde(default)]
783    pub type_only_dependencies: usize,
784    /// Baseline count of `test-only-dependencies` findings.
785    #[serde(default)]
786    pub test_only_dependencies: usize,
787    /// Baseline count of `dev-dependencies-in-production` findings.
788    #[serde(default)]
789    pub dev_dependencies_in_production: usize,
790    /// Baseline count of `boundary-violation` findings.
791    #[serde(default)]
792    pub boundary_violations: usize,
793    /// Baseline count of boundary-coverage-violation findings.
794    #[serde(default)]
795    pub boundary_coverage_violations: usize,
796    /// Baseline count of boundary-call-violation findings.
797    #[serde(default)]
798    pub boundary_call_violations: usize,
799    /// Baseline count of `policy-violation` findings.
800    #[serde(default)]
801    pub policy_violations: usize,
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807
808    #[test]
809    fn default_config_has_empty_collections() {
810        let config = FallowConfig::default();
811        assert!(config.schema.is_none());
812        assert!(config.extends.is_empty());
813        assert!(config.entry.is_empty());
814        assert!(config.ignore_patterns.is_empty());
815        assert!(config.ignore_findings.is_empty());
816        assert!(config.framework.is_empty());
817        assert!(config.workspaces.is_none());
818        assert!(config.ignore_dependencies.is_empty());
819        assert!(config.ignore_exports.is_empty());
820        assert!(config.used_class_members.is_empty());
821        assert!(config.plugins.is_empty());
822        assert!(config.dynamically_loaded.is_empty());
823        assert!(config.overrides.is_empty());
824        assert!(config.public_packages.is_empty());
825        assert_eq!(
826            config.fix.catalog.delete_preceding_comments,
827            CatalogPrecedingCommentPolicy::Auto
828        );
829        assert!(!config.production);
830    }
831
832    #[test]
833    fn deserialize_empty_json_object() {
834        let config: FallowConfig = serde_json::from_str("{}").unwrap();
835        assert!(config.entry.is_empty());
836        assert!(!config.production);
837        assert!(!config.type_aware.enabled);
838        assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
839    }
840
841    #[test]
842    fn deserialize_type_aware_config() {
843        let config: FallowConfig = serde_json::from_str(
844            r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
845        )
846        .unwrap();
847
848        assert!(config.type_aware.enabled);
849        assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
850        assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
851    }
852
853    #[test]
854    fn deserialize_type_aware_config_rejects_unknown_fields() {
855        let result = serde_json::from_str::<FallowConfig>(
856            r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
857        );
858        assert!(result.is_err());
859    }
860
861    #[test]
862    fn deserialize_json_with_all_top_level_fields() {
863        let json = r#"{
864            "$schema": "./node_modules/fallow/schema.json",
865            "entry": ["src/main.ts"],
866            "ignorePatterns": ["generated/**"],
867            "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
868            "ignoreDependencies": ["postcss"],
869            "production": true,
870            "plugins": ["custom-plugin.toml"],
871            "rules": {"unused-files": "warn"},
872            "duplicates": {"enabled": false},
873            "health": {"maxCyclomatic": 30}
874        }"#;
875        let config: FallowConfig = serde_json::from_str(json).unwrap();
876        assert_eq!(
877            config.schema.as_deref(),
878            Some("./node_modules/fallow/schema.json")
879        );
880        assert_eq!(config.entry, vec!["src/main.ts"]);
881        assert_eq!(config.ignore_patterns, vec!["generated/**"]);
882        assert_eq!(
883            config.ignore_findings,
884            vec!["**/*.test.ts", "!src/public/**"]
885        );
886        assert_eq!(config.ignore_dependencies, vec!["postcss"]);
887        assert!(config.production);
888        assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
889        assert_eq!(config.rules.unused_files, Severity::Warn);
890        assert!(!config.duplicates.enabled);
891        assert_eq!(config.health.max_cyclomatic, 30);
892    }
893
894    #[test]
895    fn deserialize_json_deny_unknown_fields() {
896        let json = r#"{"unknownField": true}"#;
897        let result: Result<FallowConfig, _> = serde_json::from_str(json);
898        assert!(result.is_err(), "unknown fields should be rejected");
899    }
900
901    #[test]
902    fn ignore_findings_serialization_is_canonical_and_sparse() {
903        let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
904        assert!(default_value.get("ignoreFindings").is_none());
905
906        let config = FallowConfig {
907            ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
908            ..Default::default()
909        };
910        let value = serde_json::to_value(config).unwrap();
911        assert_eq!(
912            value.get("ignoreFindings"),
913            Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
914        );
915    }
916
917    #[test]
918    fn ignore_findings_deserializes_from_toml() {
919        let config: FallowConfig =
920            toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
921
922        assert_eq!(
923            config.ignore_findings,
924            vec!["**/*.test.ts", "!src/public/**"]
925        );
926    }
927
928    #[test]
929    fn generic_ignore_alias_is_rejected() {
930        let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
931
932        assert!(result.is_err());
933    }
934
935    #[test]
936    fn deserialize_json_production_mode_default_false() {
937        let config: FallowConfig = serde_json::from_str("{}").unwrap();
938        assert!(!config.production);
939    }
940
941    #[test]
942    fn deserialize_json_production_mode_true() {
943        let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
944        assert!(config.production);
945    }
946
947    #[test]
948    fn deserialize_json_per_analysis_production_mode() {
949        let config: FallowConfig = serde_json::from_str(
950            r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
951        )
952        .unwrap();
953        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
954        assert!(config.production.for_analysis(ProductionAnalysis::Health));
955        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
956    }
957
958    #[test]
959    fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
960        let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
961            .unwrap_err();
962        assert!(
963            err.to_string().contains("healthTypo"),
964            "error should name the unknown field: {err}"
965        );
966    }
967
968    #[test]
969    fn deserialize_json_dynamically_loaded() {
970        let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
971        let config: FallowConfig = serde_json::from_str(json).unwrap();
972        assert_eq!(
973            config.dynamically_loaded,
974            vec!["plugins/**/*.ts", "locales/**/*.json"]
975        );
976    }
977
978    #[test]
979    fn deserialize_json_dynamically_loaded_defaults_empty() {
980        let config: FallowConfig = serde_json::from_str("{}").unwrap();
981        assert!(config.dynamically_loaded.is_empty());
982    }
983
984    #[test]
985    fn deserialize_json_fix_catalog_delete_preceding_comments() {
986        let config: FallowConfig =
987            serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
988                .unwrap();
989        assert_eq!(
990            config.fix.catalog.delete_preceding_comments,
991            CatalogPrecedingCommentPolicy::Always
992        );
993    }
994
995    #[test]
996    fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
997        let err = serde_json::from_str::<FallowConfig>(
998            r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
999        )
1000        .unwrap_err();
1001        assert!(
1002            err.to_string().contains("sometimes"),
1003            "error should name the bad policy: {err}"
1004        );
1005    }
1006
1007    #[test]
1008    fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1009        let json = r#"{
1010            "usedClassMembers": [
1011                "agInit",
1012                { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1013                { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1014            ]
1015        }"#;
1016        let config: FallowConfig = serde_json::from_str(json).unwrap();
1017        assert_eq!(
1018            config.used_class_members,
1019            vec![
1020                UsedClassMemberRule::from("agInit"),
1021                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1022                    extends: None,
1023                    implements: Some("ICellRendererAngularComp".to_string()),
1024                    members: vec!["refresh".to_string()],
1025                }),
1026                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1027                    extends: Some("BaseCommand".to_string()),
1028                    implements: Some("CanActivate".to_string()),
1029                    members: vec!["execute".to_string()],
1030                }),
1031            ]
1032        );
1033    }
1034
1035    #[test]
1036    fn deserialize_toml_minimal() {
1037        let toml_str = r#"
1038entry = ["src/index.ts"]
1039production = true
1040"#;
1041        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1042        assert_eq!(config.entry, vec!["src/index.ts"]);
1043        assert!(config.production);
1044    }
1045
1046    #[test]
1047    fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1048        // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1049        // key; the back-compat serde alias keeps those existing configs scoping
1050        // instead of silently dropping the (unknown) key and losing the patterns.
1051        let config: FallowConfig =
1052            toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1053        assert_eq!(
1054            config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1055            vec!["packages/*".to_string(), "apps/*".to_string()],
1056            "the `packages` alias must populate `patterns`"
1057        );
1058    }
1059
1060    #[test]
1061    fn deserialize_toml_per_analysis_production_mode() {
1062        let toml_str = r"
1063[production]
1064deadCode = false
1065health = true
1066dupes = false
1067";
1068        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1069        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1070        assert!(config.production.for_analysis(ProductionAnalysis::Health));
1071        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1072    }
1073
1074    #[test]
1075    fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1076        let err = toml::from_str::<FallowConfig>(
1077            r"
1078[production]
1079healthTypo = true
1080",
1081        )
1082        .unwrap_err();
1083        assert!(
1084            err.to_string().contains("healthTypo"),
1085            "error should name the unknown field: {err}"
1086        );
1087    }
1088
1089    #[test]
1090    fn deserialize_toml_with_inline_framework() {
1091        let toml_str = r#"
1092[[framework]]
1093name = "my-framework"
1094enablers = ["my-framework-pkg"]
1095entryPoints = ["src/routes/**/*.tsx"]
1096"#;
1097        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1098        assert_eq!(config.framework.len(), 1);
1099        assert_eq!(config.framework[0].name, "my-framework");
1100        assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1101        assert_eq!(
1102            config.framework[0].entry_points,
1103            vec!["src/routes/**/*.tsx"]
1104        );
1105    }
1106
1107    #[test]
1108    fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1109        let toml_str = r#"
1110[fix.catalog]
1111deletePrecedingComments = "never"
1112"#;
1113        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1114        assert_eq!(
1115            config.fix.catalog.delete_preceding_comments,
1116            CatalogPrecedingCommentPolicy::Never
1117        );
1118    }
1119
1120    #[test]
1121    fn deserialize_toml_with_workspace_config() {
1122        let toml_str = r#"
1123[workspaces]
1124patterns = ["packages/*", "apps/*"]
1125"#;
1126        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1127        assert!(config.workspaces.is_some());
1128        let ws = config.workspaces.unwrap();
1129        assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1130    }
1131
1132    #[test]
1133    fn deserialize_toml_with_ignore_exports() {
1134        let toml_str = r#"
1135[[ignoreExports]]
1136file = "src/types/**/*.ts"
1137exports = ["*"]
1138"#;
1139        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1140        assert_eq!(config.ignore_exports.len(), 1);
1141        assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1142        assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1143    }
1144
1145    #[test]
1146    fn deserialize_toml_used_class_members_supports_scoped_rules() {
1147        let toml_str = r#"
1148usedClassMembers = [
1149  { implements = "ICellRendererAngularComp", members = ["refresh"] },
1150  { extends = "BaseCommand", members = ["execute"] },
1151]
1152"#;
1153        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1154        assert_eq!(
1155            config.used_class_members,
1156            vec![
1157                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1158                    extends: None,
1159                    implements: Some("ICellRendererAngularComp".to_string()),
1160                    members: vec!["refresh".to_string()],
1161                }),
1162                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1163                    extends: Some("BaseCommand".to_string()),
1164                    implements: None,
1165                    members: vec!["execute".to_string()],
1166                }),
1167            ]
1168        );
1169    }
1170
1171    #[test]
1172    fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1173        let result = serde_json::from_str::<FallowConfig>(
1174            r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1175        );
1176        assert!(
1177            result.is_err(),
1178            "unconstrained scoped rule should be rejected"
1179        );
1180    }
1181
1182    #[test]
1183    fn deserialize_ignore_exports_used_in_file_bool() {
1184        let config: FallowConfig =
1185            serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1186
1187        assert!(config.ignore_exports_used_in_file.suppresses(false));
1188        assert!(config.ignore_exports_used_in_file.suppresses(true));
1189    }
1190
1191    #[test]
1192    fn deserialize_ignore_exports_used_in_file_kind_form() {
1193        let config: FallowConfig =
1194            serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1195
1196        assert!(!config.ignore_exports_used_in_file.suppresses(false));
1197        assert!(config.ignore_exports_used_in_file.suppresses(true));
1198    }
1199
1200    #[test]
1201    fn deserialize_toml_deny_unknown_fields() {
1202        let toml_str = r"bogus_field = true";
1203        let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1204        assert!(result.is_err(), "unknown fields should be rejected");
1205    }
1206
1207    #[test]
1208    fn json_serialize_roundtrip() {
1209        let config = FallowConfig {
1210            entry: vec!["src/main.ts".to_string()],
1211            production: true.into(),
1212            ..FallowConfig::default()
1213        };
1214        let json = serde_json::to_string(&config).unwrap();
1215        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1216        assert_eq!(restored.entry, vec!["src/main.ts"]);
1217        assert!(restored.production);
1218    }
1219
1220    #[test]
1221    fn schema_field_not_serialized() {
1222        let config = FallowConfig {
1223            schema: Some("https://example.com/schema.json".to_string()),
1224            ..FallowConfig::default()
1225        };
1226        let json = serde_json::to_string(&config).unwrap();
1227        assert!(
1228            !json.contains("$schema"),
1229            "schema field should be skipped in serialization"
1230        );
1231    }
1232
1233    #[test]
1234    fn extends_field_not_serialized() {
1235        let config = FallowConfig {
1236            extends: vec!["base.json".to_string()],
1237            ..FallowConfig::default()
1238        };
1239        let json = serde_json::to_string(&config).unwrap();
1240        assert!(
1241            !json.contains("extends"),
1242            "extends field should be skipped in serialization"
1243        );
1244    }
1245
1246    #[test]
1247    fn regression_config_deserialize_json() {
1248        let json = r#"{
1249            "regression": {
1250                "baseline": {
1251                    "totalIssues": 42,
1252                    "unusedFiles": 10,
1253                    "unusedExports": 5,
1254                    "circularDependencies": 2
1255                }
1256            }
1257        }"#;
1258        let config: FallowConfig = serde_json::from_str(json).unwrap();
1259        let regression = config.regression.unwrap();
1260        let baseline = regression.baseline.unwrap();
1261        assert_eq!(baseline.total_issues, 42);
1262        assert_eq!(baseline.unused_files, 10);
1263        assert_eq!(baseline.unused_exports, 5);
1264        assert_eq!(baseline.circular_dependencies, 2);
1265        assert_eq!(baseline.unused_types, 0);
1266        assert_eq!(baseline.boundary_violations, 0);
1267    }
1268
1269    #[test]
1270    fn regression_config_defaults_to_none() {
1271        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1272        assert!(config.regression.is_none());
1273    }
1274
1275    #[test]
1276    fn regression_baseline_all_zeros_by_default() {
1277        let baseline = RegressionBaseline::default();
1278        assert_eq!(baseline.total_issues, 0);
1279        assert_eq!(baseline.unused_files, 0);
1280        assert_eq!(baseline.unused_exports, 0);
1281        assert_eq!(baseline.unused_types, 0);
1282        assert_eq!(baseline.unused_dependencies, 0);
1283        assert_eq!(baseline.unused_dev_dependencies, 0);
1284        assert_eq!(baseline.unused_optional_dependencies, 0);
1285        assert_eq!(baseline.unused_enum_members, 0);
1286        assert_eq!(baseline.unused_class_members, 0);
1287        assert_eq!(baseline.unresolved_imports, 0);
1288        assert_eq!(baseline.unlisted_dependencies, 0);
1289        assert_eq!(baseline.duplicate_exports, 0);
1290        assert_eq!(baseline.circular_dependencies, 0);
1291        assert_eq!(baseline.type_only_dependencies, 0);
1292        assert_eq!(baseline.test_only_dependencies, 0);
1293        assert_eq!(baseline.boundary_violations, 0);
1294    }
1295
1296    #[test]
1297    fn regression_config_serialize_roundtrip() {
1298        let baseline = RegressionBaseline {
1299            total_issues: 100,
1300            unused_files: 20,
1301            unused_exports: 30,
1302            ..RegressionBaseline::default()
1303        };
1304        let regression = RegressionConfig {
1305            baseline: Some(baseline),
1306        };
1307        let config = FallowConfig {
1308            regression: Some(regression),
1309            ..FallowConfig::default()
1310        };
1311        let json = serde_json::to_string(&config).unwrap();
1312        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1313        let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1314        assert_eq!(restored_baseline.total_issues, 100);
1315        assert_eq!(restored_baseline.unused_files, 20);
1316        assert_eq!(restored_baseline.unused_exports, 30);
1317        assert_eq!(restored_baseline.unused_types, 0);
1318    }
1319
1320    #[test]
1321    fn regression_config_empty_baseline_deserialize() {
1322        let json = r#"{"regression": {}}"#;
1323        let config: FallowConfig = serde_json::from_str(json).unwrap();
1324        let regression = config.regression.unwrap();
1325        assert!(regression.baseline.is_none());
1326    }
1327
1328    #[test]
1329    fn regression_baseline_not_serialized_when_none() {
1330        let config = FallowConfig {
1331            regression: None,
1332            ..FallowConfig::default()
1333        };
1334        let json = serde_json::to_string(&config).unwrap();
1335        assert!(
1336            !json.contains("regression"),
1337            "regression should be skipped when None"
1338        );
1339    }
1340
1341    #[test]
1342    fn deserialize_json_with_overrides() {
1343        let json = r#"{
1344            "overrides": [
1345                {
1346                    "files": ["*.test.ts", "*.spec.ts"],
1347                    "rules": {
1348                        "unused-exports": "off",
1349                        "unused-files": "warn"
1350                    }
1351                }
1352            ]
1353        }"#;
1354        let config: FallowConfig = serde_json::from_str(json).unwrap();
1355        assert_eq!(config.overrides.len(), 1);
1356        assert_eq!(config.overrides[0].files.len(), 2);
1357        assert_eq!(
1358            config.overrides[0].rules.unused_exports,
1359            Some(Severity::Off)
1360        );
1361        assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1362    }
1363
1364    #[test]
1365    fn deserialize_json_with_boundaries() {
1366        let json = r#"{
1367            "boundaries": {
1368                "preset": "layered"
1369            }
1370        }"#;
1371        let config: FallowConfig = serde_json::from_str(json).unwrap();
1372        assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1373    }
1374
1375    #[test]
1376    fn deserialize_toml_with_regression_baseline() {
1377        let toml_str = r"
1378[regression.baseline]
1379totalIssues = 50
1380unusedFiles = 10
1381unusedExports = 15
1382";
1383        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1384        let baseline = config.regression.unwrap().baseline.unwrap();
1385        assert_eq!(baseline.total_issues, 50);
1386        assert_eq!(baseline.unused_files, 10);
1387        assert_eq!(baseline.unused_exports, 15);
1388    }
1389
1390    #[test]
1391    fn deserialize_toml_with_overrides() {
1392        let toml_str = r#"
1393[[overrides]]
1394files = ["*.test.ts"]
1395
1396[overrides.rules]
1397unused-exports = "off"
1398
1399[[overrides]]
1400files = ["*.stories.tsx"]
1401
1402[overrides.rules]
1403unused-files = "off"
1404"#;
1405        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1406        assert_eq!(config.overrides.len(), 2);
1407        assert_eq!(
1408            config.overrides[0].rules.unused_exports,
1409            Some(Severity::Off)
1410        );
1411        assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1412    }
1413
1414    #[test]
1415    fn regression_config_default_is_none_baseline() {
1416        let config = RegressionConfig::default();
1417        assert!(config.baseline.is_none());
1418    }
1419
1420    #[test]
1421    fn deserialize_json_multiple_ignore_export_rules() {
1422        let json = r#"{
1423            "ignoreExports": [
1424                {"file": "src/types/**/*.ts", "exports": ["*"]},
1425                {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1426                {"file": "src/index.ts", "exports": ["default"]}
1427            ]
1428        }"#;
1429        let config: FallowConfig = serde_json::from_str(json).unwrap();
1430        assert_eq!(config.ignore_exports.len(), 3);
1431        assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1432    }
1433
1434    #[test]
1435    fn deserialize_json_public_packages_camel_case() {
1436        let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1437        let config: FallowConfig = serde_json::from_str(json).unwrap();
1438        assert_eq!(
1439            config.public_packages,
1440            vec!["@myorg/shared-lib", "@myorg/utils"]
1441        );
1442    }
1443
1444    #[test]
1445    fn deserialize_json_public_packages_rejects_snake_case() {
1446        let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1447        let result: Result<FallowConfig, _> = serde_json::from_str(json);
1448        assert!(
1449            result.is_err(),
1450            "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1451        );
1452    }
1453
1454    #[test]
1455    fn deserialize_json_public_packages_empty() {
1456        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1457        assert!(config.public_packages.is_empty());
1458    }
1459
1460    #[test]
1461    fn deserialize_toml_public_packages() {
1462        let toml_str = r#"
1463publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1464"#;
1465        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1466        assert_eq!(
1467            config.public_packages,
1468            vec!["@myorg/shared-lib", "@myorg/ui"]
1469        );
1470    }
1471
1472    #[test]
1473    fn public_packages_serialize_roundtrip() {
1474        let config = FallowConfig {
1475            public_packages: vec!["@myorg/shared-lib".to_string()],
1476            ..FallowConfig::default()
1477        };
1478        let json = serde_json::to_string(&config).unwrap();
1479        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1480        assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1481    }
1482}