cargo-coupling 0.3.7

A coupling analysis tool for Rust projects - measuring the 'right distance' in your code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! Configuration file support for cargo-coupling
//!
//! This module handles parsing and applying `.coupling.toml` configuration files
//! that allow users to override volatility predictions and customize analysis.
//!
//! ## Configuration File Format
//!
//! ```toml
//! # .coupling.toml
//!
//! [analysis]
//! # Exclude test code (#[test], #[cfg(test)], mod tests) from analysis
//! exclude_tests = true
//!
//! # "Prelude-like" modules that are expected to be used by many other modules.
//! # These modules will not trigger "High Afferent Coupling" warnings.
//! prelude_modules = ["src/lib.rs", "src/prelude.rs", "src/core/*"]
//!
//! # Modules to completely exclude from analysis
//! exclude = ["src/generated/*", "src/test_utils/*"]
//!
//! [volatility]
//! # Modules expected to change frequently (High volatility)
//! high = ["src/business_rules/*", "src/pricing/*"]
//!
//! # Stable modules (Low volatility)
//! low = ["src/core/*", "src/contracts/*"]
//!
//! # Paths to ignore from analysis (deprecated: use [analysis].exclude instead)
//! ignore = ["src/generated/*", "tests/*"]
//!
//! [subdomains]
//! # DDD subdomain classification (Khononov's Balanced Coupling model)
//! # Volatility is derived from business domain, not just git history.
//! # Explicit [volatility] overrides take priority over subdomain classification.
//! core = ["src/analyzer.rs", "src/balance.rs", "src/metrics.rs"]
//! supporting = ["src/report.rs", "src/cli_output.rs"]
//! generic = ["src/web/*", "src/config.rs"]
//!
//! [thresholds]
//! # Maximum dependencies before flagging High Efferent Coupling
//! max_dependencies = 15
//!
//! # Maximum dependents before flagging High Afferent Coupling
//! max_dependents = 20
//! ```

use glob::Pattern;
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

use crate::metrics::dimensions::MetricsConfig;
pub use crate::metrics::dimensions::Subdomain;
use crate::volatility::Volatility;

/// Errors that can occur when loading configuration
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Failed to read config file: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Failed to parse config file: {0}")]
    ParseError(#[from] toml::de::Error),

    #[error("Invalid glob pattern: {0}")]
    PatternError(String),
}

/// Analysis configuration section
#[derive(Debug, Clone, Deserialize, Default)]
pub struct AnalysisConfig {
    /// Exclude test code from analysis (#[test], #[cfg(test)], mod tests)
    #[serde(default)]
    pub exclude_tests: bool,

    /// "Prelude-like" modules that are expected to be depended on by many modules.
    /// These modules will not trigger "High Afferent Coupling" warnings.
    #[serde(default)]
    pub prelude_modules: Vec<String>,

    /// Modules to completely exclude from analysis
    #[serde(default)]
    pub exclude: Vec<String>,
}

/// Volatility configuration section
#[derive(Debug, Clone, Deserialize, Default)]
pub struct VolatilityConfig {
    /// Paths that should be considered high volatility
    #[serde(default)]
    pub high: Vec<String>,

    /// Paths that should be considered medium volatility
    #[serde(default)]
    pub medium: Vec<String>,

    /// Paths that should be considered low volatility
    #[serde(default)]
    pub low: Vec<String>,

    /// Paths to ignore from analysis
    #[serde(default)]
    pub ignore: Vec<String>,
}

/// DDD subdomain classification for volatility assessment
///
/// Based on Khononov's Balanced Coupling model: volatility should be determined
/// by business domain classification, not just git history.
/// - Core subdomains = High volatility (competitive advantage, constantly optimized)
/// - Supporting subdomains = Low volatility (boring CRUD/ETL, rarely changes)
/// - Generic subdomains = Low volatility (solved problems, stable implementations)
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SubdomainConfig {
    /// Core subdomain modules (high volatility - competitive advantage)
    #[serde(default)]
    pub core: Vec<String>,

    /// Supporting subdomain modules (low volatility - stable business logic)
    #[serde(default)]
    pub supporting: Vec<String>,

    /// Generic subdomain modules (low volatility - solved problems)
    #[serde(default)]
    pub generic: Vec<String>,
}

/// Threshold configuration section
#[derive(Debug, Clone, Deserialize)]
pub struct ThresholdsConfig {
    /// Maximum dependencies before flagging High Efferent Coupling
    #[serde(default = "default_max_dependencies")]
    pub max_dependencies: usize,

    /// Maximum dependents before flagging High Afferent Coupling
    #[serde(default = "default_max_dependents")]
    pub max_dependents: usize,
}

fn default_max_dependencies() -> usize {
    15
}

fn default_max_dependents() -> usize {
    20
}

impl Default for ThresholdsConfig {
    fn default() -> Self {
        Self {
            max_dependencies: default_max_dependencies(),
            max_dependents: default_max_dependents(),
        }
    }
}

/// Root configuration structure
#[derive(Debug, Clone, Deserialize, Default)]
pub struct CouplingConfig {
    /// Analysis configuration (test exclusion, prelude modules, etc.)
    #[serde(default)]
    pub analysis: AnalysisConfig,

    /// Volatility override configuration
    #[serde(default)]
    pub volatility: VolatilityConfig,

    /// DDD subdomain classification (affects volatility assessment)
    #[serde(default)]
    pub subdomains: SubdomainConfig,

    /// Threshold configuration
    #[serde(default)]
    pub thresholds: ThresholdsConfig,
}

/// Compiled configuration with glob patterns
#[derive(Debug, Clone)]
pub struct CompiledConfig {
    // === Analysis settings ===
    /// Whether to exclude test code from analysis
    pub exclude_tests: bool,
    /// Directory containing the loaded config file, if any.
    config_root: Option<PathBuf>,
    /// Patterns for prelude-like modules (exempt from afferent coupling warnings)
    prelude_patterns: Vec<Pattern>,
    /// Patterns for modules to completely exclude from analysis
    exclude_patterns: Vec<Pattern>,

    // === Volatility settings ===
    /// Patterns for high volatility paths
    high_patterns: Vec<Pattern>,
    /// Patterns for medium volatility paths
    medium_patterns: Vec<Pattern>,
    /// Patterns for low volatility paths
    low_patterns: Vec<Pattern>,
    /// Patterns for ignored paths (deprecated, use exclude_patterns)
    ignore_patterns: Vec<Pattern>,

    // === Subdomain settings ===
    /// Patterns for core subdomain (high volatility)
    core_patterns: Vec<Pattern>,
    /// Patterns for supporting subdomain (low volatility)
    supporting_patterns: Vec<Pattern>,
    /// Patterns for generic subdomain (low volatility)
    generic_patterns: Vec<Pattern>,

    // === Thresholds ===
    /// Threshold configuration
    pub thresholds: ThresholdsConfig,

    // === Cache ===
    /// Cache of path -> volatility mappings
    cache: HashMap<String, Option<Volatility>>,
}

/// A configured pattern that matched no paths during analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeadConfigPattern {
    /// Config section containing the pattern.
    pub section: &'static str,
    /// Original pattern string from the config.
    pub pattern: String,
}

impl CompiledConfig {
    /// Create a compiled config from raw config
    pub fn from_config(config: CouplingConfig) -> Result<Self, ConfigError> {
        Self::from_config_with_root(config, None)
    }

    /// Create a compiled config from raw config and the directory containing that config file.
    fn from_config_with_root(
        config: CouplingConfig,
        config_root: Option<&Path>,
    ) -> Result<Self, ConfigError> {
        let compile_patterns = |patterns: &[String]| -> Result<Vec<Pattern>, ConfigError> {
            patterns
                .iter()
                .map(|pattern| {
                    Pattern::new(pattern)
                        .map_err(|err| ConfigError::PatternError(format!("{}: {}", pattern, err)))
                })
                .collect()
        };

        Ok(Self {
            // Analysis settings
            exclude_tests: config.analysis.exclude_tests,
            config_root: config_root.map(Path::to_path_buf),
            prelude_patterns: compile_patterns(&config.analysis.prelude_modules)?,
            exclude_patterns: compile_patterns(&config.analysis.exclude)?,
            // Volatility settings
            high_patterns: compile_patterns(&config.volatility.high)?,
            medium_patterns: compile_patterns(&config.volatility.medium)?,
            low_patterns: compile_patterns(&config.volatility.low)?,
            ignore_patterns: compile_patterns(&config.volatility.ignore)?,
            // Subdomain settings
            core_patterns: compile_patterns(&config.subdomains.core)?,
            supporting_patterns: compile_patterns(&config.subdomains.supporting)?,
            generic_patterns: compile_patterns(&config.subdomains.generic)?,
            // Thresholds
            thresholds: config.thresholds,
            cache: HashMap::new(),
        })
    }

    /// Create an empty config (no overrides)
    pub fn empty() -> Self {
        Self {
            exclude_tests: false,
            config_root: None,
            prelude_patterns: Vec::new(),
            exclude_patterns: Vec::new(),
            high_patterns: Vec::new(),
            medium_patterns: Vec::new(),
            low_patterns: Vec::new(),
            ignore_patterns: Vec::new(),
            core_patterns: Vec::new(),
            supporting_patterns: Vec::new(),
            generic_patterns: Vec::new(),
            thresholds: ThresholdsConfig::default(),
            cache: HashMap::new(),
        }
    }

    /// Set exclude_tests flag (used by CLI --exclude-tests option)
    pub fn set_exclude_tests(&mut self, exclude: bool) {
        self.exclude_tests = exclude;
    }

    /// Get the directory the config was loaded from, if known.
    pub fn config_root(&self) -> Option<&Path> {
        self.config_root.as_deref()
    }

    /// Update the config root when analyzing the same config in a git worktree.
    pub(crate) fn set_config_root(&mut self, config_root: Option<PathBuf>) {
        self.config_root = config_root;
    }

    /// Check if a module is marked as "prelude-like" (exempt from afferent coupling warnings)
    pub fn is_prelude_module(&self, path: &str) -> bool {
        self.prelude_patterns.iter().any(|p| p.matches(path))
    }

    /// Check if a path should be completely excluded from analysis
    pub fn should_exclude(&self, path: &str) -> bool {
        self.exclude_patterns.iter().any(|p| p.matches(path))
    }

    /// Check if a path should be ignored (deprecated: use should_exclude)
    pub fn should_ignore(&self, path: &str) -> bool {
        self.ignore_patterns.iter().any(|p| p.matches(path))
            || self.exclude_patterns.iter().any(|p| p.matches(path))
    }

    /// Scoring-affecting pattern strings (subdomains, volatility overrides) that
    /// matched none of the given analyzed paths.
    ///
    /// A dead subdomain/volatility pattern silently reverts scoring to raw git churn,
    /// so it is reported as drift. `analysis.exclude` and `prelude_modules` are NOT
    /// reported: an unmatched exclude analyzes nothing wrongly (defensive future-proof
    /// excludes are idiomatic), and a dead prelude exemption surfaces as visible
    /// afferent warnings rather than silent misclassification.
    pub fn dead_patterns(&self, candidate_paths: &[String]) -> Vec<DeadConfigPattern> {
        let mut dead = Vec::new();
        Self::add_dead_patterns(
            &mut dead,
            "subdomains.core",
            &self.core_patterns,
            candidate_paths,
        );
        Self::add_dead_patterns(
            &mut dead,
            "subdomains.supporting",
            &self.supporting_patterns,
            candidate_paths,
        );
        Self::add_dead_patterns(
            &mut dead,
            "subdomains.generic",
            &self.generic_patterns,
            candidate_paths,
        );
        Self::add_dead_patterns(
            &mut dead,
            "volatility.high",
            &self.high_patterns,
            candidate_paths,
        );
        Self::add_dead_patterns(
            &mut dead,
            "volatility.medium",
            &self.medium_patterns,
            candidate_paths,
        );
        Self::add_dead_patterns(
            &mut dead,
            "volatility.low",
            &self.low_patterns,
            candidate_paths,
        );
        dead
    }

    fn add_dead_patterns(
        dead: &mut Vec<DeadConfigPattern>,
        section: &'static str,
        patterns: &[Pattern],
        candidate_paths: &[String],
    ) {
        dead.extend(patterns.iter().filter_map(|pattern| {
            if candidate_paths
                .iter()
                .any(|path| pattern.matches(path.as_str()))
            {
                None
            } else {
                Some(DeadConfigPattern {
                    section,
                    pattern: pattern.as_str().to_string(),
                })
            }
        }));
    }

    /// Get the list of prelude module patterns (for reporting)
    pub fn prelude_module_count(&self) -> usize {
        self.prelude_patterns.len()
    }

    /// Get the DDD subdomain classification for a path, if any
    pub fn get_subdomain(&self, path: &str) -> Option<Subdomain> {
        if self.core_patterns.iter().any(|p| p.matches(path)) {
            Some(Subdomain::Core)
        } else if self.supporting_patterns.iter().any(|p| p.matches(path)) {
            Some(Subdomain::Supporting)
        } else if self.generic_patterns.iter().any(|p| p.matches(path)) {
            Some(Subdomain::Generic)
        } else {
            None
        }
    }

    /// Check if config has any subdomain classifications
    pub fn has_subdomain_config(&self) -> bool {
        !self.core_patterns.is_empty()
            || !self.supporting_patterns.is_empty()
            || !self.generic_patterns.is_empty()
    }

    /// Get overridden volatility for a path, if any
    ///
    /// Priority: explicit volatility override > subdomain classification
    pub fn get_volatility_override(&mut self, path: &str) -> Option<Volatility> {
        // Check cache first
        if let Some(cached) = self.cache.get(path) {
            return *cached;
        }

        // Check explicit volatility patterns first (highest priority)
        let result = if self.high_patterns.iter().any(|p| p.matches(path)) {
            Some(Volatility::High)
        } else if self.medium_patterns.iter().any(|p| p.matches(path)) {
            Some(Volatility::Medium)
        } else if self.low_patterns.iter().any(|p| p.matches(path)) {
            Some(Volatility::Low)
        } else {
            // Fall back to subdomain-based volatility
            self.get_subdomain(path).map(|sd| sd.expected_volatility())
        };

        // Cache the result
        self.cache.insert(path.to_string(), result);
        result
    }

    /// Get volatility with override, falling back to git-based value
    pub fn get_volatility(&mut self, path: &str, git_volatility: Volatility) -> Volatility {
        self.get_volatility_override(path).unwrap_or(git_volatility)
    }

    /// Check if config has any volatility overrides
    pub fn has_volatility_overrides(&self) -> bool {
        !self.high_patterns.is_empty()
            || !self.medium_patterns.is_empty()
            || !self.low_patterns.is_empty()
    }
}

impl MetricsConfig for CompiledConfig {
    fn config_root(&self) -> Option<&Path> {
        CompiledConfig::config_root(self)
    }

    fn has_volatility_overrides(&self) -> bool {
        CompiledConfig::has_volatility_overrides(self)
    }

    fn has_subdomain_config(&self) -> bool {
        CompiledConfig::has_subdomain_config(self)
    }

    fn get_subdomain(&self, path: &str) -> Option<Subdomain> {
        CompiledConfig::get_subdomain(self, path)
    }

    fn get_volatility_override(&mut self, path: &str) -> Option<Volatility> {
        CompiledConfig::get_volatility_override(self, path)
    }
}

/// Load configuration from the project directory
///
/// Searches for `.coupling.toml` in the given directory and parent directories.
pub fn load_config(project_path: &Path) -> Result<CouplingConfig, ConfigError> {
    // Search for config file
    let config_path = find_config_file(project_path);

    match config_path {
        Some(path) => {
            let content = fs::read_to_string(&path)?;
            let config: CouplingConfig = toml::from_str(&content)?;
            Ok(config)
        }
        None => Ok(CouplingConfig::default()),
    }
}

/// Find the config file by searching up the directory tree
fn find_config_file(start_path: &Path) -> Option<std::path::PathBuf> {
    let config_names = [".coupling.toml", "coupling.toml"];

    let mut current = if start_path.is_file() {
        start_path.parent()?.to_path_buf()
    } else {
        start_path.to_path_buf()
    };

    loop {
        for name in &config_names {
            let config_path = current.join(name);
            if config_path.exists() {
                return Some(config_path);
            }
        }

        // Move to parent directory
        if let Some(parent) = current.parent() {
            current = parent.to_path_buf();
        } else {
            break;
        }
    }

    None
}

/// Load and compile configuration
pub fn load_compiled_config(project_path: &Path) -> Result<CompiledConfig, ConfigError> {
    match find_config_file(project_path) {
        Some(path) => {
            let content = fs::read_to_string(&path)?;
            let config: CouplingConfig = toml::from_str(&content)?;
            let absolute_path = absolute_normalized_path(&path)?;
            CompiledConfig::from_config_with_root(config, absolute_path.parent())
        }
        None => Ok(CompiledConfig::empty()),
    }
}

fn absolute_normalized_path(path: &Path) -> Result<PathBuf, std::io::Error> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };

    let mut normalized = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other.as_os_str()),
        }
    }

    Ok(normalized)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = CouplingConfig::default();
        assert!(config.volatility.high.is_empty());
        assert!(config.volatility.low.is_empty());
        assert_eq!(config.thresholds.max_dependencies, 15);
        assert_eq!(config.thresholds.max_dependents, 20);
    }

    #[test]
    fn test_parse_config() {
        let toml = r#"
            [volatility]
            high = ["src/api/*", "src/handlers/*"]
            low = ["src/core/*"]
            ignore = ["tests/*"]

            [thresholds]
            max_dependencies = 20
            max_dependents = 30
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.volatility.high.len(), 2);
        assert_eq!(config.volatility.low.len(), 1);
        assert_eq!(config.volatility.ignore.len(), 1);
        assert_eq!(config.thresholds.max_dependencies, 20);
        assert_eq!(config.thresholds.max_dependents, 30);
    }

    #[test]
    fn test_compiled_config() {
        let toml = r#"
            [volatility]
            high = ["src/business/*"]
            low = ["src/core/*"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let mut compiled = CompiledConfig::from_config(config).unwrap();

        assert_eq!(
            compiled.get_volatility_override("src/business/pricing.rs"),
            Some(Volatility::High)
        );
        assert_eq!(
            compiled.get_volatility_override("src/core/types.rs"),
            Some(Volatility::Low)
        );
        assert_eq!(compiled.get_volatility_override("src/other/file.rs"), None);
    }

    #[test]
    fn test_ignore_patterns() {
        let toml = r#"
            [volatility]
            ignore = ["tests/*", "benches/*"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();

        assert!(compiled.should_ignore("tests/integration.rs"));
        assert!(compiled.should_ignore("benches/perf.rs"));
        assert!(!compiled.should_ignore("src/lib.rs"));
    }

    #[test]
    fn test_get_volatility_with_fallback() {
        let toml = r#"
            [volatility]
            high = ["src/api/*"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let mut compiled = CompiledConfig::from_config(config).unwrap();

        // Override wins
        assert_eq!(
            compiled.get_volatility("src/api/handler.rs", Volatility::Low),
            Volatility::High
        );

        // Fallback to git volatility
        assert_eq!(
            compiled.get_volatility("src/other/file.rs", Volatility::Medium),
            Volatility::Medium
        );
    }

    #[test]
    fn test_subdomain_config() {
        let toml = r#"
            [subdomains]
            core = ["src/analyzer.rs", "src/balance.rs"]
            supporting = ["src/report.rs", "src/cli_output.rs"]
            generic = ["src/web/*", "src/config.rs"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let mut compiled = CompiledConfig::from_config(config).unwrap();

        // Core → High volatility
        assert_eq!(
            compiled.get_subdomain("src/analyzer.rs"),
            Some(Subdomain::Core)
        );
        assert_eq!(
            compiled.get_volatility_override("src/analyzer.rs"),
            Some(Volatility::High)
        );

        // Supporting → Low volatility
        assert_eq!(
            compiled.get_subdomain("src/report.rs"),
            Some(Subdomain::Supporting)
        );
        assert_eq!(
            compiled.get_volatility_override("src/report.rs"),
            Some(Volatility::Low)
        );

        // Generic → Low volatility
        assert_eq!(
            compiled.get_subdomain("src/web/server.rs"),
            Some(Subdomain::Generic)
        );
        assert_eq!(
            compiled.get_volatility_override("src/web/server.rs"),
            Some(Volatility::Low)
        );

        // Unclassified → None
        assert_eq!(compiled.get_subdomain("src/other.rs"), None);
        assert_eq!(compiled.get_volatility_override("src/other.rs"), None);
    }

    #[test]
    fn test_subdomain_display() {
        assert_eq!(format!("{}", Subdomain::Core), "Core");
        assert_eq!(format!("{}", Subdomain::Supporting), "Supporting");
        assert_eq!(format!("{}", Subdomain::Generic), "Generic");
    }

    #[test]
    fn test_subdomain_expected_volatility() {
        assert_eq!(Subdomain::Core.expected_volatility(), Volatility::High);
        assert_eq!(Subdomain::Supporting.expected_volatility(), Volatility::Low);
        assert_eq!(Subdomain::Generic.expected_volatility(), Volatility::Low);
    }

    #[test]
    fn test_has_subdomain_config() {
        // Empty config → no subdomain config
        let compiled = CompiledConfig::empty();
        assert!(!compiled.has_subdomain_config());

        // With core patterns → has subdomain config
        let toml = r#"
            [subdomains]
            core = ["src/analyzer.rs"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_subdomain_config());

        // With only supporting patterns → has subdomain config
        let toml = r#"
            [subdomains]
            supporting = ["src/report.rs"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_subdomain_config());

        // With only generic patterns → has subdomain config
        let toml = r#"
            [subdomains]
            generic = ["src/web/*"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_subdomain_config());
    }

    #[test]
    fn test_has_volatility_overrides() {
        // Empty config → no overrides
        let compiled = CompiledConfig::empty();
        assert!(!compiled.has_volatility_overrides());

        // With high volatility → has overrides
        let toml = r#"
            [volatility]
            high = ["src/core.rs"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_volatility_overrides());

        // With medium volatility → has overrides
        let toml = r#"
            [volatility]
            medium = ["src/mid.rs"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_volatility_overrides());

        // With low volatility → has overrides
        let toml = r#"
            [volatility]
            low = ["src/stable.rs"]
        "#;
        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        assert!(compiled.has_volatility_overrides());
    }

    #[test]
    fn test_volatility_override_beats_subdomain() {
        let toml = r#"
            [volatility]
            low = ["src/analyzer.rs"]

            [subdomains]
            core = ["src/analyzer.rs"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let mut compiled = CompiledConfig::from_config(config).unwrap();

        // Explicit volatility override wins over subdomain classification
        assert_eq!(
            compiled.get_volatility_override("src/analyzer.rs"),
            Some(Volatility::Low)
        );
    }

    #[test]
    fn dead_patterns_reports_only_unmatched_patterns_by_section() {
        let toml = r#"
            [analysis]
            prelude_modules = ["src/lib.rs", "src/missing_prelude.rs"]
            exclude = ["src/never_matches/**"]

            [volatility]
            high = ["src/core/**"]
            medium = ["src/medium.rs"]
            low = ["src/stable.rs"]

            [subdomains]
            core = ["src/core/**", "src/old_core.rs"]
            supporting = ["src/supporting.rs"]
            generic = ["src/generic.rs"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();
        let candidate_paths = vec![
            "src/lib.rs".to_string(),
            "src/core/mod.rs".to_string(),
            "src/supporting.rs".to_string(),
            "src/stable.rs".to_string(),
        ];

        let dead = compiled.dead_patterns(&candidate_paths);

        assert_eq!(
            dead,
            vec![
                DeadConfigPattern {
                    section: "subdomains.core",
                    pattern: "src/old_core.rs".to_string(),
                },
                DeadConfigPattern {
                    section: "subdomains.generic",
                    pattern: "src/generic.rs".to_string(),
                },
                DeadConfigPattern {
                    section: "volatility.medium",
                    pattern: "src/medium.rs".to_string(),
                },
            ]
        );
    }

    #[test]
    fn dead_patterns_never_reports_exclude_or_prelude() {
        // A dead exclude analyzes nothing wrongly (defensive future-proof excludes are
        // idiomatic) and a dead prelude exemption surfaces as visible warnings, so
        // neither is drift.
        let toml = r#"
            [analysis]
            prelude_modules = ["src/missing_prelude.rs"]
            exclude = ["src/never_matches/**"]
        "#;

        let config: CouplingConfig = toml::from_str(toml).unwrap();
        let compiled = CompiledConfig::from_config(config).unwrap();

        assert!(
            compiled
                .dead_patterns(&["src/lib.rs".to_string()])
                .is_empty()
        );
    }

    #[test]
    fn empty_config_has_no_dead_patterns() {
        let candidate_paths = vec!["src/lib.rs".to_string()];
        assert!(
            CompiledConfig::empty()
                .dead_patterns(&candidate_paths)
                .is_empty()
        );
    }
}