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/// How `fallow health` counts cyclomatic complexity for its gates.
217///
218/// The policy changes the cyclomatic value that the `maxCyclomatic` gate reads
219/// and the cyclomatic value in every CRAP score. It does not change the health
220/// score, the complexity density, or the hotspot ranking: those keep the
221/// standard count so that grades stay comparable across projects.
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
223#[serde(rename_all = "kebab-case")]
224pub enum CyclomaticPolicy {
225    /// Count every decision point, `&&`, `||`, and `??` operator (`McCabe`).
226    #[default]
227    Standard,
228    /// Count a literal membership chain as one predicate. A chain such as
229    /// `kind === "a" || kind === "b" || kind === "c"` adds no cyclomatic
230    /// increments for its `||` operators. Only strict equality checks of one
231    /// identifier against string, number, bigint, boolean, or `null` literals
232    /// qualify. Member access, calls, mixed operators, and different operands
233    /// keep the standard count.
234    LiteralMembership,
235}
236
237impl CyclomaticPolicy {
238    /// Whether this is the default `standard` policy.
239    #[must_use]
240    pub const fn is_standard(&self) -> bool {
241        matches!(self, Self::Standard)
242    }
243}
244
245/// Configuration for complexity health metrics (`fallow health`).
246#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
247#[serde(deny_unknown_fields, rename_all = "camelCase")]
248pub struct HealthConfig {
249    /// Maximum allowed cyclomatic complexity per function (default: 20).
250    /// Functions exceeding this threshold are reported. Governs findings
251    /// only; the health score's complexity penalties use fixed calibration
252    /// (use `health.ignore` to remove a file from the score).
253    #[serde(default = "default_max_cyclomatic")]
254    pub max_cyclomatic: u16,
255
256    /// How the cyclomatic gate counts complexity (default: `standard`).
257    /// `literal-membership` counts a chain of strict equality checks of one
258    /// identifier against primitive literals (`kind === "a" || kind === "b"`)
259    /// as one predicate. The policy applies to the `maxCyclomatic` gate and
260    /// to every CRAP score, so the `maxCrap` gate reads the same value.
261    /// Findings then report the standard value as `standard_cyclomatic`. The
262    /// health score, complexity density, and hotspots keep the standard
263    /// count. Older fallow versions reject this key as unknown, so pair it
264    /// with `minimumVersion`.
265    #[serde(default, skip_serializing_if = "CyclomaticPolicy::is_standard")]
266    pub cyclomatic_policy: CyclomaticPolicy,
267
268    /// Maximum allowed cognitive complexity per function (default: 15).
269    /// Functions exceeding this threshold are reported. Governs findings
270    /// only, never the health score.
271    #[serde(default = "default_max_cognitive")]
272    pub max_cognitive: u16,
273
274    /// Maximum allowed CRAP (Change Risk Anti-Patterns) score per function
275    /// (default: 30.0). CRAP combines cyclomatic complexity with test
276    /// coverage: high complexity plus low coverage produces a high CRAP
277    /// score. Functions meeting or exceeding this threshold are reported.
278    /// Use `--coverage` with Istanbul data for accurate per-function CRAP;
279    /// otherwise fallow estimates coverage from the module graph. Governs
280    /// findings and the threshold-relative file-score signals
281    /// (`crap_above_threshold`, the `risk` triage tag, and the
282    /// `add_test_coverage` refactoring target); measured values such as
283    /// `crap_max` and the overall health score never move with it. Set to
284    /// `0` to disable CRAP enforcement entirely: no findings, nothing counts
285    /// above threshold, and file-score rows disclose baseline breaches as
286    /// exempt instead. The `complexity-crap` rule is different: it decides if
287    /// a finding fails the run, and `off` hides the findings but keeps the
288    /// file-score signals.
289    #[serde(default = "default_max_crap")]
290    pub max_crap: f64,
291
292    /// Band below `maxCyclomatic` where CRAP-only findings also receive a
293    /// secondary `refactor-function` action (default: 5). Set to `0` to only
294    /// suggest refactoring when cyclomatic already meets the configured
295    /// threshold.
296    #[serde(default = "default_crap_refactor_band")]
297    pub crap_refactor_band: u16,
298
299    /// Maximum function length in lines of code before it is reported as an
300    /// oversized "large function" (default: 60). Raise it globally, or per file
301    /// via `thresholdOverrides[].maxUnitSize`, to relax the bar for generated or
302    /// test files (where a `describe()` block spans hundreds of lines) without
303    /// disabling complexity checks on those files. This filters the reported
304    /// large-functions list only; the descriptive unit-size profile and the
305    /// health score still reflect raw sizes against fixed calibration (the
306    /// `unit_size` penalty keeps its `>60` LOC very-high-risk edge so grades
307    /// stay comparable across projects; use `health.ignore` to remove a file
308    /// from the score entirely).
309    #[serde(default = "default_max_unit_size")]
310    pub max_unit_size: u32,
311
312    /// Maximum file length in physical lines before the file is reported as a
313    /// complexity finding with `exceeded: "file_lines"` (default: `0`, off).
314    /// Every line counts, also blank lines and comment lines. A final newline
315    /// does not add a line. Set a limit such as `500` to enable the check, and
316    /// raise it per file via `thresholdOverrides[].maxFileLines`. The
317    /// `complexity-file-lines` rule decides if a finding fails the run. In
318    /// `fallow audit`, a long file that did not grow stays inherited. Older
319    /// fallow versions reject this key as unknown, so pair it with
320    /// `minimumVersion`.
321    #[serde(default, skip_serializing_if = "is_zero_u32")]
322    pub max_file_lines: u32,
323
324    /// Path to Istanbul coverage data (coverage-final.json) or raw V8 coverage
325    /// (a `NODE_V8_COVERAGE` directory or one V8 JSON file) for accurate
326    /// per-function CRAP scores. Relative paths resolve against the project root. The CLI
327    /// `--coverage` flag and `FALLOW_COVERAGE` environment variable override
328    /// this value. Consulted by `fallow health`, bare `fallow`, `fallow audit`,
329    /// `fallow viz`, and the MCP `audit` / `check_health` tools.
330    #[serde(default)]
331    pub coverage: Option<PathBuf>,
332
333    /// Absolute prefix to strip from Istanbul file paths before CRAP matching.
334    /// Use when coverage was generated under a different checkout root in CI
335    /// or Docker. The CLI `--coverage-root` flag and `FALLOW_COVERAGE_ROOT`
336    /// environment variable override this value. Consulted by `fallow health`,
337    /// bare `fallow`, `fallow audit`, `fallow viz`, and the MCP `audit` /
338    /// `check_health` tools.
339    #[serde(default)]
340    pub coverage_root: Option<PathBuf>,
341
342    /// Glob patterns to exclude from complexity analysis.
343    /// A single `*` stays within one path segment; use `**` to match across directories.
344    #[serde(default)]
345    pub ignore: Vec<String>,
346
347    /// Regular expressions excluding Tailwind arbitrary-value utilities from
348    /// token-drift findings and analytics, including CVA variants. Matches the
349    /// normalized `prefix-[value]` token, without variants, negative signs, or
350    /// suffix modifiers. Both `-mt-[7px]` and `mt-[7px]` match as `mt-[7px]`;
351    /// `bg-[#abc]/50` matches as `bg-[#abc]`. These spellings cannot be excluded
352    /// independently. Use `^icon-\[` to exclude Iconify tokens, including variants.
353    /// Defaults to no exclusions. Invalid regexes fail config loading.
354    #[serde(default, skip_serializing_if = "Vec::is_empty")]
355    pub tailwind_ignore_patterns: Vec<String>,
356
357    /// Per-file or per-function threshold overrides. These keep exceptional
358    /// functions visible as configured numeric ceilings instead of hiding them
359    /// behind binary suppressions.
360    #[serde(default, skip_serializing_if = "Vec::is_empty")]
361    pub threshold_overrides: Vec<HealthThresholdOverride>,
362
363    /// Ownership analysis configuration. Controls bot filtering and email
364    /// privacy mode for `--ownership` output.
365    #[serde(default)]
366    pub ownership: OwnershipConfig,
367
368    /// Change coupling thresholds for the `change_coupling` section and the
369    /// hidden-coupling refactoring targets. Older fallow versions reject this
370    /// key as unknown, so pair it with `minimumVersion` set to the release
371    /// that added it.
372    #[serde(default)]
373    pub change_coupling: ChangeCouplingConfig,
374
375    /// Whether health JSON output emits `suppress-line` action hints
376    /// alongside complexity findings (default: `true`). Set to `false` to
377    /// opt out across the project: useful for teams that manage suppressions
378    /// exclusively through `// fallow-ignore-*` comments authored by hand or
379    /// through the `fallow.suppress` LSP code action, but who do not want
380    /// CI-driven `suppress-line` action hints in their JSON output.
381    /// `--baseline` activates auto-omission regardless of this setting,
382    /// since baseline files are a separate suppression mechanism.
383    #[serde(default = "default_suggest_inline_suppression")]
384    pub suggest_inline_suppression: bool,
385
386    /// Whether `fallow-override-threshold-next-line` comments apply (default:
387    /// `true`). Such a comment sets the health ceilings of the function on
388    /// the next line, as in
389    /// `// fallow-override-threshold-next-line maxCognitive=40 -- reason`.
390    /// Set to `false` to keep every exception in `thresholdOverrides`: each
391    /// comment then has no effect and the report lists it as `disabled`.
392    #[serde(default = "default_inline_threshold_overrides")]
393    pub inline_threshold_overrides: bool,
394}
395
396impl Default for HealthConfig {
397    fn default() -> Self {
398        Self {
399            max_cyclomatic: default_max_cyclomatic(),
400            cyclomatic_policy: CyclomaticPolicy::Standard,
401            max_cognitive: default_max_cognitive(),
402            max_crap: default_max_crap(),
403            crap_refactor_band: default_crap_refactor_band(),
404            max_unit_size: default_max_unit_size(),
405            max_file_lines: 0,
406            coverage: None,
407            coverage_root: None,
408            ignore: vec![],
409            tailwind_ignore_patterns: vec![],
410            threshold_overrides: vec![],
411            ownership: OwnershipConfig::default(),
412            change_coupling: ChangeCouplingConfig::default(),
413            suggest_inline_suppression: default_suggest_inline_suppression(),
414            inline_threshold_overrides: default_inline_threshold_overrides(),
415        }
416    }
417}
418
419/// Per-file or per-function health threshold override.
420#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
421#[serde(deny_unknown_fields, rename_all = "camelCase")]
422pub struct HealthThresholdOverride {
423    /// Project-root-relative file globs this override applies to.
424    /// A single `*` stays within one path segment; use `**` to match across directories.
425    pub files: Vec<String>,
426    /// Exact emitted function names this override applies to. Empty means every
427    /// function in matching files. Synthetic units are matched by their emitted
428    /// name, so `"<template>"` and `"<snippet:NAME>"` are valid keys. The
429    /// synthetic `"<module>"` unit is not: it carries a file's module-scope
430    /// decision points into the aggregate metrics and never produces a finding,
431    /// so there is no ceiling for an override to move.
432    #[serde(default, skip_serializing_if = "Vec::is_empty")]
433    pub functions: Vec<String>,
434    /// Local cyclomatic complexity ceiling.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub max_cyclomatic: Option<u16>,
437    /// Local cognitive complexity ceiling.
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub max_cognitive: Option<u16>,
440    /// Local CRAP ceiling.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub max_crap: Option<f64>,
443    /// Local unit-size ceiling: maximum function length in lines of code before
444    /// it is reported as an oversized "large function". Leave `functions` empty
445    /// to relax the bar for every function in the matching files (which covers
446    /// both the `describe()` wrapper and the individual `it()` blocks in a test
447    /// suite).
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub max_unit_size: Option<u32>,
450    /// Local file-length ceiling in physical lines. `0` turns the file-length
451    /// check off for the matching files. The ceiling applies to whole files,
452    /// so an entry that sets it must leave `functions` empty.
453    #[serde(default, skip_serializing_if = "Option::is_none")]
454    pub max_file_lines: Option<u32>,
455    /// Human-readable rationale for the exception.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub reason: Option<String>,
458}
459
460impl HealthThresholdOverride {
461    /// Return true when the override configures at least one local ceiling.
462    #[must_use]
463    pub const fn has_any_threshold(&self) -> bool {
464        self.max_cyclomatic.is_some()
465            || self.max_cognitive.is_some()
466            || self.max_crap.is_some()
467            || self.max_unit_size.is_some()
468            || self.max_file_lines.is_some()
469    }
470}
471
472impl HealthConfig {
473    /// Whether the file-length check can report a finding: the global
474    /// `maxFileLines` is above `0`, or an override sets a `maxFileLines`.
475    #[must_use]
476    pub fn file_lines_check_enabled(&self) -> bool {
477        self.max_file_lines > 0
478            || self
479                .threshold_overrides
480                .iter()
481                .any(|entry| entry.max_file_lines.is_some_and(|max| max > 0))
482    }
483
484    /// Validate semantic constraints that serde cannot express.
485    #[must_use]
486    pub fn threshold_override_errors(&self) -> Vec<String> {
487        let mut errors = Vec::new();
488        for (index, override_entry) in self.threshold_overrides.iter().enumerate() {
489            if override_entry.files.is_empty() {
490                errors.push(format!(
491                    "health.thresholdOverrides[{index}].files must contain at least one pattern"
492                ));
493            }
494            if !override_entry.has_any_threshold() {
495                errors.push(format!(
496                    "health.thresholdOverrides[{index}] must set at least one of maxCyclomatic, maxCognitive, maxCrap, maxUnitSize, or maxFileLines"
497                ));
498            }
499            if override_entry.max_file_lines.is_some() && !override_entry.functions.is_empty() {
500                errors.push(format!(
501                    "health.thresholdOverrides[{index}].maxFileLines applies to whole files; move it to an entry without functions"
502                ));
503            }
504        }
505        errors
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    #[test]
514    fn change_coupling_ranges_are_validated() {
515        assert!(ChangeCouplingConfig::default().errors().is_empty());
516        let at_bounds = ChangeCouplingConfig {
517            max_files_per_commit: 1000,
518            min_degree: 1.0,
519            ..ChangeCouplingConfig::default()
520        };
521        assert!(at_bounds.errors().is_empty());
522
523        for (max_files_per_commit, min_degree) in [(1, 0.3), (1001, 0.3), (30, -0.1), (30, 1.5)] {
524            let config = ChangeCouplingConfig {
525                max_files_per_commit,
526                min_degree,
527                ..ChangeCouplingConfig::default()
528            };
529            assert_eq!(
530                config.errors().len(),
531                1,
532                "maxFilesPerCommit {max_files_per_commit}, minDegree {min_degree}"
533            );
534        }
535        let nan = ChangeCouplingConfig {
536            min_degree: f64::NAN,
537            ..ChangeCouplingConfig::default()
538        };
539        assert_eq!(nan.errors().len(), 1);
540    }
541
542    #[test]
543    fn health_config_defaults() {
544        let config = HealthConfig::default();
545        assert_eq!(config.max_cyclomatic, 20);
546        assert_eq!(config.max_cognitive, 15);
547        assert!((config.max_crap - 30.0).abs() < f64::EPSILON);
548        assert_eq!(config.crap_refactor_band, 5);
549        assert_eq!(config.max_unit_size, 60);
550        assert!(config.coverage.is_none());
551        assert!(config.coverage_root.is_none());
552        assert!(config.ignore.is_empty());
553        assert!(config.threshold_overrides.is_empty());
554        assert_eq!(config.change_coupling.max_files_per_commit, 30);
555        assert_eq!(config.change_coupling.min_revisions, 5);
556        assert_eq!(config.change_coupling.min_shared_revisions, 5);
557        assert!((config.change_coupling.min_degree - 0.3).abs() < f64::EPSILON);
558        let ownership = OwnershipConfig::default();
559        assert_eq!(config.ownership.bot_patterns, ownership.bot_patterns);
560        assert_eq!(config.ownership.email_mode, ownership.email_mode);
561    }
562
563    #[test]
564    fn health_config_json_all_fields() {
565        let json = r#"{
566            "maxCyclomatic": 30,
567            "maxCognitive": 25,
568            "maxCrap": 50.0,
569            "crapRefactorBand": 3,
570            "coverage": "coverage/coverage-final.json",
571            "coverageRoot": "/ci/workspace",
572            "ignore": ["**/generated/**", "vendor/**"],
573            "thresholdOverrides": [{
574                "files": ["components/auth/src/index.ts"],
575                "functions": ["createAuthModule"],
576                "maxCognitive": 25,
577                "reason": "linear module assembly; agreed 2026-06"
578            }]
579        }"#;
580        let config: HealthConfig = serde_json::from_str(json).unwrap();
581        assert_eq!(config.max_cyclomatic, 30);
582        assert_eq!(config.max_cognitive, 25);
583        assert!((config.max_crap - 50.0).abs() < f64::EPSILON);
584        assert_eq!(config.crap_refactor_band, 3);
585        assert_eq!(
586            config.coverage,
587            Some(PathBuf::from("coverage/coverage-final.json"))
588        );
589        assert_eq!(config.coverage_root, Some(PathBuf::from("/ci/workspace")));
590        assert_eq!(config.ignore, vec!["**/generated/**", "vendor/**"]);
591        assert_eq!(config.threshold_overrides.len(), 1);
592        assert_eq!(
593            config.threshold_overrides[0].files,
594            vec!["components/auth/src/index.ts"]
595        );
596        assert_eq!(
597            config.threshold_overrides[0].functions,
598            vec!["createAuthModule"]
599        );
600        assert_eq!(config.threshold_overrides[0].max_cognitive, Some(25));
601    }
602
603    #[test]
604    fn health_config_json_partial_uses_defaults() {
605        let json = r#"{"maxCyclomatic": 10}"#;
606        let config: HealthConfig = serde_json::from_str(json).unwrap();
607        assert_eq!(config.max_cyclomatic, 10);
608        assert_eq!(config.max_cognitive, 15); // default
609        assert!((config.max_crap - 30.0).abs() < f64::EPSILON); // default
610        assert_eq!(config.crap_refactor_band, 5); // default
611        assert!(config.ignore.is_empty()); // default
612        assert!(config.threshold_overrides.is_empty()); // default
613    }
614
615    #[test]
616    fn health_config_json_only_max_crap() {
617        let json = r#"{"maxCrap": 15.5}"#;
618        let config: HealthConfig = serde_json::from_str(json).unwrap();
619        assert!((config.max_crap - 15.5).abs() < f64::EPSILON);
620        assert_eq!(config.max_cyclomatic, 20); // default
621        assert_eq!(config.cyclomatic_policy, CyclomaticPolicy::Standard);
622        assert_eq!(config.max_cognitive, 15); // default
623        assert_eq!(config.crap_refactor_band, 5); // default
624    }
625
626    #[test]
627    fn health_config_json_empty_object_uses_all_defaults() {
628        let config: HealthConfig = serde_json::from_str("{}").unwrap();
629        assert_eq!(config.max_cyclomatic, 20);
630        assert_eq!(config.max_cognitive, 15);
631        assert_eq!(config.crap_refactor_band, 5);
632        assert!(config.ignore.is_empty());
633        assert!(config.threshold_overrides.is_empty());
634    }
635
636    #[test]
637    fn health_config_json_only_ignore() {
638        let json = r#"{"ignore": ["test/**"]}"#;
639        let config: HealthConfig = serde_json::from_str(json).unwrap();
640        assert_eq!(config.max_cyclomatic, 20); // default
641        assert_eq!(config.max_cognitive, 15); // default
642        assert_eq!(config.ignore, vec!["test/**"]);
643        assert!(config.threshold_overrides.is_empty());
644    }
645
646    #[test]
647    fn health_config_toml_all_fields() {
648        let toml_str = r#"
649maxCyclomatic = 25
650maxCognitive = 20
651ignore = ["generated/**", "vendor/**"]
652
653[[thresholdOverrides]]
654files = ["src/auth.ts"]
655maxCognitive = 25
656"#;
657        let config: HealthConfig = toml::from_str(toml_str).unwrap();
658        assert_eq!(config.max_cyclomatic, 25);
659        assert_eq!(config.max_cognitive, 20);
660        assert_eq!(config.ignore, vec!["generated/**", "vendor/**"]);
661        assert_eq!(config.threshold_overrides.len(), 1);
662        assert_eq!(config.threshold_overrides[0].max_cognitive, Some(25));
663    }
664
665    #[test]
666    fn health_config_toml_defaults() {
667        let config: HealthConfig = toml::from_str("").unwrap();
668        assert_eq!(config.max_cyclomatic, 20);
669        assert_eq!(config.max_cognitive, 15);
670        assert!(config.ignore.is_empty());
671        assert!(config.threshold_overrides.is_empty());
672    }
673
674    #[test]
675    fn health_config_json_roundtrip() {
676        let config = HealthConfig {
677            max_cyclomatic: 50,
678            cyclomatic_policy: CyclomaticPolicy::LiteralMembership,
679            max_cognitive: 40,
680            max_crap: 75.0,
681            crap_refactor_band: 4,
682            max_unit_size: 120,
683            max_file_lines: 500,
684            ignore: vec!["test/**".to_string()],
685            tailwind_ignore_patterns: Vec::new(),
686            threshold_overrides: vec![HealthThresholdOverride {
687                files: vec!["src/auth.ts".to_string()],
688                functions: Vec::new(),
689                max_cyclomatic: Some(30),
690                max_cognitive: None,
691                max_crap: Some(45.0),
692                max_unit_size: None,
693                max_file_lines: None,
694                reason: Some("framework assembly".to_string()),
695            }],
696            coverage: None,
697            coverage_root: None,
698            ownership: OwnershipConfig::default(),
699            change_coupling: ChangeCouplingConfig {
700                min_degree: 0.4,
701                ..ChangeCouplingConfig::default()
702            },
703            suggest_inline_suppression: false,
704            inline_threshold_overrides: false,
705        };
706        let json = serde_json::to_string(&config).unwrap();
707        let restored: HealthConfig = serde_json::from_str(&json).unwrap();
708        assert_eq!(restored.max_cyclomatic, 50);
709        assert_eq!(
710            restored.cyclomatic_policy,
711            CyclomaticPolicy::LiteralMembership
712        );
713        assert!((restored.change_coupling.min_degree - 0.4).abs() < f64::EPSILON);
714        assert_eq!(restored.max_cognitive, 40);
715        assert!((restored.max_crap - 75.0).abs() < f64::EPSILON);
716        assert_eq!(restored.crap_refactor_band, 4);
717        assert_eq!(restored.max_unit_size, 120);
718        assert_eq!(restored.max_file_lines, 500);
719        assert_eq!(restored.ignore, vec!["test/**"]);
720        assert_eq!(restored.threshold_overrides.len(), 1);
721        assert_eq!(restored.threshold_overrides[0].max_cyclomatic, Some(30));
722        assert_eq!(restored.threshold_overrides[0].max_crap, Some(45.0));
723        assert!(!restored.suggest_inline_suppression);
724        assert!(!restored.inline_threshold_overrides);
725        assert!(HealthConfig::default().inline_threshold_overrides);
726    }
727
728    #[test]
729    fn health_config_threshold_override_omitted_functions_matches_all() {
730        let json = r#"{
731            "thresholdOverrides": [{
732                "files": ["src/auth.ts"],
733                "maxCognitive": 25
734            }]
735        }"#;
736        let config: HealthConfig = serde_json::from_str(json).unwrap();
737        let override_entry = &config.threshold_overrides[0];
738        assert!(override_entry.functions.is_empty());
739        assert_eq!(override_entry.max_cognitive, Some(25));
740        assert!(config.threshold_override_errors().is_empty());
741    }
742
743    #[test]
744    fn health_config_threshold_override_validation_requires_files() {
745        let json = r#"{
746            "thresholdOverrides": [{
747                "files": [],
748                "maxCognitive": 25
749            }]
750        }"#;
751        let config: HealthConfig = serde_json::from_str(json).unwrap();
752        assert_eq!(
753            config.threshold_override_errors(),
754            vec!["health.thresholdOverrides[0].files must contain at least one pattern"]
755        );
756    }
757
758    #[test]
759    fn health_config_threshold_override_validation_requires_threshold() {
760        let json = r#"{
761            "thresholdOverrides": [{
762                "files": ["src/auth.ts"],
763                "reason": "temporary"
764            }]
765        }"#;
766        let config: HealthConfig = serde_json::from_str(json).unwrap();
767        assert_eq!(
768            config.threshold_override_errors(),
769            vec![
770                "health.thresholdOverrides[0] must set at least one of maxCyclomatic, maxCognitive, maxCrap, maxUnitSize, or maxFileLines"
771            ]
772        );
773    }
774
775    #[test]
776    fn health_config_threshold_override_max_unit_size_only_is_valid() {
777        let json = r#"{
778            "thresholdOverrides": [{
779                "files": ["**/*.test.*"],
780                "maxUnitSize": 500
781            }]
782        }"#;
783        let config: HealthConfig = serde_json::from_str(json).unwrap();
784        let override_entry = &config.threshold_overrides[0];
785        assert_eq!(override_entry.max_unit_size, Some(500));
786        assert!(override_entry.max_cyclomatic.is_none());
787        assert!(override_entry.has_any_threshold());
788        assert!(config.threshold_override_errors().is_empty());
789    }
790
791    #[test]
792    fn health_config_threshold_override_max_file_lines() {
793        let json = r#"{
794            "maxFileLines": 500,
795            "thresholdOverrides": [
796                {"files": ["src/generated/**"], "maxFileLines": 0},
797                {"files": ["src/a.ts"], "functions": ["f"], "maxFileLines": 900}
798            ]
799        }"#;
800        let config: HealthConfig = serde_json::from_str(json).unwrap();
801        assert_eq!(config.max_file_lines, 500);
802        assert_eq!(config.threshold_overrides[0].max_file_lines, Some(0));
803        assert!(config.threshold_overrides[0].has_any_threshold());
804        assert_eq!(
805            config.threshold_override_errors(),
806            vec![
807                "health.thresholdOverrides[1].maxFileLines applies to whole files; move it to an entry without functions"
808            ]
809        );
810        assert_eq!(HealthConfig::default().max_file_lines, 0);
811    }
812
813    #[test]
814    fn health_config_json_only_max_unit_size() {
815        let json = r#"{"maxUnitSize": 100}"#;
816        let config: HealthConfig = serde_json::from_str(json).unwrap();
817        assert_eq!(config.max_unit_size, 100);
818        assert_eq!(config.max_cyclomatic, 20); // default
819        assert!(config.threshold_overrides.is_empty());
820    }
821
822    #[test]
823    fn health_config_threshold_override_rejects_unknown_keys() {
824        let err = serde_json::from_str::<HealthConfig>(
825            r#"{"thresholdOverrides":[{"files":["src/auth.ts"],"maxCogntive":25}]}"#,
826        )
827        .unwrap_err();
828        assert!(err.to_string().contains("maxCogntive"));
829    }
830
831    #[test]
832    fn health_config_suggest_inline_suppression_default_true() {
833        let config = HealthConfig::default();
834        assert!(config.suggest_inline_suppression);
835    }
836
837    #[test]
838    fn health_config_suggest_inline_suppression_explicit_false() {
839        let json = r#"{"suggestInlineSuppression": false}"#;
840        let config: HealthConfig = serde_json::from_str(json).unwrap();
841        assert!(!config.suggest_inline_suppression);
842    }
843
844    #[test]
845    fn health_config_suggest_inline_suppression_omitted_uses_default() {
846        let config: HealthConfig = serde_json::from_str("{}").unwrap();
847        assert!(config.suggest_inline_suppression);
848    }
849
850    #[test]
851    fn health_config_zero_thresholds() {
852        let json = r#"{"maxCyclomatic": 0, "maxCognitive": 0}"#;
853        let config: HealthConfig = serde_json::from_str(json).unwrap();
854        assert_eq!(config.max_cyclomatic, 0);
855        assert_eq!(config.max_cognitive, 0);
856    }
857
858    #[test]
859    fn health_config_large_thresholds() {
860        let json = r#"{"maxCyclomatic": 65535, "maxCognitive": 65535}"#;
861        let config: HealthConfig = serde_json::from_str(json).unwrap();
862        assert_eq!(config.max_cyclomatic, u16::MAX);
863        assert_eq!(config.max_cognitive, u16::MAX);
864    }
865
866    #[test]
867    fn ownership_config_default_has_bot_patterns() {
868        let cfg = OwnershipConfig::default();
869        assert!(cfg.bot_patterns.iter().any(|p| p == r"*\[bot\]*"));
870        assert!(cfg.bot_patterns.iter().any(|p| p == "dependabot*"));
871        assert!(cfg.bot_patterns.iter().any(|p| p == "github-actions*"));
872        assert!(
873            !cfg.bot_patterns.iter().any(|p| p == "*noreply*"),
874            "*noreply* must not be a default bot pattern (filters real human \
875             contributors using GitHub's privacy default email)"
876        );
877        assert_eq!(cfg.email_mode, EmailMode::Handle);
878    }
879
880    #[test]
881    fn ownership_config_json_overrides_defaults() {
882        let json = r#"{
883            "ownership": {
884                "botPatterns": ["custom-bot*"],
885                "emailMode": "raw"
886            }
887        }"#;
888        let config: HealthConfig = serde_json::from_str(json).unwrap();
889        assert_eq!(config.ownership.bot_patterns, vec!["custom-bot*"]);
890        assert_eq!(config.ownership.email_mode, EmailMode::Raw);
891    }
892
893    #[test]
894    fn ownership_config_email_mode_kebab_case() {
895        for (mode, repr) in [
896            (EmailMode::Raw, "\"raw\""),
897            (EmailMode::Handle, "\"handle\""),
898            (EmailMode::Anonymized, "\"anonymized\""),
899            (EmailMode::Hash, "\"hash\""),
900        ] {
901            let s = serde_json::to_string(&mode).unwrap();
902            assert_eq!(s, repr);
903            let back: EmailMode = serde_json::from_str(repr).unwrap();
904            assert_eq!(back, mode);
905        }
906    }
907
908    #[test]
909    fn ownership_config_email_mode_accepts_legacy_hash_alias() {
910        let back: EmailMode = serde_json::from_str("\"hash\"").unwrap();
911        assert_eq!(back, EmailMode::Hash);
912    }
913}