Skip to main content

fallow_config/config/
mod.rs

1mod boundaries;
2mod dependency_ignore;
3mod duplicates_config;
4mod entry_effect;
5mod entry_span;
6mod finding_ignore;
7mod flags;
8mod format;
9pub mod glob_validation;
10mod health;
11mod ignore_patterns;
12mod legacy_glob;
13mod markup_extensions;
14mod mutation;
15mod override_effect;
16mod parsing;
17mod resolution;
18mod resolve;
19mod rules;
20mod similar_code;
21mod used_class_members;
22mod workspace_settings;
23
24#[expect(
25    clippy::redundant_pub_crate,
26    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"
27)]
28pub(crate) use boundaries::wildcard_placement_error;
29pub use boundaries::{
30    AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
31    BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
32    LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
33    ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
34    ZoneReferenceKind, ZoneValidationError,
35};
36pub use dependency_ignore::{IgnoreDependencyMatcher, is_dependency_glob};
37pub use duplicates_config::{
38    DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
39};
40pub use entry_effect::EntryEffectRecord;
41pub use entry_span::ConfigEntrySpan;
42pub use finding_ignore::FindingIgnoreMatcher;
43pub use flags::{FlagsConfig, SdkPattern};
44pub use format::OutputFormat;
45pub use glob_validation::compile_path_glob;
46pub use health::{
47    ChangeCouplingConfig, CyclomaticPolicy, EmailMode, HealthConfig, HealthThresholdOverride,
48    OwnershipConfig,
49};
50pub use ignore_patterns::{IgnorePatternSet, UNLIFTABLE_IGNORE_SEGMENTS};
51pub use legacy_glob::{
52    LegacyGlobGroup, LegacyGlobNarrowing, find_legacy_glob_narrowings, has_single_segment_wildcard,
53    suggest_cross_directory_rewrite,
54};
55pub use markup_extensions::{
56    DEFAULT_MARKUP_EXTENSIONS, resolve_markup_extensions, template_markup_extension,
57};
58pub use mutation::{MutationConfig, MutationOperatorName, MutationRunner};
59pub use override_effect::{IneffectiveOverrideRule, project_level_override_rules};
60pub use parsing::{CONFIG_FILE_NAMES, ConfigLoadOptions};
61pub use resolution::{
62    AnalysisSnapshot, CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, CompiledIgnoreCatalogReferenceRule,
63    CompiledIgnoreDependencyOverrideRule, CompiledIgnoreExportRule, ConfigOverride,
64    DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_FILE_SIZE_BYTES, DEFAULT_MAX_FILE_SIZE_MB,
65    IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule, IgnoreExportRule,
66    PACKAGE_BASELINES_ENV, ResolvedConfig, ResolvedOverride, cache_config_hash,
67    cache_dir_env_override, cache_dir_from_env_value, cache_max_size_env_override,
68    cache_max_size_from_env_value, package_baselines_disabled_by_env_value,
69    resolve_max_file_size_bytes,
70};
71pub use resolve::ResolveConfig;
72pub use rules::{
73    KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, Severity, closest_known_rule_name,
74    default_severity_for_kind, is_opt_in_kind,
75};
76pub use similar_code::SimilarCodeConfig;
77pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
78pub use workspace_settings::ResolvedWorkspaceSettings;
79
80use schemars::JsonSchema;
81use serde::{Deserialize, Deserializer, Serialize};
82use std::ops::Not;
83use std::path::PathBuf;
84
85use crate::external_plugin::ExternalPluginDef;
86use crate::workspace::WorkspaceConfig;
87
88/// Value of the `ignoreExportsUsedInFile` config key: whether an export
89/// referenced elsewhere in its own file is suppressed from `unused-export`.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
91#[serde(untagged, rename_all = "camelCase")]
92pub enum IgnoreExportsUsedInFileConfig {
93    /// Blanket toggle: `true` suppresses any export with a same-file use,
94    /// regardless of kind. The default is `false`.
95    Bool(bool),
96    /// Knip-parity object form restricting the suppression to type-only
97    /// exports.
98    ByKind(IgnoreExportsUsedInFileByKind),
99}
100
101impl Default for IgnoreExportsUsedInFileConfig {
102    fn default() -> Self {
103        Self::Bool(false)
104    }
105}
106
107impl From<bool> for IgnoreExportsUsedInFileConfig {
108    fn from(value: bool) -> Self {
109        Self::Bool(value)
110    }
111}
112
113impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
114    fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
115        Self::ByKind(value)
116    }
117}
118
119impl IgnoreExportsUsedInFileConfig {
120    /// Whether any form of the same-file-use suppression is active (the bool
121    /// form is `true`, or either by-kind field is set).
122    #[must_use]
123    pub const fn is_enabled(self) -> bool {
124        match self {
125            Self::Bool(value) => value,
126            Self::ByKind(kind) => kind.type_ || kind.interface,
127        }
128    }
129
130    /// Whether an export with a same-file use should be suppressed, given
131    /// whether fallow classified it as type-only. The bool form suppresses
132    /// regardless of kind; the by-kind form suppresses type-only exports only.
133    #[must_use]
134    pub const fn suppresses(self, is_type_only: bool) -> bool {
135        match self {
136            Self::Bool(value) => value,
137            Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
138        }
139    }
140}
141
142/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
143/// restricting the same-file-use suppression to type-only exports.
144#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
145#[serde(rename_all = "camelCase")]
146pub struct IgnoreExportsUsedInFileByKind {
147    /// 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.
148    #[serde(default, rename = "type")]
149    pub type_: bool,
150    /// 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.
151    #[serde(default)]
152    pub interface: bool,
153}
154
155/// Options for the `unused-component-props` rule.
156///
157/// Lets a project exempt component props whose local destructure binding name
158/// matches a regex from `unused-component-props`, honoring the
159/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
160/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
161/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
162/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
163/// behavior unchanged.
164#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
165#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
166pub struct UnusedComponentPropsConfig {
167    /// Regex matched against each declared prop's LOCAL destructure binding name
168    /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
169    /// to the public prop name when there is no alias. A prop whose local name
170    /// matches is treated as intentionally unused and never reported as
171    /// `unused-component-props`. Matching is unanchored (substring), like
172    /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
173    /// underscore. Compiled and validated at config load (an invalid regex fails
174    /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub ignore_pattern: Option<String>,
177}
178
179impl UnusedComponentPropsConfig {
180    /// True when no option is set, so serialization can omit the section.
181    #[must_use]
182    pub fn is_default(&self) -> bool {
183        self.ignore_pattern.is_none()
184    }
185}
186
187/// Options for the `circular-dependencies` rule.
188///
189/// The default leaves the rule unchanged: every runtime import edge takes
190/// part in cycle detection, and only type-only edges are skipped.
191#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
192#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
193pub struct CircularDependenciesConfig {
194    /// Skip import edges that load their target on demand or on another
195    /// thread when fallow looks for cycles. A literal `import()` inside a
196    /// function, a template `import()`, a lazy `import.meta.glob`, a worker
197    /// URL and a webpack worker loader request (`worker-loader!./work.js`)
198    /// are lazy edges. A top-level `await import()`, `require()` and an
199    /// eager `import.meta.glob` load before the module finishes, so they stay.
200    /// An edge that also carries a static import stays. Default `false`.
201    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
202    pub ignore_lazy_imports: bool,
203}
204
205impl CircularDependenciesConfig {
206    /// True when no option is set, so serialization can omit the section.
207    #[must_use]
208    pub const fn is_default(&self) -> bool {
209        !self.ignore_lazy_imports
210    }
211}
212
213/// Options for projects that use the Effect library.
214///
215/// The default changes nothing: each Effect export is reported like any
216/// other export.
217#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
218#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
219pub struct EffectConfig {
220    /// Report an unused exported Effect schema as an unused type, under the
221    /// `unused-types` rule, and not as an unused export. An Effect schema
222    /// defines a runtime value and a type (`typeof User.Type`), so a team
223    /// that keeps exported types as contracts can keep schemas too. With
224    /// `"unused-types": "off"`, fallow does not report them. A schema is a
225    /// class that extends a `Schema` class factory (`Schema.Class`,
226    /// `Schema.TaggedClass`, `Schema.TaggedError`, `Schema.TaggedRequest`,
227    /// `Schema.Error`, `Schema.Opaque`), or a const whose
228    /// value is a `Schema` constructor, member or pipe chain
229    /// (`Schema.Struct({...})`, `Schema.String.pipe(Schema.brand("Id"))`).
230    /// Each `pipe` argument must be a `Schema` transform.
231    /// `Schema` must come from `effect`, `effect/Schema` or `@effect/schema`.
232    /// Default `false`.
233    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
234    pub schema_exports_as_types: bool,
235}
236
237impl EffectConfig {
238    /// True when no option is set, so serialization can omit the section.
239    #[must_use]
240    pub const fn is_default(&self) -> bool {
241        !self.schema_exports_as_types
242    }
243}
244
245/// The `fix` config section: settings for `fallow fix` apply behavior.
246#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
247#[serde(rename_all = "camelCase")]
248pub struct FixConfig {
249    /// 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.
250    #[serde(default)]
251    pub catalog: CatalogFixConfig,
252}
253
254/// The `fix.catalog` section: how `fallow fix` cleans up unused
255/// `pnpm-workspace.yaml` catalog entries.
256#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
257#[serde(rename_all = "camelCase")]
258pub struct CatalogFixConfig {
259    /// 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.
260    #[serde(default)]
261    pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
262}
263
264/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
265/// lines directly above a catalog entry that `fallow fix` removes. A
266/// `fallow-keep` marker in the block always preserves it regardless of policy.
267#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
268#[serde(rename_all = "lowercase")]
269pub enum CatalogPrecedingCommentPolicy {
270    /// Delete the adjacent comment block only when heuristics attribute it to
271    /// the entry (preceded by a blank line or directly under the catalog
272    /// header) and it is not a section banner. The default.
273    #[default]
274    Auto,
275    /// Always delete the adjacent comment block with the entry.
276    Always,
277    /// Never delete preceding comments.
278    Never,
279}
280
281/// Completeness policy for opt-in TypeScript semantic analysis.
282#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
283#[serde(rename_all = "kebab-case")]
284pub enum TypeAwareRequire {
285    /// Keep conservative findings and report semantic gaps without failing.
286    #[default]
287    BestEffort,
288    /// Fail the quality gate when any requested semantic query is incomplete.
289    Complete,
290}
291
292impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
293    fn from(value: TypeAwareRequire) -> Self {
294        match value {
295            TypeAwareRequire::BestEffort => Self::BestEffort,
296            TypeAwareRequire::Complete => Self::Complete,
297        }
298    }
299}
300
301/// Shared opt-in configuration for TypeScript semantic analysis.
302#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
303#[serde(deny_unknown_fields, rename_all = "camelCase")]
304pub struct TypeAwareConfig {
305    /// Enable the optional TypeScript semantic pass. Disabled by default.
306    #[serde(default)]
307    pub enabled: bool,
308    /// TypeScript project config paths, resolved relative to the project root.
309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
310    pub projects: Vec<String>,
311    /// Decide whether partial semantic analysis is advisory or gating.
312    #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
313    pub require: TypeAwareRequire,
314}
315
316#[expect(
317    clippy::trivially_copy_pass_by_ref,
318    reason = "serde skip_serializing_if callbacks receive field values by reference"
319)]
320fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
321    matches!(value, TypeAwareRequire::BestEffort)
322}
323
324impl TypeAwareConfig {
325    /// True when the section equals its default (disabled, no projects,
326    /// best-effort), so serialization can omit it.
327    #[must_use]
328    pub fn is_default(&self) -> bool {
329        !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
330    }
331}
332
333/// Schema for `extends`. The loader accepts one string or an array of strings
334/// and normalizes both to a list before it deserializes the config (#3351).
335fn extends_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
336    schemars::json_schema!({
337        "anyOf": [
338            { "type": "string" },
339            { "type": "array", "items": { "type": "string" } }
340        ]
341    })
342}
343
344/// The user-facing fallow configuration as authored in `.fallowrc.json` /
345/// `.fallowrc.jsonc` / `fallow.toml` / `.fallow.toml`.
346///
347/// Every field documents its serialized meaning, default, and precedence
348/// against CLI flags and environment variables where they exist.
349/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
350/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
351/// Unknown keys are rejected at load so typos fail loud.
352#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
353#[serde(deny_unknown_fields, rename_all = "camelCase")]
354// Both `.fallowrc.json` and `.fallowrc.jsonc` are read with the JSONC dialect
355// from `crate::jsonc::parse_options`, so the schema declares the same dialect.
356// JSON language service clients (VS Code, Zed) read these two keywords off the
357// root object and otherwise flag syntax the loader accepts. They are
358// annotations only: nothing in fallow reads them back.
359#[schemars(extend("allowComments" = true, "allowTrailingCommas" = true))]
360pub struct FallowConfig {
361    /// 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.
362    #[serde(rename = "$schema", default, skip_serializing)]
363    pub schema: Option<String>,
364
365    /// 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.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub minimum_version: Option<String>,
368
369    /// A single parent config source, or an ordered array of them, to inherit before this file's own keys apply; each source 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).
370    #[serde(default, skip_serializing)]
371    #[schemars(schema_with = "extends_schema")]
372    pub extends: Vec<String>,
373
374    /// 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. For a script that does not run in production, use `supportEntry` and leave its glob out of `entry`: a file that also matches `entry` stays a runtime root. A single `*` stays within one path segment; use `**` to match across directories.
375    #[serde(default)]
376    pub entry: Vec<String>,
377
378    /// 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. A `!`-prefixed entry is an exception that applies after the defaults and the positive patterns: `"!src/policy/coverage/**"` brings back hand-written source under a built-in default such as `**/coverage/**`, and `"!.config/**"` adds a hidden directory to discovery. Paths under `node_modules` or `.git` can not be lifted, and a `!` entry that names one of these segments is a config error. A single `*` stays within one path segment; use `**` to match across directories.
379    #[serde(default)]
380    pub ignore_patterns: Vec<String>,
381
382    /// An array of project-root-relative glob patterns whose matching files are support entry points: dev scripts, tooling and setup files that run outside production. In default mode a support entry keeps its file and its imports reachable, the same as `entry`. In `--production` mode (or `production` for dead-code analysis), fallow leaves a file that only a support entry matches out of the analysis, so its imports credit no export, file or dependency. A file that also matches `entry`, a framework plugin or a package.json field stays an entry point, and a support file that production code imports stays a normal module. Use `entry` for the files that run in production. A single `*` stays within one path segment; use `**` to match across directories.
383    #[serde(default, skip_serializing_if = "Vec::is_empty")]
384    pub support_entry: Vec<String>,
385
386    /// 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. A matching file that parses with errors reports no `source-parse-degraded` diagnostic, and its partial parse does not mark other findings as incomplete; use this only for files that are broken on purpose, such as syntax-error test fixtures. A single `*` stays within one path segment; use `**` to match across directories.
387    #[serde(default, skip_serializing_if = "Vec::is_empty")]
388    pub ignore_findings: Vec<String>,
389
390    /// 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`); an entry with neither never activates, and config load warns. Each entry can also have `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.
391    #[serde(default)]
392    pub framework: Vec<ExternalPluginDef>,
393
394    /// Monorepo workspace configuration. `patterns` adds workspace package roots beyond manifest discovery; `changedSince` maps exact project-root-relative workspace roots to Git baseline refs. A global changed-since request overrides those per-package baselines.
395    #[serde(default)]
396    pub workspaces: Option<WorkspaceConfig>,
397
398    /// A list of package names or package-name globs 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. An entry without glob characters matches the package name exactly; an entry with `*`, `?`, `[` or `{` is a glob in the `ignorePatterns` syntax matched against the package name, so `@acme/*` covers every package in the `@acme` scope.
399    #[serde(default)]
400    pub ignore_dependencies: Vec<String>,
401
402    /// A list of binary names or name globs that the `unlisted-binaries` rule does not report. Set it for a binary that the operating system, the CI image, or a tool outside `node_modules` provides (e.g. `["gnome-extensions", "tailscale"]`). An entry without glob characters matches the binary name exactly; an entry with `*`, `?`, `[` or `{` is a glob matched against the binary name, so `xcrun*` covers every name that starts with `xcrun`. Fallow already skips shell builtins and a fixed list of common operating-system tools (such as `git`, `ssh-keygen`, `curl`, and `ffmpeg`).
403    #[serde(default, skip_serializing_if = "Vec::is_empty")]
404    pub ignore_binaries: Vec<String>,
405
406    /// A list of command names whose file arguments fallow does not make entry points. Fallow reads commands in package.json scripts (root and workspace packages), CI files (GitHub Actions and GitLab CI), Dockerfiles, Procfiles, and fly.toml files, and a file that a command names (such as `node scripts/seed.ts`) normally becomes an entry point. A listed command still counts as a used dependency, and its `--config` file is still tracked. Formatters and linters (ESLint, Prettier, Oxlint, Oxfmt, Biome, Stylelint, and similar tools) never make their targets entry points, so they do not need to be listed. Set it for a command whose file arguments are data, not code that runs (e.g. `["my-codegen"]`), or use `["*"]` to turn off entry points from all commands and declare real entries in `entry`. A name matches the command after environment, package-manager, and wrapper prefixes (`npx`, `pnpm exec`, `yarn run`, `varlock run --`), by exact file name; `*` is the only wildcard.
407    #[serde(default, skip_serializing_if = "Vec::is_empty")]
408    pub ignore_command_entries: Vec<String>,
409
410    /// 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.
411    #[serde(default)]
412    pub ignore_unresolved_imports: Vec<String>,
413
414    /// 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. A single `*` stays within one path segment; use `**` to match across directories.
415    #[serde(default)]
416    pub ignore_exports: Vec<IgnoreExportRule>,
417
418    /// 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.
419    #[serde(default, skip_serializing_if = "Vec::is_empty")]
420    pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
421
422    /// 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"`.
423    #[serde(default, skip_serializing_if = "Vec::is_empty")]
424    pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
425
426    /// 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.
427    #[serde(default)]
428    pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
429
430    /// 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.
431    #[serde(default, skip_serializing_if = "Vec::is_empty")]
432    pub ignore_decorators: Vec<String>,
433
434    /// 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.
435    #[serde(default)]
436    pub used_class_members: Vec<UsedClassMemberRule>,
437
438    /// 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), `ignoreSymlinks` (false, omit clone instances whose path is a symlink or lies under a symlinked directory), `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.
439    #[serde(default)]
440    pub duplicates: DuplicatesConfig,
441
442    /// Configures the explicit local `similar-code` candidate workflow:
443    /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
444    /// additional `ignore` globs. Provider identity, setup, executables,
445    /// endpoints, credentials, and consent cannot be set by project config.
446    #[serde(default)]
447    pub similar_code: SimilarCodeConfig,
448
449    /// Configures the explicit `fallow mutation` workflow: `runner` (`auto`
450    /// or `vitest`), `operators` (kebab-case names, default the default set),
451    /// `minScore` (0 to 100; a lower score exits with code 1), and
452    /// `concurrency` (half the logical cores). No key starts a run, and the
453    /// side-effect override is a CLI flag only.
454    #[serde(default, skip_serializing_if = "MutationConfig::is_default")]
455    pub mutation: MutationConfig,
456
457    /// 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), `maxFileLines` (max physical lines per file before a file-level finding, 0 means off), `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`/`maxFileLines`/`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 `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.
458    #[serde(default)]
459    pub health: HealthConfig,
460
461    /// Opts into TypeScript semantic analysis for project-wide symbol use,
462    /// provenance, API surface, symbol impact, and public-signature coupling.
463    /// This does not surface compiler diagnostics or typed lint rules.
464    #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
465    pub type_aware: TypeAwareConfig,
466
467    /// 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.
468    #[serde(default)]
469    pub rules: RulesConfig,
470
471    #[serde(
472        default,
473        skip_serializing_if = "UnusedComponentPropsConfig::is_default"
474    )]
475    /// 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).
476    pub unused_component_props: UnusedComponentPropsConfig,
477
478    #[serde(
479        default,
480        skip_serializing_if = "CircularDependenciesConfig::is_default"
481    )]
482    /// Options for the `circular-dependencies` rule, currently only `ignoreLazyImports`. Set `{ "ignoreLazyImports": true }` to skip import edges that load on demand or on another thread (an `import()` inside a function, a template `import()`, a lazy `import.meta.glob`, a worker URL, a webpack worker loader request such as `worker-loader!./work.js`) when fallow looks for cycles. A top-level `await import()`, `require()`, an eager glob, and an edge that also has a static import stay in the cycle graph. Default `false` leaves the rule unchanged.
483    pub circular_dependencies: CircularDependenciesConfig,
484
485    #[serde(default, skip_serializing_if = "EffectConfig::is_default")]
486    /// Options for projects that use the Effect library, currently only `schemaExportsAsTypes`. Set `{ "schemaExportsAsTypes": true }` to report an unused exported Effect schema (a class that extends `Schema.Class`, `Schema.TaggedClass`, `Schema.TaggedError` and the other `Schema` class factories, or a const such as `Schema.Struct({...})` or `Schema.String.pipe(Schema.brand("Id"))`) as an unused type under the `unused-types` rule, not as an unused export, so `"unused-types": "off"` hides it. `Schema` must come from `effect`, `effect/Schema` or `@effect/schema`. A re-export of a schema from another module also counts. In a module that imports Effect, a chain on an imported schema (`Imported.pipe(Schema.brand("Id"))`, `Imported.annotations({...})`) and an alias (`export const Copy = Imported`) also count. Default `false` leaves every report unchanged.
487    pub effect: EffectConfig,
488
489    /// 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).
490    #[serde(default)]
491    pub boundaries: BoundaryConfig,
492
493    /// 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.*` and `import.meta.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`).
494    #[serde(default)]
495    pub flags: FlagsConfig,
496
497    /// 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.
498    #[serde(default)]
499    pub security: SecurityConfig,
500
501    /// 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.
502    #[serde(default)]
503    pub fix: FixConfig,
504
505    /// 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.
506    #[serde(default)]
507    pub resolve: ResolveConfig,
508
509    /// 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).
510    #[serde(default)]
511    pub production: ProductionConfig,
512
513    /// 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).
514    #[serde(default)]
515    pub plugins: Vec<String>,
516
517    /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
518    /// project root. Each pack declares `banned-call`, `banned-import`, or
519    /// `banned-effect` rules that report as `policy-violation` findings. Packs
520    /// are pure data: no project code is executed. Invalid or missing packs
521    /// fail config load.
522    #[serde(default, skip_serializing_if = "Vec::is_empty")]
523    pub rule_packs: Vec<String>,
524
525    /// 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. A single `*` stays within one path segment; use `**` to match across directories.
526    #[serde(default)]
527    pub dynamically_loaded: Vec<String>,
528
529    /// An array of file extensions, without the leading dot, for server-side template files whose text counts as CSS class references for the `unreferenced-css-class` finding of `fallow health --css`. These files are read as text only: they do not join source discovery or the module graph, so they never become unused files and their imports are not followed. Templates are more lenient than Markdown: the whole text of a template file counts as a dynamic class reference, so any class-like word in it counts as used, also a common word such as `hidden` or `title` in prose or a template tag. A Markdown file joins the reference text only when it has dynamic class syntax. The extensions `liquid`, `njk`, `hbs`, `handlebars`, `twig`, and `blade.php` are always read; set this (e.g. `["tpl", "erb"]`) for other template languages. An extension matches the end of a file name, ignoring case, so `blade.php` matches `welcome.blade.php`. Values may contain only letters, digits, `.`, `-`, and `_`. A value whose last segment is a script, stylesheet, data or asset extension (`js`, `ts`, `css`, `json`, `svg`, `xml`, `map`, and similar, so also `module.css` or `d.ts`), or a compound value that ends in a markup extension that fallow already reads (`page.html`), is a config error. The walk uses the ignore files of source discovery (`.gitignore`, `.ignore`), skips `ignorePatterns`, `health.ignore`, `node_modules`, `vendor`, and build output directories, reads only regular files, and skips files over the `--max-file-size` limit. In `extends`, a child list replaces the parent list.
530    #[serde(
531        default,
532        skip_serializing_if = "Vec::is_empty",
533        deserialize_with = "markup_extensions::deserialize_markup_extensions"
534    )]
535    pub markup_extensions: Vec<String>,
536
537    /// 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 a rule 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). For most rules, an override cannot start a detector for a rule that is off at top level, so set the top-level rule on and use an override to set `off` for the other paths. Project-level rules ignore overrides: unused-dependencies, unused-dev-dependencies, unused-optional-dependencies, unlisted-dependencies, unlisted-binaries, type-only-dependencies, test-only-dependencies, dev-dependencies-in-production, duplicate-exports, re-export-cycle and unused-catalog-entries. Fallow reports each such entry as an `override-rule-ineffective` diagnostic that names the mechanism that works. A single `*` stays within one path segment; use `**` to match across directories.
538    #[serde(default)]
539    pub overrides: Vec<ConfigOverride>,
540
541    /// 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.
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub codeowners: Option<String>,
544
545    /// 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).
546    #[serde(default)]
547    pub public_packages: Vec<String>,
548
549    /// 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.
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub regression: Option<RegressionConfig>,
552
553    /// 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.
554    #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
555    pub audit: AuditConfig,
556
557    /// 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.
558    #[serde(default)]
559    pub sealed: bool,
560
561    /// 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.
562    #[serde(default)]
563    pub include_entry_exports: bool,
564
565    /// When true, the report keeps the unused exports, unused types, unused class members and unused enum members of a file that is an unused file. Boolean, defaults to false: deleting an unused file removes these findings, so the report hides them and counts them in cascade_hidden. The CLI flag --show-cascade applies the same behavior for one run.
566    #[serde(default)]
567    pub show_cascade: bool,
568
569    /// 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.
570    #[serde(default)]
571    pub auto_imports: bool,
572
573    /// When true, the run fails with exit code 1 if fallow could not parse a source file cleanly (a `source-parse-degraded` or `source-nesting-too-deep` 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.
574    #[serde(default)]
575    pub fail_on_parse_error: bool,
576
577    /// 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`.
578    #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
579    pub cache: CacheConfig,
580}
581
582/// Scopes `fallow security` catalogue behavior. An absent category block admits
583/// every catalogue category. `hardcoded-secret` is include-required and only
584/// runs when explicitly listed in `security.categories.include`.
585#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
586#[serde(deny_unknown_fields, rename_all = "camelCase")]
587pub struct SecurityConfig {
588    /// Include/exclude filter over category ids (e.g. `dangerous-html`).
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub categories: Option<SecurityCategories>,
591    /// Additional project-local names for HTTP request objects. These names
592    /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
593    /// `*.body` source patterns. They do not replace the built-ins and do not
594    /// gate `*.searchParams`, which intentionally stays ungated.
595    #[serde(default, skip_serializing_if = "Vec::is_empty")]
596    pub request_receivers: Vec<String>,
597}
598
599impl SecurityConfig {
600    /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
601    /// in first-seen order, with empty entries dropped; the form the matcher
602    /// compares receiver names against (matching is case-insensitive).
603    #[must_use]
604    pub fn normalized_request_receivers(&self) -> Vec<String> {
605        let mut receivers = Vec::new();
606        for receiver in &self.request_receivers {
607            let normalized = receiver.trim().to_ascii_lowercase();
608            if !normalized.is_empty() && !receivers.contains(&normalized) {
609                receivers.push(normalized);
610            }
611        }
612        receivers
613    }
614
615    /// False when any configured receiver is empty or whitespace-only, which
616    /// config validation reports as an error instead of silently dropping it.
617    #[must_use]
618    pub fn request_receivers_are_valid(&self) -> bool {
619        self.request_receivers
620            .iter()
621            .all(|receiver| !receiver.trim().is_empty())
622    }
623}
624
625/// Include/exclude lists scoping the active security categories. When `include`
626/// is set, only those categories are active; `exclude` removes categories from
627/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
628/// still requires explicit inclusion.
629#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
630#[serde(deny_unknown_fields, rename_all = "camelCase")]
631pub struct SecurityCategories {
632    /// Catalogue category ids to admit. When set, all others are excluded.
633    #[serde(default, skip_serializing_if = "Option::is_none")]
634    pub include: Option<Vec<String>>,
635    /// Catalogue category ids to remove from the admitted set.
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub exclude: Option<Vec<String>>,
638}
639
640/// The `cache` config section: location and size ceiling of fallow's
641/// persistent caches (default directory `<root>/.fallow`).
642#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
643#[serde(deny_unknown_fields, rename_all = "camelCase")]
644pub struct CacheConfig {
645    /// Directory for fallow's persistent analysis cache. Relative paths resolve
646    /// from the project root.
647    #[serde(default, skip_serializing_if = "Option::is_none")]
648    pub dir: Option<PathBuf>,
649    /// Maximum size of the persistent extraction cache, in megabytes.
650    #[serde(default, skip_serializing_if = "Option::is_none")]
651    pub max_size_mb: Option<u32>,
652}
653
654impl CacheConfig {
655    /// True when neither field is set, so serialization can omit the section.
656    #[must_use]
657    pub fn is_default(&self) -> bool {
658        self.dir.is_none() && self.max_size_mb.is_none()
659    }
660}
661
662/// The analysis families production mode can be scoped to independently via
663/// the object form of the `production` config key.
664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
665pub enum ProductionAnalysis {
666    /// Unused files/exports/dependencies detection.
667    DeadCode,
668    /// Complexity and health scoring.
669    Health,
670    /// Clone detection.
671    Dupes,
672}
673
674/// Value of the `production` config key: excludes test/spec/story/dev files
675/// from discovery, either globally or per analysis family.
676#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
677#[serde(untagged)]
678pub enum ProductionConfig {
679    /// Boolean form applying to every analysis. The default is `false`.
680    Global(bool),
681    /// Object form (`{ deadCode?, health?, dupes? }`) scoping production mode
682    /// per analysis family.
683    PerAnalysis(PerAnalysisProductionConfig),
684}
685
686impl<'de> Deserialize<'de> for ProductionConfig {
687    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
688    where
689        D: Deserializer<'de>,
690    {
691        struct ProductionConfigVisitor;
692
693        impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
694            type Value = ProductionConfig;
695
696            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
697                formatter.write_str("a boolean or per-analysis production config object")
698            }
699
700            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
701            where
702                E: serde::de::Error,
703            {
704                Ok(ProductionConfig::Global(value))
705            }
706
707            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
708            where
709                A: serde::de::MapAccess<'de>,
710            {
711                PerAnalysisProductionConfig::deserialize(
712                    serde::de::value::MapAccessDeserializer::new(map),
713                )
714                .map(ProductionConfig::PerAnalysis)
715            }
716        }
717
718        deserializer.deserialize_any(ProductionConfigVisitor)
719    }
720}
721
722impl Default for ProductionConfig {
723    fn default() -> Self {
724        Self::Global(false)
725    }
726}
727
728impl From<bool> for ProductionConfig {
729    fn from(value: bool) -> Self {
730        Self::Global(value)
731    }
732}
733
734impl Not for ProductionConfig {
735    type Output = bool;
736
737    fn not(self) -> Self::Output {
738        !self.any_enabled()
739    }
740}
741
742impl ProductionConfig {
743    /// Whether production mode applies to `analysis` under this config.
744    #[must_use]
745    pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
746        match self {
747            Self::Global(value) => value,
748            Self::PerAnalysis(config) => match analysis {
749                ProductionAnalysis::DeadCode => config.dead_code,
750                ProductionAnalysis::Health => config.health,
751                ProductionAnalysis::Dupes => config.dupes,
752            },
753        }
754    }
755
756    /// The boolean form's value; `false` for the per-analysis form, which has
757    /// no global toggle.
758    #[must_use]
759    pub const fn global(self) -> bool {
760        match self {
761            Self::Global(value) => value,
762            Self::PerAnalysis(_) => false,
763        }
764    }
765
766    /// Whether production mode is enabled for at least one analysis family.
767    #[must_use]
768    pub const fn any_enabled(self) -> bool {
769        match self {
770            Self::Global(value) => value,
771            Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
772        }
773    }
774}
775
776/// Object form of the `production` config key, scoping production mode to
777/// individual analysis families in combined `fallow` and `fallow audit`.
778#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
779#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
780pub struct PerAnalysisProductionConfig {
781    /// 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.
782    pub dead_code: bool,
783    /// 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.
784    pub health: bool,
785    /// 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.
786    pub dupes: bool,
787}
788
789/// The `audit` config section: in-repo defaults for `fallow audit`, each
790/// overridable by its matching CLI flag.
791#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
792#[serde(rename_all = "camelCase")]
793pub struct AuditConfig {
794    /// 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.
795    #[serde(default, skip_serializing_if = "AuditGate::is_default")]
796    pub gate: AuditGate,
797
798    /// Selects how a worsened complexity finding affects the `fallow audit` verdict under `gate: new-only`. A worsened finding was already in the base snapshot, and a measured value is higher now. Any growth of cyclomatic, cognitive or CRAP counts. The line count must grow by at least 5 lines, and it includes comments and blank lines. `warn` (default) makes the verdict at least `warn` and does not fail the run. `error` counts a worsened finding like an introduced finding. `off` reports only the growth of a metric that the finding exceeds as worsened, which gives at least `warn`. A finding whose exceeded metric grew is worsened when it stays in its severity tier (`moderate`, `high`, `critical`), and introduced when it moves to a higher tier or exceeds a metric that the base finding did not exceed. The `--worsened` CLI flag overrides this.
799    #[serde(default, skip_serializing_if = "AuditWorsened::is_default")]
800    pub worsened: AuditWorsened,
801
802    /// Toggles the dead-code sub-analysis in `fallow audit` (unused files, exports, types, members and dependencies, plus boundary violations and circular dependencies, which come from the same pass). Defaults to on when unset; set `false` to leave it out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip dead-code` turns it off for one run and `--only` replaces this selection. The review brief (`--brief`, `fallow review`) keeps every sub-analysis because it reads the module graph.
803    #[serde(default, skip_serializing_if = "Option::is_none")]
804    pub dead_code: Option<bool>,
805
806    /// Toggles the health sub-analysis in `fallow audit` (complexity and CRAP findings, plus styling findings, which come from the same pass). Defaults to on when unset; set `false` to leave it out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip health` turns it off for one run and `--only` replaces this selection.
807    #[serde(default, skip_serializing_if = "Option::is_none")]
808    pub health: Option<bool>,
809
810    /// Toggles the duplication sub-analysis in `fallow audit`. Defaults to on when unset; set `false` to leave clone groups out of the verdict, summary and attribution, on the head and on the base snapshot. `fallow audit --skip dupes` turns it off for one run and `--only` replaces this selection.
811    #[serde(default, skip_serializing_if = "Option::is_none")]
812    pub dupes: Option<bool>,
813
814    /// 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.
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub css: Option<bool>,
817
818    /// 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.
819    #[serde(default, skip_serializing_if = "Option::is_none")]
820    pub css_deep: Option<bool>,
821
822    /// 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`.
823    #[serde(default, skip_serializing_if = "Option::is_none")]
824    pub dead_code_baseline: Option<String>,
825
826    /// 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.
827    #[serde(default, skip_serializing_if = "Option::is_none")]
828    pub health_baseline: Option<String>,
829
830    /// 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.
831    #[serde(default, skip_serializing_if = "Option::is_none")]
832    pub dupes_baseline: Option<String>,
833
834    /// 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 same window applies to the base-snapshot files in the project cache directory, counted from their last use; independent of this window, audit keeps only the newest 32 of those files. The `FALLOW_AUDIT_CACHE_MAX_AGE_DAYS` environment variable overrides this field.
835    #[serde(default, skip_serializing_if = "Option::is_none")]
836    pub cache_max_age_days: Option<u32>,
837
838    /// 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.
839    #[serde(default, skip_serializing_if = "Option::is_none")]
840    pub type_aware: Option<bool>,
841}
842
843impl AuditConfig {
844    /// True when every field is unset, so serialization can omit the section.
845    #[must_use]
846    pub fn is_empty(&self) -> bool {
847        self.gate.is_default()
848            && self.worsened.is_default()
849            && self.dead_code.is_none()
850            && self.health.is_none()
851            && self.dupes.is_none()
852            && self.css.is_none()
853            && self.css_deep.is_none()
854            && self.dead_code_baseline.is_none()
855            && self.health_baseline.is_none()
856            && self.dupes_baseline.is_none()
857            && self.cache_max_age_days.is_none()
858            && self.type_aware.is_none()
859    }
860}
861
862/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
863#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
864#[serde(rename_all = "kebab-case")]
865pub enum AuditGate {
866    /// Fail only on findings the current changeset introduced, determined by
867    /// a base-snapshot attribution pass. The default.
868    #[default]
869    NewOnly,
870    /// Fail on every finding in changed files, skipping the attribution pass.
871    All,
872}
873
874impl AuditGate {
875    /// True for the default `new-only` gate, so serialization can omit it.
876    #[must_use]
877    pub const fn is_default(&self) -> bool {
878        matches!(self, Self::NewOnly)
879    }
880}
881
882/// Value of `audit.worsened`: how a worsened complexity finding affects the
883/// `fallow audit` verdict.
884#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
885#[serde(rename_all = "kebab-case")]
886pub enum AuditWorsened {
887    /// A worsened finding makes the verdict at least `warn` and does not fail
888    /// the run. The default.
889    #[default]
890    Warn,
891    /// A worsened finding counts like an introduced finding.
892    Error,
893    /// Growth only in metrics that the finding does not exceed stays
894    /// inherited. Growth of an exceeded metric stays worsened and gives at
895    /// least `warn`.
896    Off,
897}
898
899impl AuditWorsened {
900    /// True for the default `warn` mode, so serialization can omit it.
901    #[must_use]
902    pub const fn is_default(&self) -> bool {
903        matches!(self, Self::Warn)
904    }
905}
906
907/// The `regression` config section holding the saved issue-count baseline for
908/// the `--fail-on-regression` gate.
909#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
910#[serde(rename_all = "camelCase")]
911pub struct RegressionConfig {
912    /// 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.
913    #[serde(default, skip_serializing_if = "Option::is_none")]
914    pub baseline: Option<RegressionBaseline>,
915}
916
917/// Saved per-issue-type counts written by `--save-baseline` and compared by
918/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
919/// so hand-trimmed baselines stay loadable.
920#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
921#[serde(rename_all = "camelCase")]
922pub struct RegressionBaseline {
923    /// Baseline count of optional component prop review candidates.
924    #[serde(default)]
925    pub absent_component_props: usize,
926
927    /// Compatibility identity for the analysis that produced these counts.
928    /// Missing values in existing configs are treated as syntactic.
929    #[serde(default)]
930    pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
931    /// Baseline count across all issue types.
932    #[serde(default)]
933    pub total_issues: usize,
934    /// Baseline count of `unused-files` findings.
935    #[serde(default)]
936    pub unused_files: usize,
937    /// Baseline count of `unused-exports` findings.
938    #[serde(default)]
939    pub unused_exports: usize,
940    /// Baseline count of `unused-types` findings.
941    #[serde(default)]
942    pub unused_types: usize,
943    /// Baseline count of `unused-dependencies` findings.
944    #[serde(default)]
945    pub unused_dependencies: usize,
946    /// Baseline count of `unused-dev-dependencies` findings.
947    #[serde(default)]
948    pub unused_dev_dependencies: usize,
949    /// Baseline count of `unused-optional-dependencies` findings.
950    #[serde(default)]
951    pub unused_optional_dependencies: usize,
952    /// Baseline count of `unused-enum-members` findings.
953    #[serde(default)]
954    pub unused_enum_members: usize,
955    /// Baseline count of `unused-class-members` findings.
956    #[serde(default)]
957    pub unused_class_members: usize,
958    /// Baseline count of `unresolved-imports` findings.
959    #[serde(default)]
960    pub unresolved_imports: usize,
961    /// Baseline count of `unlisted-dependencies` findings.
962    #[serde(default)]
963    pub unlisted_dependencies: usize,
964    /// Baseline count of `unlisted-binaries` findings.
965    #[serde(default)]
966    pub unlisted_binaries: usize,
967    /// Baseline count of `duplicate-exports` findings.
968    #[serde(default)]
969    pub duplicate_exports: usize,
970    /// Baseline count of `circular-dependencies` findings.
971    #[serde(default)]
972    pub circular_dependencies: usize,
973    /// Baseline count of `re-export-cycle` findings.
974    #[serde(default)]
975    pub re_export_cycles: usize,
976    /// Baseline count of `package-cycle` findings.
977    #[serde(default)]
978    pub package_cycles: usize,
979    /// Baseline count of `type-only-dependencies` findings.
980    #[serde(default)]
981    pub type_only_dependencies: usize,
982    /// Baseline count of `test-only-dependencies` findings.
983    #[serde(default)]
984    pub test_only_dependencies: usize,
985    /// Baseline count of `dev-dependencies-in-production` findings.
986    #[serde(default)]
987    pub dev_dependencies_in_production: usize,
988    /// Baseline count of `boundary-violation` findings.
989    #[serde(default)]
990    pub boundary_violations: usize,
991    /// Baseline count of boundary-coverage-violation findings.
992    #[serde(default)]
993    pub boundary_coverage_violations: usize,
994    /// Baseline count of boundary-call-violation findings.
995    #[serde(default)]
996    pub boundary_call_violations: usize,
997    /// Baseline count of `policy-violation` findings.
998    #[serde(default)]
999    pub policy_violations: usize,
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004    use super::*;
1005
1006    #[test]
1007    fn regression_baseline_preserves_absent_component_prop_count() {
1008        let baseline: RegressionBaseline =
1009            serde_json::from_value(serde_json::json!({"absentComponentProps":7})).unwrap();
1010        assert_eq!(
1011            serde_json::to_value(baseline).unwrap()["absentComponentProps"],
1012            7
1013        );
1014    }
1015
1016    #[test]
1017    fn default_config_has_empty_collections() {
1018        let config = FallowConfig::default();
1019        assert!(config.schema.is_none());
1020        assert!(config.extends.is_empty());
1021        assert!(config.entry.is_empty());
1022        assert!(config.ignore_patterns.is_empty());
1023        assert!(config.ignore_findings.is_empty());
1024        assert!(config.framework.is_empty());
1025        assert!(config.workspaces.is_none());
1026        assert!(config.ignore_dependencies.is_empty());
1027        assert!(config.ignore_exports.is_empty());
1028        assert!(config.used_class_members.is_empty());
1029        assert!(config.plugins.is_empty());
1030        assert!(config.dynamically_loaded.is_empty());
1031        assert!(config.overrides.is_empty());
1032        assert!(config.public_packages.is_empty());
1033        assert_eq!(
1034            config.fix.catalog.delete_preceding_comments,
1035            CatalogPrecedingCommentPolicy::Auto
1036        );
1037        assert!(!config.production);
1038    }
1039
1040    #[test]
1041    fn deserialize_empty_json_object() {
1042        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1043        assert!(config.entry.is_empty());
1044        assert!(!config.production);
1045        assert!(!config.type_aware.enabled);
1046        assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
1047    }
1048
1049    #[test]
1050    fn deserialize_type_aware_config() {
1051        let config: FallowConfig = serde_json::from_str(
1052            r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
1053        )
1054        .unwrap();
1055
1056        assert!(config.type_aware.enabled);
1057        assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
1058        assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
1059    }
1060
1061    #[test]
1062    fn deserialize_type_aware_config_rejects_unknown_fields() {
1063        let result = serde_json::from_str::<FallowConfig>(
1064            r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
1065        );
1066        assert!(result.is_err());
1067    }
1068
1069    #[test]
1070    fn deserialize_json_with_all_top_level_fields() {
1071        let json = r#"{
1072            "$schema": "./node_modules/fallow/schema.json",
1073            "entry": ["src/main.ts"],
1074            "ignorePatterns": ["generated/**"],
1075            "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
1076            "ignoreDependencies": ["postcss"],
1077            "production": true,
1078            "plugins": ["custom-plugin.toml"],
1079            "rules": {"unused-files": "warn"},
1080            "duplicates": {"enabled": false},
1081            "health": {"maxCyclomatic": 30}
1082        }"#;
1083        let config: FallowConfig = serde_json::from_str(json).unwrap();
1084        assert_eq!(
1085            config.schema.as_deref(),
1086            Some("./node_modules/fallow/schema.json")
1087        );
1088        assert_eq!(config.entry, vec!["src/main.ts"]);
1089        assert_eq!(config.ignore_patterns, vec!["generated/**"]);
1090        assert_eq!(
1091            config.ignore_findings,
1092            vec!["**/*.test.ts", "!src/public/**"]
1093        );
1094        assert_eq!(config.ignore_dependencies, vec!["postcss"]);
1095        assert!(config.production);
1096        assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
1097        assert_eq!(config.rules.unused_files, Severity::Warn);
1098        assert!(!config.duplicates.enabled);
1099        assert_eq!(config.health.max_cyclomatic, 30);
1100    }
1101
1102    #[test]
1103    fn deserialize_json_deny_unknown_fields() {
1104        let json = r#"{"unknownField": true}"#;
1105        let result: Result<FallowConfig, _> = serde_json::from_str(json);
1106        assert!(result.is_err(), "unknown fields should be rejected");
1107    }
1108
1109    #[test]
1110    fn ignore_findings_serialization_is_canonical_and_sparse() {
1111        let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
1112        assert!(default_value.get("ignoreFindings").is_none());
1113
1114        let config = FallowConfig {
1115            ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
1116            ..Default::default()
1117        };
1118        let value = serde_json::to_value(config).unwrap();
1119        assert_eq!(
1120            value.get("ignoreFindings"),
1121            Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
1122        );
1123    }
1124
1125    #[test]
1126    fn ignore_findings_deserializes_from_toml() {
1127        let config: FallowConfig =
1128            toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
1129
1130        assert_eq!(
1131            config.ignore_findings,
1132            vec!["**/*.test.ts", "!src/public/**"]
1133        );
1134    }
1135
1136    #[test]
1137    fn generic_ignore_alias_is_rejected() {
1138        let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
1139
1140        assert!(result.is_err());
1141    }
1142
1143    #[test]
1144    fn deserialize_json_production_mode_default_false() {
1145        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1146        assert!(!config.production);
1147    }
1148
1149    #[test]
1150    fn deserialize_json_production_mode_true() {
1151        let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
1152        assert!(config.production);
1153    }
1154
1155    #[test]
1156    fn deserialize_json_per_analysis_production_mode() {
1157        let config: FallowConfig = serde_json::from_str(
1158            r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
1159        )
1160        .unwrap();
1161        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1162        assert!(config.production.for_analysis(ProductionAnalysis::Health));
1163        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1164    }
1165
1166    #[test]
1167    fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
1168        let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
1169            .unwrap_err();
1170        assert!(
1171            err.to_string().contains("healthTypo"),
1172            "error should name the unknown field: {err}"
1173        );
1174    }
1175
1176    #[test]
1177    fn deserialize_json_dynamically_loaded() {
1178        let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
1179        let config: FallowConfig = serde_json::from_str(json).unwrap();
1180        assert_eq!(
1181            config.dynamically_loaded,
1182            vec!["plugins/**/*.ts", "locales/**/*.json"]
1183        );
1184    }
1185
1186    #[test]
1187    fn deserialize_json_dynamically_loaded_defaults_empty() {
1188        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1189        assert!(config.dynamically_loaded.is_empty());
1190    }
1191
1192    #[test]
1193    fn deserialize_json_fix_catalog_delete_preceding_comments() {
1194        let config: FallowConfig =
1195            serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
1196                .unwrap();
1197        assert_eq!(
1198            config.fix.catalog.delete_preceding_comments,
1199            CatalogPrecedingCommentPolicy::Always
1200        );
1201    }
1202
1203    #[test]
1204    fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
1205        let err = serde_json::from_str::<FallowConfig>(
1206            r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
1207        )
1208        .unwrap_err();
1209        assert!(
1210            err.to_string().contains("sometimes"),
1211            "error should name the bad policy: {err}"
1212        );
1213    }
1214
1215    #[test]
1216    fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1217        let json = r#"{
1218            "usedClassMembers": [
1219                "agInit",
1220                { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1221                { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1222            ]
1223        }"#;
1224        let config: FallowConfig = serde_json::from_str(json).unwrap();
1225        assert_eq!(
1226            config.used_class_members,
1227            vec![
1228                UsedClassMemberRule::from("agInit"),
1229                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1230                    extends: None,
1231                    implements: Some("ICellRendererAngularComp".to_string()),
1232                    members: vec!["refresh".to_string()],
1233                }),
1234                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1235                    extends: Some("BaseCommand".to_string()),
1236                    implements: Some("CanActivate".to_string()),
1237                    members: vec!["execute".to_string()],
1238                }),
1239            ]
1240        );
1241    }
1242
1243    #[test]
1244    fn deserialize_toml_minimal() {
1245        let toml_str = r#"
1246entry = ["src/index.ts"]
1247production = true
1248"#;
1249        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1250        assert_eq!(config.entry, vec!["src/index.ts"]);
1251        assert!(config.production);
1252    }
1253
1254    #[test]
1255    fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1256        // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1257        // key; the back-compat serde alias keeps those existing configs scoping
1258        // instead of silently dropping the (unknown) key and losing the patterns.
1259        let config: FallowConfig =
1260            toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1261        assert_eq!(
1262            config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1263            vec!["packages/*".to_string(), "apps/*".to_string()],
1264            "the `packages` alias must populate `patterns`"
1265        );
1266    }
1267
1268    #[test]
1269    fn deserialize_toml_per_analysis_production_mode() {
1270        let toml_str = r"
1271[production]
1272deadCode = false
1273health = true
1274dupes = false
1275";
1276        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1277        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1278        assert!(config.production.for_analysis(ProductionAnalysis::Health));
1279        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1280    }
1281
1282    #[test]
1283    fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1284        let err = toml::from_str::<FallowConfig>(
1285            r"
1286[production]
1287healthTypo = true
1288",
1289        )
1290        .unwrap_err();
1291        assert!(
1292            err.to_string().contains("healthTypo"),
1293            "error should name the unknown field: {err}"
1294        );
1295    }
1296
1297    #[test]
1298    fn deserialize_toml_with_inline_framework() {
1299        let toml_str = r#"
1300[[framework]]
1301name = "my-framework"
1302enablers = ["my-framework-pkg"]
1303entryPoints = ["src/routes/**/*.tsx"]
1304"#;
1305        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1306        assert_eq!(config.framework.len(), 1);
1307        assert_eq!(config.framework[0].name, "my-framework");
1308        assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1309        assert_eq!(
1310            config.framework[0].entry_points,
1311            vec!["src/routes/**/*.tsx"]
1312        );
1313    }
1314
1315    #[test]
1316    fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1317        let toml_str = r#"
1318[fix.catalog]
1319deletePrecedingComments = "never"
1320"#;
1321        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1322        assert_eq!(
1323            config.fix.catalog.delete_preceding_comments,
1324            CatalogPrecedingCommentPolicy::Never
1325        );
1326    }
1327
1328    #[test]
1329    fn deserialize_toml_with_workspace_config() {
1330        let toml_str = r#"
1331[workspaces]
1332patterns = ["packages/*", "apps/*"]
1333[workspaces.changedSince]
1334"packages/web" = "main"
1335"packages/legacy" = "release/2024.10"
1336"#;
1337        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1338        assert!(config.workspaces.is_some());
1339        let ws = config.workspaces.unwrap();
1340        assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1341        assert_eq!(ws.changed_since["packages/web"], "main");
1342        assert_eq!(ws.changed_since["packages/legacy"], "release/2024.10");
1343    }
1344
1345    #[test]
1346    fn deserialize_toml_with_ignore_exports() {
1347        let toml_str = r#"
1348[[ignoreExports]]
1349file = "src/types/**/*.ts"
1350exports = ["*"]
1351"#;
1352        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1353        assert_eq!(config.ignore_exports.len(), 1);
1354        assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1355        assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1356    }
1357
1358    #[test]
1359    fn deserialize_toml_used_class_members_supports_scoped_rules() {
1360        let toml_str = r#"
1361usedClassMembers = [
1362  { implements = "ICellRendererAngularComp", members = ["refresh"] },
1363  { extends = "BaseCommand", members = ["execute"] },
1364]
1365"#;
1366        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1367        assert_eq!(
1368            config.used_class_members,
1369            vec![
1370                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1371                    extends: None,
1372                    implements: Some("ICellRendererAngularComp".to_string()),
1373                    members: vec!["refresh".to_string()],
1374                }),
1375                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1376                    extends: Some("BaseCommand".to_string()),
1377                    implements: None,
1378                    members: vec!["execute".to_string()],
1379                }),
1380            ]
1381        );
1382    }
1383
1384    #[test]
1385    fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1386        let result = serde_json::from_str::<FallowConfig>(
1387            r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1388        );
1389        assert!(
1390            result.is_err(),
1391            "unconstrained scoped rule should be rejected"
1392        );
1393    }
1394
1395    #[test]
1396    fn deserialize_ignore_exports_used_in_file_bool() {
1397        let config: FallowConfig =
1398            serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1399
1400        assert!(config.ignore_exports_used_in_file.suppresses(false));
1401        assert!(config.ignore_exports_used_in_file.suppresses(true));
1402    }
1403
1404    #[test]
1405    fn deserialize_effect_schema_exports_as_types() {
1406        let default: FallowConfig = serde_json::from_str("{}").unwrap();
1407        assert!(!default.effect.schema_exports_as_types);
1408        assert!(
1409            !serde_json::to_string(&default)
1410                .unwrap()
1411                .contains("\"effect\""),
1412            "the default section is not serialized"
1413        );
1414
1415        let config: FallowConfig =
1416            serde_json::from_str(r#"{"effect":{"schemaExportsAsTypes":true}}"#).unwrap();
1417        assert!(config.effect.schema_exports_as_types);
1418
1419        let toml: FallowConfig = toml::from_str("[effect]\nschemaExportsAsTypes = true\n").unwrap();
1420        assert!(toml.effect.schema_exports_as_types);
1421
1422        let typo = serde_json::from_str::<FallowConfig>(r#"{"effect":{"schemaExports":true}}"#);
1423        assert!(typo.is_err(), "an unknown effect key fails the load");
1424    }
1425
1426    #[test]
1427    fn deserialize_ignore_exports_used_in_file_kind_form() {
1428        let config: FallowConfig =
1429            serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1430
1431        assert!(!config.ignore_exports_used_in_file.suppresses(false));
1432        assert!(config.ignore_exports_used_in_file.suppresses(true));
1433    }
1434
1435    #[test]
1436    fn deserialize_toml_deny_unknown_fields() {
1437        let toml_str = r"bogus_field = true";
1438        let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1439        assert!(result.is_err(), "unknown fields should be rejected");
1440    }
1441
1442    #[test]
1443    fn json_serialize_roundtrip() {
1444        let config = FallowConfig {
1445            entry: vec!["src/main.ts".to_string()],
1446            production: true.into(),
1447            ..FallowConfig::default()
1448        };
1449        let json = serde_json::to_string(&config).unwrap();
1450        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1451        assert_eq!(restored.entry, vec!["src/main.ts"]);
1452        assert!(restored.production);
1453    }
1454
1455    #[test]
1456    fn schema_field_not_serialized() {
1457        let config = FallowConfig {
1458            schema: Some("https://example.com/schema.json".to_string()),
1459            ..FallowConfig::default()
1460        };
1461        let json = serde_json::to_string(&config).unwrap();
1462        assert!(
1463            !json.contains("$schema"),
1464            "schema field should be skipped in serialization"
1465        );
1466    }
1467
1468    #[test]
1469    fn extends_field_not_serialized() {
1470        let config = FallowConfig {
1471            extends: vec!["base.json".to_string()],
1472            ..FallowConfig::default()
1473        };
1474        let json = serde_json::to_string(&config).unwrap();
1475        assert!(
1476            !json.contains("extends"),
1477            "extends field should be skipped in serialization"
1478        );
1479    }
1480
1481    #[test]
1482    fn regression_config_deserialize_json() {
1483        let json = r#"{
1484            "regression": {
1485                "baseline": {
1486                    "totalIssues": 42,
1487                    "unusedFiles": 10,
1488                    "unusedExports": 5,
1489                    "circularDependencies": 2
1490                }
1491            }
1492        }"#;
1493        let config: FallowConfig = serde_json::from_str(json).unwrap();
1494        let regression = config.regression.unwrap();
1495        let baseline = regression.baseline.unwrap();
1496        assert_eq!(baseline.total_issues, 42);
1497        assert_eq!(baseline.unused_files, 10);
1498        assert_eq!(baseline.unused_exports, 5);
1499        assert_eq!(baseline.circular_dependencies, 2);
1500        assert_eq!(baseline.unused_types, 0);
1501        assert_eq!(baseline.boundary_violations, 0);
1502    }
1503
1504    #[test]
1505    fn regression_config_defaults_to_none() {
1506        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1507        assert!(config.regression.is_none());
1508    }
1509
1510    #[test]
1511    fn regression_baseline_all_zeros_by_default() {
1512        let baseline = RegressionBaseline::default();
1513        assert_eq!(baseline.total_issues, 0);
1514        assert_eq!(baseline.unused_files, 0);
1515        assert_eq!(baseline.unused_exports, 0);
1516        assert_eq!(baseline.unused_types, 0);
1517        assert_eq!(baseline.unused_dependencies, 0);
1518        assert_eq!(baseline.unused_dev_dependencies, 0);
1519        assert_eq!(baseline.unused_optional_dependencies, 0);
1520        assert_eq!(baseline.unused_enum_members, 0);
1521        assert_eq!(baseline.unused_class_members, 0);
1522        assert_eq!(baseline.unresolved_imports, 0);
1523        assert_eq!(baseline.unlisted_dependencies, 0);
1524        assert_eq!(baseline.duplicate_exports, 0);
1525        assert_eq!(baseline.circular_dependencies, 0);
1526        assert_eq!(baseline.type_only_dependencies, 0);
1527        assert_eq!(baseline.test_only_dependencies, 0);
1528        assert_eq!(baseline.boundary_violations, 0);
1529    }
1530
1531    #[test]
1532    fn regression_config_serialize_roundtrip() {
1533        let baseline = RegressionBaseline {
1534            total_issues: 100,
1535            unused_files: 20,
1536            unused_exports: 30,
1537            ..RegressionBaseline::default()
1538        };
1539        let regression = RegressionConfig {
1540            baseline: Some(baseline),
1541        };
1542        let config = FallowConfig {
1543            regression: Some(regression),
1544            ..FallowConfig::default()
1545        };
1546        let json = serde_json::to_string(&config).unwrap();
1547        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1548        let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1549        assert_eq!(restored_baseline.total_issues, 100);
1550        assert_eq!(restored_baseline.unused_files, 20);
1551        assert_eq!(restored_baseline.unused_exports, 30);
1552        assert_eq!(restored_baseline.unused_types, 0);
1553    }
1554
1555    #[test]
1556    fn regression_config_empty_baseline_deserialize() {
1557        let json = r#"{"regression": {}}"#;
1558        let config: FallowConfig = serde_json::from_str(json).unwrap();
1559        let regression = config.regression.unwrap();
1560        assert!(regression.baseline.is_none());
1561    }
1562
1563    #[test]
1564    fn regression_baseline_not_serialized_when_none() {
1565        let config = FallowConfig {
1566            regression: None,
1567            ..FallowConfig::default()
1568        };
1569        let json = serde_json::to_string(&config).unwrap();
1570        assert!(
1571            !json.contains("regression"),
1572            "regression should be skipped when None"
1573        );
1574    }
1575
1576    #[test]
1577    fn deserialize_json_with_overrides() {
1578        let json = r#"{
1579            "overrides": [
1580                {
1581                    "files": ["*.test.ts", "*.spec.ts"],
1582                    "rules": {
1583                        "unused-exports": "off",
1584                        "unused-files": "warn"
1585                    }
1586                }
1587            ]
1588        }"#;
1589        let config: FallowConfig = serde_json::from_str(json).unwrap();
1590        assert_eq!(config.overrides.len(), 1);
1591        assert_eq!(config.overrides[0].files.len(), 2);
1592        assert_eq!(
1593            config.overrides[0].rules.unused_exports,
1594            Some(Severity::Off)
1595        );
1596        assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1597    }
1598
1599    #[test]
1600    fn deserialize_json_with_boundaries() {
1601        let json = r#"{
1602            "boundaries": {
1603                "preset": "layered"
1604            }
1605        }"#;
1606        let config: FallowConfig = serde_json::from_str(json).unwrap();
1607        assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1608    }
1609
1610    #[test]
1611    fn deserialize_toml_with_regression_baseline() {
1612        let toml_str = r"
1613[regression.baseline]
1614totalIssues = 50
1615unusedFiles = 10
1616unusedExports = 15
1617";
1618        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1619        let baseline = config.regression.unwrap().baseline.unwrap();
1620        assert_eq!(baseline.total_issues, 50);
1621        assert_eq!(baseline.unused_files, 10);
1622        assert_eq!(baseline.unused_exports, 15);
1623    }
1624
1625    #[test]
1626    fn deserialize_toml_with_overrides() {
1627        let toml_str = r#"
1628[[overrides]]
1629files = ["*.test.ts"]
1630
1631[overrides.rules]
1632unused-exports = "off"
1633
1634[[overrides]]
1635files = ["*.stories.tsx"]
1636
1637[overrides.rules]
1638unused-files = "off"
1639"#;
1640        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1641        assert_eq!(config.overrides.len(), 2);
1642        assert_eq!(
1643            config.overrides[0].rules.unused_exports,
1644            Some(Severity::Off)
1645        );
1646        assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1647    }
1648
1649    #[test]
1650    fn regression_config_default_is_none_baseline() {
1651        let config = RegressionConfig::default();
1652        assert!(config.baseline.is_none());
1653    }
1654
1655    #[test]
1656    fn deserialize_json_multiple_ignore_export_rules() {
1657        let json = r#"{
1658            "ignoreExports": [
1659                {"file": "src/types/**/*.ts", "exports": ["*"]},
1660                {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1661                {"file": "src/index.ts", "exports": ["default"]}
1662            ]
1663        }"#;
1664        let config: FallowConfig = serde_json::from_str(json).unwrap();
1665        assert_eq!(config.ignore_exports.len(), 3);
1666        assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1667    }
1668
1669    #[test]
1670    fn deserialize_json_public_packages_camel_case() {
1671        let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1672        let config: FallowConfig = serde_json::from_str(json).unwrap();
1673        assert_eq!(
1674            config.public_packages,
1675            vec!["@myorg/shared-lib", "@myorg/utils"]
1676        );
1677    }
1678
1679    #[test]
1680    fn deserialize_json_public_packages_rejects_snake_case() {
1681        let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1682        let result: Result<FallowConfig, _> = serde_json::from_str(json);
1683        assert!(
1684            result.is_err(),
1685            "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1686        );
1687    }
1688
1689    #[test]
1690    fn deserialize_json_public_packages_empty() {
1691        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1692        assert!(config.public_packages.is_empty());
1693    }
1694
1695    #[test]
1696    fn deserialize_toml_public_packages() {
1697        let toml_str = r#"
1698publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1699"#;
1700        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1701        assert_eq!(
1702            config.public_packages,
1703            vec!["@myorg/shared-lib", "@myorg/ui"]
1704        );
1705    }
1706
1707    #[test]
1708    fn public_packages_serialize_roundtrip() {
1709        let config = FallowConfig {
1710            public_packages: vec!["@myorg/shared-lib".to_string()],
1711            ..FallowConfig::default()
1712        };
1713        let json = serde_json::to_string(&config).unwrap();
1714        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1715        assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1716    }
1717}