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