Skip to main content

fallow_config/config/
health.rs

1use std::path::PathBuf;
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6const fn default_max_cyclomatic() -> u16 {
7    20
8}
9
10const fn default_max_cognitive() -> u16 {
11    15
12}
13
14/// Savoia and Evans (2007) canonical CRAP threshold: CC=5 untested gives
15/// exactly `5^2 + 5 = 30`, marking the boundary where refactoring or test
16/// coverage becomes recommended.
17const fn default_max_crap() -> f64 {
18    30.0
19}
20
21const fn default_crap_refactor_band() -> u16 {
22    5
23}
24
25/// SIG unit-size "very high risk" boundary: functions over 60 lines of code.
26/// This is the default line-count threshold above which a function is reported
27/// as an oversized "large function".
28const fn default_max_unit_size() -> u32 {
29    60
30}
31
32#[expect(
33    clippy::trivially_copy_pass_by_ref,
34    reason = "serde skip_serializing_if passes a reference"
35)]
36const fn is_zero_u32(value: &u32) -> bool {
37    *value == 0
38}
39
40/// Default for `suggest_inline_suppression`: emit `suppress-line` actions
41/// alongside health findings unless a baseline is active or the team has
42/// opted out via config.
43const fn default_suggest_inline_suppression() -> bool {
44    true
45}
46
47/// Default for `inline_threshold_overrides`: the comment form applies.
48const fn default_inline_threshold_overrides() -> bool {
49    true
50}
51
52/// Default bot/service-account author patterns filtered from ownership metrics.
53///
54/// Matches common CI bot signatures and service-account naming conventions.
55/// Users can extend via `health.ownership.botPatterns` in config.
56///
57/// Note on `[bot]` matching: globset treats `[abc]` as a character class.
58/// To match the literal `[bot]` substring (used by GitHub App bots), escape
59/// the brackets as `\[bot\]`.
60///
61/// `*noreply*` is intentionally NOT a default. Most human GitHub contributors
62/// commit from `<id>+<handle>@users.noreply.github.com` addresses (GitHub's
63/// privacy default). Filtering on `noreply` would silently exclude the
64/// majority of real authors. The actual bot accounts already match via the
65/// `\[bot\]` literal (e.g., `github-actions[bot]@users.noreply.github.com`).
66fn default_bot_patterns() -> Vec<String> {
67    vec![
68        r"*\[bot\]*".to_string(),
69        "dependabot*".to_string(),
70        "renovate*".to_string(),
71        "github-actions*".to_string(),
72        "svc-*".to_string(),
73        "*-service-account*".to_string(),
74    ]
75}
76
77const fn default_email_mode() -> EmailMode {
78    EmailMode::Handle
79}
80
81/// Privacy mode for author emails emitted in ownership output.
82///
83/// Defaults to `handle` (local-part only, no domain) so SARIF and JSON
84/// artifacts do not leak raw email addresses into CI pipelines.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
86#[serde(rename_all = "kebab-case")]
87pub enum EmailMode {
88    /// Show the raw email address as it appears in git history.
89    /// Use for public repositories where history is already exposed.
90    Raw,
91    /// Show the local-part only (before the `@`). Mailmap-resolved where possible.
92    /// Default. Balances readability and privacy.
93    Handle,
94    /// Show a stable `xxh3:<16hex>` pseudonym derived from the raw email.
95    /// Non-cryptographic; suitable to keep raw emails out of CI artifacts
96    /// (SARIF, code-scanning uploads) but not as a security primitive:
97    /// a known list of org emails can be brute-forced into a rainbow table.
98    /// Use in regulated environments where even local-parts are sensitive.
99    Anonymized,
100    /// Older spelling of `anonymized`.
101    Hash,
102}
103
104/// Configuration for ownership analysis (`fallow health --hotspots --ownership`).
105#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
106#[serde(rename_all = "camelCase")]
107pub struct OwnershipConfig {
108    /// Glob patterns that identify bot or service-account commits to exclude
109    /// from ownership signals. A pattern matches the local part of the author
110    /// email or the full author value. Overrides the defaults entirely when set.
111    #[serde(default = "default_bot_patterns")]
112    pub bot_patterns: Vec<String>,
113
114    /// Privacy mode for emitted author emails. Defaults to `handle`.
115    /// Override on the CLI via `--ownership-emails=raw|handle|anonymized`.
116    /// The legacy spelling `hash` is still accepted for compatibility.
117    #[serde(default = "default_email_mode")]
118    pub email_mode: EmailMode,
119}
120
121impl Default for OwnershipConfig {
122    fn default() -> Self {
123        Self {
124            bot_patterns: default_bot_patterns(),
125            email_mode: default_email_mode(),
126        }
127    }
128}
129
130/// Thresholds for change coupling (`change_coupling` in `fallow health`).
131///
132/// The defaults are the Code Maat defaults. A pair of files is hidden coupling
133/// when each file has `minRevisions` commits, the pair shares
134/// `minSharedRevisions` commits, the coupling degree reaches `minDegree`, and
135/// no import or re-export chain connects the two files.
136#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, JsonSchema)]
137#[serde(deny_unknown_fields, rename_all = "camelCase")]
138pub struct ChangeCouplingConfig {
139    /// Skip a commit that changes more analyzed files than this (default:
140    /// 30, from 2 to 1000). Bulk commits (renames, format passes) create
141    /// false pairs. The upper bound keeps the pair count of one commit small.
142    #[serde(default = "default_coupling_max_files_per_commit")]
143    #[schemars(range(min = 2, max = 1000))]
144    pub max_files_per_commit: usize,
145    /// Minimum commits for each file of a pair (default: 5).
146    #[serde(default = "default_coupling_min_revisions")]
147    pub min_revisions: u32,
148    /// Minimum commits that change both files of a pair (default: 5).
149    #[serde(default = "default_coupling_min_shared_revisions")]
150    pub min_shared_revisions: u32,
151    /// Minimum coupling degree, from 0 to 1 (default: 0.3). The degree is the
152    /// number of shared commits divided by the mean commit count of the two
153    /// files.
154    #[serde(default = "default_coupling_min_degree")]
155    #[schemars(range(min = 0.0, max = 1.0))]
156    pub min_degree: f64,
157}
158
159const fn default_coupling_max_files_per_commit() -> usize {
160    30
161}
162
163const fn default_coupling_min_revisions() -> u32 {
164    5
165}
166
167const fn default_coupling_min_shared_revisions() -> u32 {
168    5
169}
170
171const fn default_coupling_min_degree() -> f64 {
172    0.3
173}
174
175/// Smallest `maxFilesPerCommit`: a commit needs two files to form a pair.
176const MIN_COUPLING_FILES_PER_COMMIT: usize = 2;
177
178/// Largest `maxFilesPerCommit`. A commit with `n` files gives `n * (n - 1) / 2`
179/// pairs, so a higher value lets one bulk commit dominate the run time.
180const MAX_COUPLING_FILES_PER_COMMIT: usize = 1000;
181
182impl ChangeCouplingConfig {
183    /// Validate the ranges that serde cannot express.
184    #[must_use]
185    pub fn errors(&self) -> Vec<String> {
186        let mut errors = Vec::new();
187        if !(MIN_COUPLING_FILES_PER_COMMIT..=MAX_COUPLING_FILES_PER_COMMIT)
188            .contains(&self.max_files_per_commit)
189        {
190            errors.push(format!(
191                "health.changeCoupling.maxFilesPerCommit must be from {MIN_COUPLING_FILES_PER_COMMIT} to {MAX_COUPLING_FILES_PER_COMMIT}, found {}",
192                self.max_files_per_commit
193            ));
194        }
195        if !(0.0..=1.0).contains(&self.min_degree) {
196            errors.push(format!(
197                "health.changeCoupling.minDegree must be from 0 to 1, found {}",
198                self.min_degree
199            ));
200        }
201        errors
202    }
203}
204
205impl Default for ChangeCouplingConfig {
206    fn default() -> Self {
207        Self {
208            max_files_per_commit: default_coupling_max_files_per_commit(),
209            min_revisions: default_coupling_min_revisions(),
210            min_shared_revisions: default_coupling_min_shared_revisions(),
211            min_degree: default_coupling_min_degree(),
212        }
213    }
214}
215
216/// Settings for the shallow directories section
217/// (`fallow health --shallow-directories`).
218///
219/// A directory is shallow when files outside it use at least as many of its
220/// interface items as it keeps inside, and it shows at least `minInterface`
221/// items.
222#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
223#[serde(deny_unknown_fields, rename_all = "camelCase")]
224pub struct ShallowDirectoriesConfig {
225    /// Minimum number of interface items that files outside a directory use
226    /// before the directory can be shallow (default: 8, at least 1).
227    #[serde(default = "default_shallow_min_interface")]
228    #[schemars(range(min = 1))]
229    pub min_interface: u32,
230    /// Glob patterns for directories to leave out of the section, relative to
231    /// the project root (for example `src/generated` or `src/api/**`). A
232    /// pattern matches the directory path, not the files in it.
233    #[serde(default)]
234    pub ignore: Vec<String>,
235}
236
237const fn default_shallow_min_interface() -> u32 {
238    8
239}
240
241impl Default for ShallowDirectoriesConfig {
242    fn default() -> Self {
243        Self {
244            min_interface: default_shallow_min_interface(),
245            ignore: Vec::new(),
246        }
247    }
248}
249
250impl ShallowDirectoriesConfig {
251    /// Validate the ranges that serde cannot express.
252    #[must_use]
253    pub fn errors(&self) -> Vec<String> {
254        if self.min_interface == 0 {
255            return vec![
256                "health.shallowDirectories.minInterface must be at least 1, found 0".to_string(),
257            ];
258        }
259        Vec::new()
260    }
261}
262
263/// How `fallow health` counts cyclomatic complexity for its gates.
264///
265/// The policy changes the cyclomatic value that the `maxCyclomatic` gate reads
266/// and the cyclomatic value in every CRAP score. It does not change the health
267/// score, the complexity density, or the hotspot ranking: those keep the
268/// standard count so that grades stay comparable across projects.
269#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
270#[serde(rename_all = "kebab-case")]
271pub enum CyclomaticPolicy {
272    /// Count every decision point, `&&`, `||`, and `??` operator (`McCabe`).
273    #[default]
274    Standard,
275    /// Count a literal membership chain as one predicate. A chain such as
276    /// `kind === "a" || kind === "b" || kind === "c"` adds no cyclomatic
277    /// increments for its `||` operators. Only strict equality checks of one
278    /// identifier against string, number, bigint, boolean, or `null` literals
279    /// qualify. Member access, calls, mixed operators, and different operands
280    /// keep the standard count.
281    LiteralMembership,
282}
283
284impl CyclomaticPolicy {
285    /// Whether this is the default `standard` policy.
286    #[must_use]
287    pub const fn is_standard(&self) -> bool {
288        matches!(self, Self::Standard)
289    }
290}
291
292/// Configuration for complexity health metrics (`fallow health`).
293#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
294#[serde(deny_unknown_fields, rename_all = "camelCase")]
295pub struct HealthConfig {
296    /// Maximum allowed cyclomatic complexity per function (default: 20).
297    /// Functions exceeding this threshold are reported. Governs findings
298    /// only; the health score's complexity penalties use fixed calibration
299    /// (use `health.ignore` to remove a file from the score).
300    #[serde(default = "default_max_cyclomatic")]
301    pub max_cyclomatic: u16,
302
303    /// How the cyclomatic gate counts complexity (default: `standard`).
304    /// `literal-membership` counts a chain of strict equality checks of one
305    /// identifier against primitive literals (`kind === "a" || kind === "b"`)
306    /// as one predicate. The policy applies to the `maxCyclomatic` gate and
307    /// to every CRAP score, so the `maxCrap` gate reads the same value.
308    /// Findings then report the standard value as `standard_cyclomatic`. The
309    /// health score, complexity density, and hotspots keep the standard
310    /// count. Older fallow versions reject this key as unknown, so pair it
311    /// with `minimumVersion`.
312    #[serde(default, skip_serializing_if = "CyclomaticPolicy::is_standard")]
313    pub cyclomatic_policy: CyclomaticPolicy,
314
315    /// Maximum allowed cognitive complexity per function (default: 15).
316    /// Functions exceeding this threshold are reported. Governs findings
317    /// only, never the health score.
318    #[serde(default = "default_max_cognitive")]
319    pub max_cognitive: u16,
320
321    /// Maximum allowed CRAP (Change Risk Anti-Patterns) score per function
322    /// (default: 30.0). CRAP combines cyclomatic complexity with test
323    /// coverage: high complexity plus low coverage produces a high CRAP
324    /// score. Functions meeting or exceeding this threshold are reported.
325    /// Use `--coverage` with Istanbul data for accurate per-function CRAP;
326    /// otherwise fallow estimates coverage from the module graph. Governs
327    /// findings and the threshold-relative file-score signals
328    /// (`crap_above_threshold`, the `risk` triage tag, and the
329    /// `add_test_coverage` refactoring target); measured values such as
330    /// `crap_max` and the overall health score never move with it. Set to
331    /// `0` to disable CRAP enforcement entirely: no findings, nothing counts
332    /// above threshold, and file-score rows disclose baseline breaches as
333    /// exempt instead. The `complexity-crap` rule is different: it decides if
334    /// a finding fails the run, and `off` hides the findings but keeps the
335    /// file-score signals.
336    #[serde(default = "default_max_crap")]
337    pub max_crap: f64,
338
339    /// Band below `maxCyclomatic` where CRAP-only findings also receive a
340    /// secondary `refactor-function` action (default: 5). Set to `0` to only
341    /// suggest refactoring when cyclomatic already meets the configured
342    /// threshold.
343    #[serde(default = "default_crap_refactor_band")]
344    pub crap_refactor_band: u16,
345
346    /// Maximum function length in lines of code before it is reported as an
347    /// oversized "large function" (default: 60). Raise it globally, or per file
348    /// via `thresholdOverrides[].maxUnitSize`, to relax the bar for generated or
349    /// test files (where a `describe()` block spans hundreds of lines) without
350    /// disabling complexity checks on those files. This filters the reported
351    /// large-functions list only; the descriptive unit-size profile and the
352    /// health score still reflect raw sizes against fixed calibration (the
353    /// `unit_size` penalty keeps its `>60` LOC very-high-risk edge so grades
354    /// stay comparable across projects; use `health.ignore` to remove a file
355    /// from the score entirely).
356    #[serde(default = "default_max_unit_size")]
357    pub max_unit_size: u32,
358
359    /// Maximum file length in physical lines before the file is reported as a
360    /// complexity finding with `exceeded: "file_lines"` (default: `0`, off).
361    /// Every line counts, also blank lines and comment lines. A final newline
362    /// does not add a line. Set a limit such as `500` to enable the check, and
363    /// raise it per file via `thresholdOverrides[].maxFileLines`. The
364    /// `complexity-file-lines` rule decides if a finding fails the run. In
365    /// `fallow audit`, a long file that did not grow stays inherited. Older
366    /// fallow versions reject this key as unknown, so pair it with
367    /// `minimumVersion`.
368    #[serde(default, skip_serializing_if = "is_zero_u32")]
369    pub max_file_lines: u32,
370
371    /// Path to Istanbul coverage data (coverage-final.json) or raw V8 coverage
372    /// (a `NODE_V8_COVERAGE` directory or one V8 JSON file) for accurate
373    /// per-function CRAP scores. A relative path is taken from the project
374    /// root. A relative or absolute path may name a file up to the project
375    /// scope base (the git top level of the root); use the CLI flag for a
376    /// file outside the project. The CLI
377    /// `--coverage` flag and `FALLOW_COVERAGE` environment variable override
378    /// this value. Consulted by `fallow health`, bare `fallow`, `fallow audit`,
379    /// `fallow viz`, and the MCP `audit` / `check_health` tools.
380    #[serde(default)]
381    pub coverage: Option<PathBuf>,
382
383    /// Absolute prefix to strip from Istanbul file paths before CRAP matching.
384    /// Use when coverage was generated under a different checkout root in CI
385    /// or Docker. The CLI `--coverage-root` flag and `FALLOW_COVERAGE_ROOT`
386    /// environment variable override this value. Consulted by `fallow health`,
387    /// bare `fallow`, `fallow audit`, `fallow viz`, and the MCP `audit` /
388    /// `check_health` tools.
389    #[serde(default)]
390    pub coverage_root: Option<PathBuf>,
391
392    /// Glob patterns to exclude from complexity analysis.
393    /// A single `*` stays within one path segment; use `**` to match across directories.
394    #[serde(default)]
395    pub ignore: Vec<String>,
396
397    /// Regular expressions excluding Tailwind arbitrary-value utilities from
398    /// token-drift findings and analytics, including CVA variants. Matches the
399    /// normalized `prefix-[value]` token, without variants, negative signs, or
400    /// suffix modifiers. Both `-mt-[7px]` and `mt-[7px]` match as `mt-[7px]`;
401    /// `bg-[#abc]/50` matches as `bg-[#abc]`. These spellings cannot be excluded
402    /// independently. Use `^icon-\[` to exclude Iconify tokens, including variants.
403    /// Defaults to no exclusions. Invalid regexes fail config loading.
404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
405    pub tailwind_ignore_patterns: Vec<String>,
406
407    /// Per-file or per-function threshold overrides. These keep exceptional
408    /// functions visible as configured numeric ceilings instead of hiding them
409    /// behind binary suppressions.
410    #[serde(default, skip_serializing_if = "Vec::is_empty")]
411    pub threshold_overrides: Vec<HealthThresholdOverride>,
412
413    /// Ownership analysis configuration. Controls bot filtering and email
414    /// privacy mode for `--ownership` output.
415    #[serde(default)]
416    pub ownership: OwnershipConfig,
417
418    /// Change coupling thresholds for the `change_coupling` section and the
419    /// hidden-coupling refactoring targets. Older fallow versions reject this
420    /// key as unknown, so pair it with `minimumVersion` set to the release
421    /// that added it.
422    #[serde(default)]
423    pub change_coupling: ChangeCouplingConfig,
424
425    /// Settings for the shallow directories section
426    /// (`fallow health --shallow-directories`). Older fallow versions reject
427    /// this key as unknown, so pair it with `minimumVersion` set to the
428    /// release that added it.
429    #[serde(default)]
430    pub shallow_directories: ShallowDirectoriesConfig,
431
432    /// Whether health JSON output emits `suppress-line` action hints
433    /// alongside complexity findings (default: `true`). Set to `false` to
434    /// opt out across the project: useful for teams that manage suppressions
435    /// exclusively through `// fallow-ignore-*` comments authored by hand or
436    /// through the `fallow.suppress` LSP code action, but who do not want
437    /// CI-driven `suppress-line` action hints in their JSON output.
438    /// `--baseline` activates auto-omission regardless of this setting,
439    /// since baseline files are a separate suppression mechanism.
440    #[serde(default = "default_suggest_inline_suppression")]
441    pub suggest_inline_suppression: bool,
442
443    /// Whether `fallow-override-threshold-next-line` comments apply (default:
444    /// `true`). Such a comment sets the health ceilings of the function on
445    /// the next line, as in
446    /// `// fallow-override-threshold-next-line maxCognitive=40 -- reason`.
447    /// Set to `false` to keep every exception in `thresholdOverrides`: each
448    /// comment then has no effect and the report lists it as `disabled`.
449    #[serde(default = "default_inline_threshold_overrides")]
450    pub inline_threshold_overrides: bool,
451}
452
453impl Default for HealthConfig {
454    fn default() -> Self {
455        Self {
456            max_cyclomatic: default_max_cyclomatic(),
457            cyclomatic_policy: CyclomaticPolicy::Standard,
458            max_cognitive: default_max_cognitive(),
459            max_crap: default_max_crap(),
460            crap_refactor_band: default_crap_refactor_band(),
461            max_unit_size: default_max_unit_size(),
462            max_file_lines: 0,
463            coverage: None,
464            coverage_root: None,
465            ignore: vec![],
466            tailwind_ignore_patterns: vec![],
467            threshold_overrides: vec![],
468            ownership: OwnershipConfig::default(),
469            change_coupling: ChangeCouplingConfig::default(),
470            shallow_directories: ShallowDirectoriesConfig::default(),
471            suggest_inline_suppression: default_suggest_inline_suppression(),
472            inline_threshold_overrides: default_inline_threshold_overrides(),
473        }
474    }
475}
476
477/// Per-file or per-function health threshold override.
478#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
479#[serde(deny_unknown_fields, rename_all = "camelCase")]
480pub struct HealthThresholdOverride {
481    /// Project-root-relative file globs this override applies to.
482    /// A single `*` stays within one path segment; use `**` to match across directories.
483    pub files: Vec<String>,
484    /// Exact emitted function names this override applies to. Empty means every
485    /// function in matching files. Synthetic units are matched by their emitted
486    /// name, so `"<template>"` and `"<snippet:NAME>"` are valid keys. The
487    /// synthetic `"<module>"` unit is not: it carries a file's module-scope
488    /// decision points into the aggregate metrics and never produces a finding,
489    /// so there is no ceiling for an override to move.
490    #[serde(default, skip_serializing_if = "Vec::is_empty")]
491    pub functions: Vec<String>,
492    /// Local cyclomatic complexity ceiling.
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub max_cyclomatic: Option<u16>,
495    /// Local cognitive complexity ceiling.
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub max_cognitive: Option<u16>,
498    /// Local CRAP ceiling.
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub max_crap: Option<f64>,
501    /// Local unit-size ceiling: maximum function length in lines of code before
502    /// it is reported as an oversized "large function". Leave `functions` empty
503    /// to relax the bar for every function in the matching files (which covers
504    /// both the `describe()` wrapper and the individual `it()` blocks in a test
505    /// suite).
506    #[serde(default, skip_serializing_if = "Option::is_none")]
507    pub max_unit_size: Option<u32>,
508    /// Local file-length ceiling in physical lines. `0` turns the file-length
509    /// check off for the matching files. The ceiling applies to whole files,
510    /// so an entry that sets it must leave `functions` empty.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub max_file_lines: Option<u32>,
513    /// Human-readable rationale for the exception.
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub reason: Option<String>,
516}
517
518impl HealthThresholdOverride {
519    /// Return true when the override configures at least one local ceiling.
520    #[must_use]
521    pub const fn has_any_threshold(&self) -> bool {
522        self.max_cyclomatic.is_some()
523            || self.max_cognitive.is_some()
524            || self.max_crap.is_some()
525            || self.max_unit_size.is_some()
526            || self.max_file_lines.is_some()
527    }
528}
529
530impl HealthConfig {
531    /// Whether the file-length check can report a finding: the global
532    /// `maxFileLines` is above `0`, or an override sets a `maxFileLines`.
533    #[must_use]
534    pub fn file_lines_check_enabled(&self) -> bool {
535        self.max_file_lines > 0
536            || self
537                .threshold_overrides
538                .iter()
539                .any(|entry| entry.max_file_lines.is_some_and(|max| max > 0))
540    }
541
542    /// Validate semantic constraints that serde cannot express.
543    #[must_use]
544    pub fn threshold_override_errors(&self) -> Vec<String> {
545        let mut errors = Vec::new();
546        for (index, override_entry) in self.threshold_overrides.iter().enumerate() {
547            if override_entry.files.is_empty() {
548                errors.push(format!(
549                    "health.thresholdOverrides[{index}].files must contain at least one pattern"
550                ));
551            }
552            if !override_entry.has_any_threshold() {
553                errors.push(format!(
554                    "health.thresholdOverrides[{index}] must set at least one of maxCyclomatic, maxCognitive, maxCrap, maxUnitSize, or maxFileLines"
555                ));
556            }
557            if override_entry.max_file_lines.is_some() && !override_entry.functions.is_empty() {
558                errors.push(format!(
559                    "health.thresholdOverrides[{index}].maxFileLines applies to whole files; move it to an entry without functions"
560                ));
561            }
562        }
563        errors
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    #[test]
572    fn change_coupling_ranges_are_validated() {
573        assert!(ChangeCouplingConfig::default().errors().is_empty());
574        let at_bounds = ChangeCouplingConfig {
575            max_files_per_commit: 1000,
576            min_degree: 1.0,
577            ..ChangeCouplingConfig::default()
578        };
579        assert!(at_bounds.errors().is_empty());
580
581        for (max_files_per_commit, min_degree) in [(1, 0.3), (1001, 0.3), (30, -0.1), (30, 1.5)] {
582            let config = ChangeCouplingConfig {
583                max_files_per_commit,
584                min_degree,
585                ..ChangeCouplingConfig::default()
586            };
587            assert_eq!(
588                config.errors().len(),
589                1,
590                "maxFilesPerCommit {max_files_per_commit}, minDegree {min_degree}"
591            );
592        }
593        let nan = ChangeCouplingConfig {
594            min_degree: f64::NAN,
595            ..ChangeCouplingConfig::default()
596        };
597        assert_eq!(nan.errors().len(), 1);
598    }
599
600    #[test]
601    fn health_config_defaults() {
602        let config = HealthConfig::default();
603        assert_eq!(config.max_cyclomatic, 20);
604        assert_eq!(config.max_cognitive, 15);
605        assert!((config.max_crap - 30.0).abs() < f64::EPSILON);
606        assert_eq!(config.crap_refactor_band, 5);
607        assert_eq!(config.max_unit_size, 60);
608        assert!(config.coverage.is_none());
609        assert!(config.coverage_root.is_none());
610        assert!(config.ignore.is_empty());
611        assert!(config.threshold_overrides.is_empty());
612        assert_eq!(config.change_coupling.max_files_per_commit, 30);
613        assert_eq!(config.change_coupling.min_revisions, 5);
614        assert_eq!(config.change_coupling.min_shared_revisions, 5);
615        assert!((config.change_coupling.min_degree - 0.3).abs() < f64::EPSILON);
616        let ownership = OwnershipConfig::default();
617        assert_eq!(config.ownership.bot_patterns, ownership.bot_patterns);
618        assert_eq!(config.ownership.email_mode, ownership.email_mode);
619    }
620
621    #[test]
622    fn health_config_json_all_fields() {
623        let json = r#"{
624            "maxCyclomatic": 30,
625            "maxCognitive": 25,
626            "maxCrap": 50.0,
627            "crapRefactorBand": 3,
628            "coverage": "coverage/coverage-final.json",
629            "coverageRoot": "/ci/workspace",
630            "ignore": ["**/generated/**", "vendor/**"],
631            "thresholdOverrides": [{
632                "files": ["components/auth/src/index.ts"],
633                "functions": ["createAuthModule"],
634                "maxCognitive": 25,
635                "reason": "linear module assembly; agreed 2026-06"
636            }]
637        }"#;
638        let config: HealthConfig = serde_json::from_str(json).unwrap();
639        assert_eq!(config.max_cyclomatic, 30);
640        assert_eq!(config.max_cognitive, 25);
641        assert!((config.max_crap - 50.0).abs() < f64::EPSILON);
642        assert_eq!(config.crap_refactor_band, 3);
643        assert_eq!(
644            config.coverage,
645            Some(PathBuf::from("coverage/coverage-final.json"))
646        );
647        assert_eq!(config.coverage_root, Some(PathBuf::from("/ci/workspace")));
648        assert_eq!(config.ignore, vec!["**/generated/**", "vendor/**"]);
649        assert_eq!(config.threshold_overrides.len(), 1);
650        assert_eq!(
651            config.threshold_overrides[0].files,
652            vec!["components/auth/src/index.ts"]
653        );
654        assert_eq!(
655            config.threshold_overrides[0].functions,
656            vec!["createAuthModule"]
657        );
658        assert_eq!(config.threshold_overrides[0].max_cognitive, Some(25));
659    }
660
661    #[test]
662    fn health_config_json_partial_uses_defaults() {
663        let json = r#"{"maxCyclomatic": 10}"#;
664        let config: HealthConfig = serde_json::from_str(json).unwrap();
665        assert_eq!(config.max_cyclomatic, 10);
666        assert_eq!(config.max_cognitive, 15); // default
667        assert!((config.max_crap - 30.0).abs() < f64::EPSILON); // default
668        assert_eq!(config.crap_refactor_band, 5); // default
669        assert!(config.ignore.is_empty()); // default
670        assert!(config.threshold_overrides.is_empty()); // default
671    }
672
673    #[test]
674    fn health_config_json_only_max_crap() {
675        let json = r#"{"maxCrap": 15.5}"#;
676        let config: HealthConfig = serde_json::from_str(json).unwrap();
677        assert!((config.max_crap - 15.5).abs() < f64::EPSILON);
678        assert_eq!(config.max_cyclomatic, 20); // default
679        assert_eq!(config.cyclomatic_policy, CyclomaticPolicy::Standard);
680        assert_eq!(config.max_cognitive, 15); // default
681        assert_eq!(config.crap_refactor_band, 5); // default
682    }
683
684    #[test]
685    fn health_config_json_empty_object_uses_all_defaults() {
686        let config: HealthConfig = serde_json::from_str("{}").unwrap();
687        assert_eq!(config.max_cyclomatic, 20);
688        assert_eq!(config.max_cognitive, 15);
689        assert_eq!(config.crap_refactor_band, 5);
690        assert!(config.ignore.is_empty());
691        assert!(config.threshold_overrides.is_empty());
692    }
693
694    #[test]
695    fn health_config_json_only_ignore() {
696        let json = r#"{"ignore": ["test/**"]}"#;
697        let config: HealthConfig = serde_json::from_str(json).unwrap();
698        assert_eq!(config.max_cyclomatic, 20); // default
699        assert_eq!(config.max_cognitive, 15); // default
700        assert_eq!(config.ignore, vec!["test/**"]);
701        assert!(config.threshold_overrides.is_empty());
702    }
703
704    #[test]
705    fn health_config_toml_all_fields() {
706        let toml_str = r#"
707maxCyclomatic = 25
708maxCognitive = 20
709ignore = ["generated/**", "vendor/**"]
710
711[[thresholdOverrides]]
712files = ["src/auth.ts"]
713maxCognitive = 25
714"#;
715        let config: HealthConfig = toml::from_str(toml_str).unwrap();
716        assert_eq!(config.max_cyclomatic, 25);
717        assert_eq!(config.max_cognitive, 20);
718        assert_eq!(config.ignore, vec!["generated/**", "vendor/**"]);
719        assert_eq!(config.threshold_overrides.len(), 1);
720        assert_eq!(config.threshold_overrides[0].max_cognitive, Some(25));
721    }
722
723    #[test]
724    fn health_config_toml_defaults() {
725        let config: HealthConfig = toml::from_str("").unwrap();
726        assert_eq!(config.max_cyclomatic, 20);
727        assert_eq!(config.max_cognitive, 15);
728        assert!(config.ignore.is_empty());
729        assert!(config.threshold_overrides.is_empty());
730    }
731
732    #[test]
733    fn health_config_json_roundtrip() {
734        let config = HealthConfig {
735            max_cyclomatic: 50,
736            cyclomatic_policy: CyclomaticPolicy::LiteralMembership,
737            max_cognitive: 40,
738            max_crap: 75.0,
739            crap_refactor_band: 4,
740            max_unit_size: 120,
741            max_file_lines: 500,
742            ignore: vec!["test/**".to_string()],
743            tailwind_ignore_patterns: Vec::new(),
744            threshold_overrides: vec![HealthThresholdOverride {
745                files: vec!["src/auth.ts".to_string()],
746                functions: Vec::new(),
747                max_cyclomatic: Some(30),
748                max_cognitive: None,
749                max_crap: Some(45.0),
750                max_unit_size: None,
751                max_file_lines: None,
752                reason: Some("framework assembly".to_string()),
753            }],
754            coverage: None,
755            coverage_root: None,
756            ownership: OwnershipConfig::default(),
757            change_coupling: ChangeCouplingConfig {
758                min_degree: 0.4,
759                ..ChangeCouplingConfig::default()
760            },
761            shallow_directories: ShallowDirectoriesConfig::default(),
762            suggest_inline_suppression: false,
763            inline_threshold_overrides: false,
764        };
765        let json = serde_json::to_string(&config).unwrap();
766        let restored: HealthConfig = serde_json::from_str(&json).unwrap();
767        assert_eq!(restored.max_cyclomatic, 50);
768        assert_eq!(
769            restored.cyclomatic_policy,
770            CyclomaticPolicy::LiteralMembership
771        );
772        assert!((restored.change_coupling.min_degree - 0.4).abs() < f64::EPSILON);
773        assert_eq!(restored.max_cognitive, 40);
774        assert!((restored.max_crap - 75.0).abs() < f64::EPSILON);
775        assert_eq!(restored.crap_refactor_band, 4);
776        assert_eq!(restored.max_unit_size, 120);
777        assert_eq!(restored.max_file_lines, 500);
778        assert_eq!(restored.ignore, vec!["test/**"]);
779        assert_eq!(restored.threshold_overrides.len(), 1);
780        assert_eq!(restored.threshold_overrides[0].max_cyclomatic, Some(30));
781        assert_eq!(restored.threshold_overrides[0].max_crap, Some(45.0));
782        assert!(!restored.suggest_inline_suppression);
783        assert!(!restored.inline_threshold_overrides);
784        assert!(HealthConfig::default().inline_threshold_overrides);
785    }
786
787    #[test]
788    fn health_config_threshold_override_omitted_functions_matches_all() {
789        let json = r#"{
790            "thresholdOverrides": [{
791                "files": ["src/auth.ts"],
792                "maxCognitive": 25
793            }]
794        }"#;
795        let config: HealthConfig = serde_json::from_str(json).unwrap();
796        let override_entry = &config.threshold_overrides[0];
797        assert!(override_entry.functions.is_empty());
798        assert_eq!(override_entry.max_cognitive, Some(25));
799        assert!(config.threshold_override_errors().is_empty());
800    }
801
802    #[test]
803    fn health_config_threshold_override_validation_requires_files() {
804        let json = r#"{
805            "thresholdOverrides": [{
806                "files": [],
807                "maxCognitive": 25
808            }]
809        }"#;
810        let config: HealthConfig = serde_json::from_str(json).unwrap();
811        assert_eq!(
812            config.threshold_override_errors(),
813            vec!["health.thresholdOverrides[0].files must contain at least one pattern"]
814        );
815    }
816
817    #[test]
818    fn health_config_threshold_override_validation_requires_threshold() {
819        let json = r#"{
820            "thresholdOverrides": [{
821                "files": ["src/auth.ts"],
822                "reason": "temporary"
823            }]
824        }"#;
825        let config: HealthConfig = serde_json::from_str(json).unwrap();
826        assert_eq!(
827            config.threshold_override_errors(),
828            vec![
829                "health.thresholdOverrides[0] must set at least one of maxCyclomatic, maxCognitive, maxCrap, maxUnitSize, or maxFileLines"
830            ]
831        );
832    }
833
834    #[test]
835    fn health_config_threshold_override_max_unit_size_only_is_valid() {
836        let json = r#"{
837            "thresholdOverrides": [{
838                "files": ["**/*.test.*"],
839                "maxUnitSize": 500
840            }]
841        }"#;
842        let config: HealthConfig = serde_json::from_str(json).unwrap();
843        let override_entry = &config.threshold_overrides[0];
844        assert_eq!(override_entry.max_unit_size, Some(500));
845        assert!(override_entry.max_cyclomatic.is_none());
846        assert!(override_entry.has_any_threshold());
847        assert!(config.threshold_override_errors().is_empty());
848    }
849
850    #[test]
851    fn health_config_threshold_override_max_file_lines() {
852        let json = r#"{
853            "maxFileLines": 500,
854            "thresholdOverrides": [
855                {"files": ["src/generated/**"], "maxFileLines": 0},
856                {"files": ["src/a.ts"], "functions": ["f"], "maxFileLines": 900}
857            ]
858        }"#;
859        let config: HealthConfig = serde_json::from_str(json).unwrap();
860        assert_eq!(config.max_file_lines, 500);
861        assert_eq!(config.threshold_overrides[0].max_file_lines, Some(0));
862        assert!(config.threshold_overrides[0].has_any_threshold());
863        assert_eq!(
864            config.threshold_override_errors(),
865            vec![
866                "health.thresholdOverrides[1].maxFileLines applies to whole files; move it to an entry without functions"
867            ]
868        );
869        assert_eq!(HealthConfig::default().max_file_lines, 0);
870    }
871
872    #[test]
873    fn health_config_json_only_max_unit_size() {
874        let json = r#"{"maxUnitSize": 100}"#;
875        let config: HealthConfig = serde_json::from_str(json).unwrap();
876        assert_eq!(config.max_unit_size, 100);
877        assert_eq!(config.max_cyclomatic, 20); // default
878        assert!(config.threshold_overrides.is_empty());
879    }
880
881    #[test]
882    fn health_config_threshold_override_rejects_unknown_keys() {
883        let err = serde_json::from_str::<HealthConfig>(
884            r#"{"thresholdOverrides":[{"files":["src/auth.ts"],"maxCogntive":25}]}"#,
885        )
886        .unwrap_err();
887        assert!(err.to_string().contains("maxCogntive"));
888    }
889
890    #[test]
891    fn health_config_suggest_inline_suppression_default_true() {
892        let config = HealthConfig::default();
893        assert!(config.suggest_inline_suppression);
894    }
895
896    #[test]
897    fn health_config_suggest_inline_suppression_explicit_false() {
898        let json = r#"{"suggestInlineSuppression": false}"#;
899        let config: HealthConfig = serde_json::from_str(json).unwrap();
900        assert!(!config.suggest_inline_suppression);
901    }
902
903    #[test]
904    fn health_config_suggest_inline_suppression_omitted_uses_default() {
905        let config: HealthConfig = serde_json::from_str("{}").unwrap();
906        assert!(config.suggest_inline_suppression);
907    }
908
909    #[test]
910    fn health_config_zero_thresholds() {
911        let json = r#"{"maxCyclomatic": 0, "maxCognitive": 0}"#;
912        let config: HealthConfig = serde_json::from_str(json).unwrap();
913        assert_eq!(config.max_cyclomatic, 0);
914        assert_eq!(config.max_cognitive, 0);
915    }
916
917    #[test]
918    fn health_config_large_thresholds() {
919        let json = r#"{"maxCyclomatic": 65535, "maxCognitive": 65535}"#;
920        let config: HealthConfig = serde_json::from_str(json).unwrap();
921        assert_eq!(config.max_cyclomatic, u16::MAX);
922        assert_eq!(config.max_cognitive, u16::MAX);
923    }
924
925    #[test]
926    fn ownership_config_default_has_bot_patterns() {
927        let cfg = OwnershipConfig::default();
928        assert!(cfg.bot_patterns.iter().any(|p| p == r"*\[bot\]*"));
929        assert!(cfg.bot_patterns.iter().any(|p| p == "dependabot*"));
930        assert!(cfg.bot_patterns.iter().any(|p| p == "github-actions*"));
931        assert!(
932            !cfg.bot_patterns.iter().any(|p| p == "*noreply*"),
933            "*noreply* must not be a default bot pattern (filters real human \
934             contributors using GitHub's privacy default email)"
935        );
936        assert_eq!(cfg.email_mode, EmailMode::Handle);
937    }
938
939    #[test]
940    fn ownership_config_json_overrides_defaults() {
941        let json = r#"{
942            "ownership": {
943                "botPatterns": ["custom-bot*"],
944                "emailMode": "raw"
945            }
946        }"#;
947        let config: HealthConfig = serde_json::from_str(json).unwrap();
948        assert_eq!(config.ownership.bot_patterns, vec!["custom-bot*"]);
949        assert_eq!(config.ownership.email_mode, EmailMode::Raw);
950    }
951
952    #[test]
953    fn ownership_config_email_mode_kebab_case() {
954        for (mode, repr) in [
955            (EmailMode::Raw, "\"raw\""),
956            (EmailMode::Handle, "\"handle\""),
957            (EmailMode::Anonymized, "\"anonymized\""),
958            (EmailMode::Hash, "\"hash\""),
959        ] {
960            let s = serde_json::to_string(&mode).unwrap();
961            assert_eq!(s, repr);
962            let back: EmailMode = serde_json::from_str(repr).unwrap();
963            assert_eq!(back, mode);
964        }
965    }
966
967    #[test]
968    fn ownership_config_email_mode_accepts_legacy_hash_alias() {
969        let back: EmailMode = serde_json::from_str("\"hash\"").unwrap();
970        assert_eq!(back, EmailMode::Hash);
971    }
972}