garbage-code-hunter 0.2.2

A humorous Rust code quality detector that roasts your garbage 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
//! StyleFinding — the structured representation of a code style observation.
//!
//! Evolves from the raw `CodeIssue` to include confidence, evidence,
//! category context, and actionable suggestions. This is the standard
//! data model for all outputs (terminal, JSON, Markdown, CI, etc.).

use crate::analyzer::{CodeIssue, Severity};
use crate::signals::{classify_rule, StyleProfile, StyleSignal};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;

// ── Identity ─────────────────────────────────────────────────────

/// Unique identifier for a finding.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FindingId(String);

impl FindingId {
    pub fn new(seed: &str) -> Self {
        let mut hasher = std::hash::DefaultHasher::new();
        seed.hash(&mut hasher);
        Self(format!("{:016x}", hasher.finish())[..12].to_string())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

// ── Location ─────────────────────────────────────────────────────

/// Location in source code with optional span and symbol name.
#[derive(Debug, Clone)]
pub struct CodeLocation {
    pub file_path: PathBuf,
    pub line: usize,
    pub column: usize,
    pub span: Option<TextSpan>,
    pub symbol_name: Option<String>,
}

/// A contiguous range of text in source code.
#[derive(Debug, Clone)]
pub struct TextSpan {
    pub start_line: usize,
    pub start_column: usize,
    pub end_line: usize,
    pub end_column: usize,
}

// ── Rule Metadata ────────────────────────────────────────────────

/// Meta information about the rule that triggered the finding.
#[derive(Debug, Clone)]
pub struct RuleMeta {
    pub name: String,
    pub category: StyleCategory,
    pub intent: RuleIntent,
}

/// Code style categories — what aspect of the code is being evaluated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StyleCategory {
    Naming,
    Complexity,
    Duplication,
    Comments,
    DebuggingLeftovers,
    Structure,
    Consistency,
    DependencyStyle,
}

impl StyleCategory {
    pub fn display_name(&self) -> &'static str {
        match self {
            StyleCategory::Naming => "Naming",
            StyleCategory::Complexity => "Complexity",
            StyleCategory::Duplication => "Duplication",
            StyleCategory::Comments => "Comments",
            StyleCategory::DebuggingLeftovers => "Debugging Leftovers",
            StyleCategory::Structure => "Structure",
            StyleCategory::Consistency => "Consistency",
            StyleCategory::DependencyStyle => "Dependency Style",
        }
    }
}

/// Intent behind a rule — why this rule exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleIntent {
    Readability,
    Maintainability,
    TeamConvention,
    NoiseReduction,
    CognitiveLoad,
}

impl RuleIntent {
    pub fn display_name(&self) -> &'static str {
        match self {
            RuleIntent::Readability => "Readability",
            RuleIntent::Maintainability => "Maintainability",
            RuleIntent::TeamConvention => "Team Convention",
            RuleIntent::NoiseReduction => "Noise Reduction",
            RuleIntent::CognitiveLoad => "Cognitive Load",
        }
    }
}

// ── Confidence ──────────────────────────────────────────────────

/// How confident we are that this is a real issue vs. a false positive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Confidence {
    Low,
    Medium,
    High,
}

impl Confidence {
    pub fn display_name(&self) -> &'static str {
        match self {
            Confidence::Low => "Low",
            Confidence::Medium => "Medium",
            Confidence::High => "High",
        }
    }

    pub fn score(&self) -> f64 {
        match self {
            Confidence::Low => 0.3,
            Confidence::Medium => 0.6,
            Confidence::High => 1.0,
        }
    }
}

// ── Evidence ────────────────────────────────────────────────────

/// Evidence supporting the finding.
#[derive(Debug, Clone)]
pub struct Evidence {
    pub snippet: Option<String>,
    pub metric: Option<EvidenceMetric>,
    pub nearby_context: Vec<String>,
}

/// A numeric metric with threshold comparison.
#[derive(Debug, Clone)]
pub struct EvidenceMetric {
    pub name: String,
    pub value: f64,
    pub threshold: f64,
    pub unit: String,
}

// ── Suggestion ──────────────────────────────────────────────────

/// A suggested fix or improvement for the finding.
#[derive(Debug, Clone)]
pub struct StyleSuggestion {
    pub title: String,
    pub explanation: String,
    pub quick_fix_hint: Option<String>,
    pub safer_alternative: Option<String>,
}

// ── StyleFinding ────────────────────────────────────────────────

/// The core finding model — a structured observation about code style.
///
/// Each finding represents one detected issue with full metadata
/// for presentation, filtering, and educational feedback.
#[derive(Debug, Clone)]
pub struct StyleFinding {
    pub id: FindingId,
    pub location: CodeLocation,
    pub rule: RuleMeta,
    pub signal: StyleSignal,
    pub severity: Severity,
    pub confidence: Confidence,
    pub evidence: Evidence,
    pub suggestion: Option<StyleSuggestion>,
}

impl StyleFinding {
    /// Create a finding from a signal-level detection (no single-line location).
    pub fn for_signal(signal: StyleSignal, violation_count: usize, file_path: PathBuf) -> Self {
        let id = FindingId::new(&format!(
            "signal:{:?}:{violation_count}:{}",
            signal,
            file_path.display()
        ));
        let severity = if violation_count > 10 {
            Severity::Nuclear
        } else if violation_count > 3 {
            Severity::Spicy
        } else {
            Severity::Mild
        };
        StyleFinding {
            id,
            location: CodeLocation {
                file_path,
                line: 0,
                column: 0,
                span: None,
                symbol_name: None,
            },
            rule: RuleMeta {
                name: signal.display_name().to_string(),
                category: StyleCategory::Consistency,
                intent: RuleIntent::Maintainability,
            },
            signal,
            severity,
            confidence: Confidence::High,
            evidence: Evidence {
                snippet: Some(format!(
                    "{violation_count} {} violations",
                    signal.display_name()
                )),
                metric: Some(EvidenceMetric {
                    name: "violations".to_string(),
                    value: violation_count as f64,
                    threshold: 0.0,
                    unit: "count".to_string(),
                }),
                nearby_context: Vec::new(),
            },
            suggestion: None,
        }
    }

    /// Convert back to a `CodeIssue` for downstream consumers that
    /// still depend on the legacy issue model.
    pub fn to_code_issue(&self) -> CodeIssue {
        CodeIssue {
            file_path: self.location.file_path.clone(),
            line: self.location.line,
            column: self.location.column,
            rule_name: self.rule.name.clone(),
            message: self
                .evidence
                .snippet
                .clone()
                .unwrap_or_else(|| format!("{:?}", self.signal)),
            severity: self.severity.clone(),
        }
    }
}

impl From<&CodeIssue> for StyleFinding {
    fn from(issue: &CodeIssue) -> Self {
        let id = FindingId::new(&format!(
            "{}:{}:{}:{}",
            issue.file_path.display(),
            issue.line,
            issue.rule_name,
            issue.message,
        ));
        let signal = classify_rule(&issue.rule_name);
        let location = CodeLocation {
            file_path: issue.file_path.clone(),
            line: issue.line,
            column: issue.column,
            span: None,
            symbol_name: None,
        };
        let rule = RuleMeta {
            name: issue.rule_name.clone(),
            category: rule_to_category(&issue.rule_name),
            intent: rule_to_intent(&issue.rule_name),
        };
        let confidence = rule_to_confidence(&issue.rule_name);
        let evidence = Evidence {
            snippet: Some(issue.message.clone()),
            metric: None,
            nearby_context: Vec::new(),
        };

        StyleFinding {
            id,
            location,
            rule,
            signal,
            severity: issue.severity.clone(),
            confidence,
            evidence,
            suggestion: None,
        }
    }
}

// ── Category / Intent / Confidence mapping ──────────────────────

fn rule_to_category(rule_name: &str) -> StyleCategory {
    match rule_name {
        n if n.contains("naming")
            || n.contains("letter")
            || n.contains("hungarian")
            || n.contains("abbreviation")
            || n.contains("name")
            || n.contains("predicate") =>
        {
            StyleCategory::Naming
        }
        n if n.contains("nest")
            || n.contains("complex")
            || n.contains("function_length")
            || n.contains("long-function")
            || n.contains("god-function")
            || n.contains("too-many-params")
            || n.contains("module-complexity")
            || n.contains("trait-complexity") =>
        {
            StyleCategory::Complexity
        }
        n if n.contains("duplicat") => StyleCategory::Duplication,
        n if n.contains("todo")
            || n.contains("fixme")
            || n.contains("commented")
            || n.contains("dead-code") =>
        {
            StyleCategory::Comments
        }
        n if n.contains("println")
            || n.contains("unwrap")
            || n.contains("panic")
            || n.contains("except")
            || n.contains("rescue") =>
        {
            StyleCategory::DebuggingLeftovers
        }
        n if n.contains("file-too-long")
            || n.contains("module-nesting")
            || n.contains("import") =>
        {
            StyleCategory::Structure
        }
        n if n.contains("generic") || n.contains("magic") || n.contains("constant-name") => {
            StyleCategory::Consistency
        }
        _ => StyleCategory::Consistency,
    }
}

fn rule_to_intent(rule_name: &str) -> RuleIntent {
    match rule_name {
        n if n.contains("naming")
            || n.contains("letter")
            || n.contains("name")
            || n.contains("hungarian")
            || n.contains("abbreviation") =>
        {
            RuleIntent::Readability
        }
        n if n.contains("nest")
            || n.contains("complex")
            || n.contains("long-function")
            || n.contains("god-function")
            || n.contains("too-many-params") =>
        {
            RuleIntent::CognitiveLoad
        }
        n if n.contains("duplicat") => RuleIntent::Maintainability,
        n if n.contains("todo")
            || n.contains("fixme")
            || n.contains("commented")
            || n.contains("dead-code") =>
        {
            RuleIntent::NoiseReduction
        }
        n if n.contains("println")
            || n.contains("unwrap")
            || n.contains("panic")
            || n.contains("except")
            || n.contains("rescue") =>
        {
            RuleIntent::NoiseReduction
        }
        n if n.contains("magic") || n.contains("constant-name") || n.contains("generic") => {
            RuleIntent::Maintainability
        }
        _ => RuleIntent::Readability,
    }
}

fn rule_to_confidence(rule_name: &str) -> Confidence {
    // High-confidence: objectively measurable
    if matches!(
        rule_name,
        "magic-number"
            | "code-duplication"
            | "cross-file-duplication"
            | "unwrap-abuse"
            | "panic-abuse"
            | "empty-catch"
            | "bare-except"
            | "bare-rescue"
            | "println-debugging"
            | "dead-code"
            | "commented-code"
            | "file-too-long"
    ) {
        return Confidence::High;
    }

    // Medium-confidence: measurable but context-dependent
    if matches!(
        rule_name,
        "deep-nesting"
            | "cyclomatic-complexity"
            | "complex-closure"
            | "long-function"
            | "god-function"
            | "too-many-params"
            | "module-complexity"
            | "trait-complexity"
            | "todo-comment"
            | "todo-fixme"
            | "todo-bug"
            | "todo-hack"
    ) {
        return Confidence::Medium;
    }

    // Low-confidence: subjective / style preference
    Confidence::Low
}

// ── Universal Style IR ──────────────────────────────────────────
//
// These functions build StyleProfile directly from StyleFinding[*].signal,
// without needing classify_rule(). This is the language-agnostic Style IR
// path — any language that produces StyleFindings gets signal scoring and
// personality inference for free.

/// Compute signal scores from findings using each finding's `.signal` field
/// (language-agnostic, no classify_rule() needed).
pub fn compute_signal_scores_from_findings(
    findings: &[StyleFinding],
    total_lines: usize,
) -> HashMap<StyleSignal, f64> {
    let k_lines = (total_lines as f64 / 1000.0).max(0.001);
    let mut counts: HashMap<StyleSignal, usize> = HashMap::new();

    for finding in findings {
        *counts.entry(finding.signal).or_insert(0) += 1;
    }

    let mut scores = HashMap::new();
    for signal in StyleSignal::all() {
        let count = counts.get(signal).copied().unwrap_or(0);
        let density = count as f64 / k_lines;
        let score = ((density + 1.0).log2() * 6.0).min(25.0);
        scores.insert(*signal, score);
    }

    scores
}

/// Build a StyleProfile directly from findings (language-agnostic).
pub fn build_profile_from_findings(findings: &[StyleFinding], total_lines: usize) -> StyleProfile {
    let signal_scores = compute_signal_scores_from_findings(findings, total_lines);
    StyleProfile::from_signal_scores(signal_scores)
}

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

    fn make_issue(rule: &str) -> CodeIssue {
        CodeIssue {
            file_path: PathBuf::from("src/main.rs"),
            line: 42,
            column: 5,
            rule_name: rule.to_string(),
            message: format!("{rule} detected"),
            severity: Severity::Spicy,
        }
    }

    // ── FindingId ─────────────────────────────────────────────────

    /// Objective: Verify FindingId is 12-char hex from blake3 hash.
    #[test]
    fn test_finding_id_format() {
        let id = FindingId::new("test-seed");
        assert_eq!(id.as_str().len(), 12, "id should be 12 hex chars");
        assert!(id.as_str().chars().all(|c| c.is_ascii_hexdigit()));
    }

    /// Objective: Verify same seed produces same id.
    #[test]
    fn test_finding_id_deterministic() {
        let a = FindingId::new("hello");
        let b = FindingId::new("hello");
        assert_eq!(a, b);
    }

    /// Objective: Verify different seeds produce different ids.
    #[test]
    fn test_finding_id_distinct() {
        let a = FindingId::new("hello");
        let b = FindingId::new("world");
        assert_ne!(a, b);
    }

    // ── Category mapping ─────────────────────────────────────────

    /// Objective: Verify naming-related rules map to StyleCategory::Naming.
    #[test]
    fn test_category_naming() {
        for name in &[
            "terrible-naming",
            "single-letter-variable",
            "meaningless-naming",
            "hungarian-notation",
            "abbreviation-abuse",
            "go-receiver-name",
            "ruby-predicate-method",
        ] {
            assert_eq!(
                rule_to_category(name),
                StyleCategory::Naming,
                "{name} should be Naming"
            );
        }
    }

    /// Objective: Verify complexity rules map to Complexity.
    #[test]
    fn test_category_complexity() {
        for name in &[
            "deep-nesting",
            "cyclomatic-complexity",
            "complex-closure",
            "long-function",
            "god-function",
            "too-many-params",
            "module-complexity",
        ] {
            assert_eq!(
                rule_to_category(name),
                StyleCategory::Complexity,
                "{name} should be Complexity"
            );
        }
    }

    /// Objective: Verify duplication rules map to Duplication.
    #[test]
    fn test_category_duplication() {
        assert_eq!(
            rule_to_category("code-duplication"),
            StyleCategory::Duplication
        );
        assert_eq!(
            rule_to_category("cross-file-duplication"),
            StyleCategory::Duplication
        );
    }

    // ── Confidence mapping ───────────────────────────────────────

    /// Objective: Verify objectively measurable rules return High confidence.
    #[test]
    fn test_confidence_high() {
        for name in &[
            "magic-number",
            "code-duplication",
            "unwrap-abuse",
            "empty-catch",
            "dead-code",
        ] {
            assert_eq!(
                rule_to_confidence(name),
                Confidence::High,
                "{name} should be High confidence"
            );
        }
    }

    /// Objective: Verify context-dependent rules return Medium confidence.
    #[test]
    fn test_confidence_medium() {
        for name in &[
            "deep-nesting",
            "long-function",
            "todo-comment",
            "too-many-params",
        ] {
            assert_eq!(
                rule_to_confidence(name),
                Confidence::Medium,
                "{name} should be Medium confidence"
            );
        }
    }

    /// Objective: Verify subjective rules return Low confidence.
    #[test]
    fn test_confidence_low() {
        for name in &[
            "terrible-naming",
            "single-letter-variable",
            "abbreviation-abuse",
            "go-receiver-name",
        ] {
            assert_eq!(
                rule_to_confidence(name),
                Confidence::Low,
                "{name} should be Low confidence"
            );
        }
    }

    // ── StyleFinding conversion ──────────────────────────────────

    /// Objective: Verify From<&CodeIssue> produces correct fields.
    #[test]
    fn test_finding_from_issue_basic() {
        let issue = make_issue("unwrap-abuse");
        let finding = StyleFinding::from(&issue);
        assert_eq!(finding.location.file_path, PathBuf::from("src/main.rs"));
        assert_eq!(finding.location.line, 42);
        assert_eq!(finding.rule.name, "unwrap-abuse");
        assert_eq!(finding.signal, StyleSignal::PanicAddiction);
        assert_eq!(finding.severity, Severity::Spicy);
        assert_eq!(finding.confidence, Confidence::High);
    }

    /// Objective: Verify finding ID is deterministic for same input.
    #[test]
    fn test_finding_id_from_issue_deterministic() {
        let issue = make_issue("deep-nesting");
        let a = StyleFinding::from(&issue).id;
        let b = StyleFinding::from(&issue).id;
        assert_eq!(a, b, "same issue should produce same finding id");
    }

    /// Objective: Verify rule_to_category falls back to Consistency for unmatched rules.
    #[test]
    fn test_category_fallback_consistency() {
        let cat = rule_to_category("zzz-unmatched-rule");
        assert_eq!(cat, StyleCategory::Consistency);
    }

    /// Objective: Verify rule_to_intent handles known and unknown rules.
    #[test]
    fn test_intent_mapping() {
        assert_eq!(rule_to_intent("deep-nesting"), RuleIntent::CognitiveLoad);
        assert_eq!(rule_to_intent("unwrap-abuse"), RuleIntent::NoiseReduction);
        assert_eq!(
            rule_to_intent("code-duplication"),
            RuleIntent::Maintainability
        );
        assert_eq!(rule_to_intent("terrible-naming"), RuleIntent::Readability);
    }

    /// Objective: Verify Confidence score values.
    #[test]
    fn test_confidence_score_values() {
        assert!((Confidence::High.score() - 1.0).abs() < f64::EPSILON);
        assert!((Confidence::Medium.score() - 0.6).abs() < f64::EPSILON);
        assert!((Confidence::Low.score() - 0.3).abs() < f64::EPSILON);
    }

    /// Objective: Verify display_name methods return non-empty strings.
    #[test]
    fn test_display_names_non_empty() {
        for cat in &[
            StyleCategory::Naming,
            StyleCategory::Complexity,
            StyleCategory::Duplication,
            StyleCategory::Comments,
            StyleCategory::DebuggingLeftovers,
            StyleCategory::Structure,
            StyleCategory::Consistency,
            StyleCategory::DependencyStyle,
        ] {
            assert!(
                !cat.display_name().is_empty(),
                "{:?} display_name empty",
                cat
            );
        }
        for intent in &[
            RuleIntent::Readability,
            RuleIntent::Maintainability,
            RuleIntent::TeamConvention,
            RuleIntent::NoiseReduction,
            RuleIntent::CognitiveLoad,
        ] {
            assert!(
                !intent.display_name().is_empty(),
                "{:?} display_name empty",
                intent
            );
        }
        for conf in &[Confidence::Low, Confidence::Medium, Confidence::High] {
            assert!(
                !conf.display_name().is_empty(),
                "{:?} display_name empty",
                conf
            );
        }
    }

    /// Objective: Verify evidence snippet comes from issue message.
    #[test]
    fn test_evidence_snippet() {
        let issue = make_issue("deep-nesting");
        let finding = StyleFinding::from(&issue);
        assert_eq!(
            finding.evidence.snippet.as_deref(),
            Some("deep-nesting detected")
        );
    }

    /// Objective: Verify suggestion is None by default for From<CodeIssue>.
    #[test]
    fn test_suggestion_default_none() {
        let issue = make_issue("long-function");
        let finding = StyleFinding::from(&issue);
        assert!(finding.suggestion.is_none());
    }

    // ── Universal Style IR ────────────────────────────────────────

    fn finding(signal: StyleSignal, severity: Severity) -> StyleFinding {
        let issue = CodeIssue {
            file_path: PathBuf::from("test.rs"),
            line: 1,
            column: 1,
            rule_name: format!("{:?}", signal).to_lowercase(),
            message: "test".to_string(),
            severity,
        };
        // Override signal since rule_name won't map correctly
        let mut f = StyleFinding::from(&issue);
        f.signal = signal;
        f
    }

    /// Objective: Verify compute_signal_scores_from_findings counts signals correctly.
    #[test]
    fn test_signal_scores_from_findings() {
        let findings = vec![
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Spicy),
            finding(StyleSignal::PanicAddiction, Severity::Mild),
        ];
        let scores = compute_signal_scores_from_findings(&findings, 1000);
        assert!(
            *scores.get(&StyleSignal::Duplication).unwrap_or(&0.0)
                > *scores.get(&StyleSignal::PanicAddiction).unwrap_or(&0.0),
            "Duplication (2 count) should score higher than PanicAddiction (1 count)"
        );
    }

    /// Objective: Verify compute_signal_scores_from_findings returns 0 for empty input.
    #[test]
    fn test_signal_scores_from_findings_empty() {
        let scores = compute_signal_scores_from_findings(&[], 1000);
        for signal in StyleSignal::all() {
            assert_eq!(
                scores.get(signal).copied().unwrap_or(0.0),
                0.0,
                "empty findings => all signal scores 0"
            );
        }
    }

    /// Objective: Verify build_profile_from_findings produces correct dominant signal.
    #[test]
    fn test_build_profile_from_findings_dominant() {
        let findings = vec![
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::NestedHell, Severity::Mild),
        ];
        let profile = build_profile_from_findings(&findings, 1000);
        assert_eq!(
            profile.dominant_signal,
            Some(StyleSignal::Duplication),
            "3 duplicates vs 1 nested => Duplication should be dominant"
        );
    }

    /// Objective: Verify build_profile_from_findings allows personality inference.
    #[test]
    fn test_build_profile_from_findings_personality() {
        let findings = vec![
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
            finding(StyleSignal::Duplication, Severity::Nuclear),
        ];
        let profile = build_profile_from_findings(&findings, 100);
        let personality = profile.infer_personality_type();
        assert_eq!(
            personality, "The Copy-Paste Artist",
            "massive duplication => Copy-Paste Artist, got {personality}"
        );
    }
}