cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! Health score: a single 0–100 number plus letter grade summarizing
//! severity-weighted, LOC-density-normalized findings (see todo.md §4
//! "Health Score & Decision Surface").
//!
//! Only *gating* findings are scored (see
//! [`crate::finding::EvidenceClass::is_gating`]): heuristic findings are
//! advisory by default (todo.md §17.2, §17.5) and produce no deduction, so
//! the score speaks only about `derived_fact`/`bounded_semantic`/
//! `external_measurement` findings.
//!
//! Deliberately narrow, matching §4's own guardrails:
//! 1. **Erklärbar** — every input (fail/warn counts, total LOC, deduction) is
//!    carried on [`HealthScore`] alongside the score, not hidden inside an
//!    opaque formula.
//! 2. **Nicht optimierbar** — weights are fixed per severity
//!    ([`FAIL_WEIGHT`]/[`WARN_WEIGHT`]), not configurable per rule, so
//!    there's no per-rule knob to game.
//! 3. **Kontextrelativ** — crate-type profiles are opt-in via `judge.toml`
//!    (`[[crate_profile]]`, see [`crate::rules::boundaries::CrateProfile`]), not
//!    auto-guessed from crate contents.
//! 4. **Trend vor Absolutwert** — [`trend`] recomputes the same formula over
//!    a saved baseline's stored findings, but only under the same formula
//!    and profile conditions ([`ScoreContext`]); otherwise the trend is
//!    explicitly [`Trend::NotComparable`] instead of a false delta.
//!
//! An incomplete basis never scores: unreadable source files are a
//! [`LocError`], a zero-LOC workspace is [`ScoreOutcome::Unavailable`], and
//! an out-of-range `deduction_multiplier` is rejected at deserialization
//! (see todo.md §15.1) — all three are errors, not perfect scores.

use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::baseline::Baseline;
use crate::rules::boundaries::CrateProfile;
use crate::finding::{Finding, Severity};
use crate::ingest::{CrateInfo, SourceFile, Workspace};

/// Fixed per-severity deduction weight (see module docs, point 2 — not
/// configurable per rule).
pub const FAIL_WEIGHT: f64 = 10.0;
pub const WARN_WEIGHT: f64 = 3.0;

/// Version of the score formula itself (severity weights, density
/// normalization, grade cutoffs). Stored on saved baselines via
/// [`ScoreContext`] so a trend is only computed when both scores used the
/// same formula — bump this on any formula change.
///
/// v2: heuristic findings no longer deduct — the score covers only gating
/// findings (see module docs). Baselines scored under v1 are
/// [`Trend::NotComparable`], not a false delta.
pub const SCORE_FORMULA_VERSION: u32 = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Grade {
    A,
    B,
    C,
    D,
    F,
}

impl Grade {
    fn from_score(score: f64) -> Self {
        if score >= 90.0 {
            Self::A
        } else if score >= 80.0 {
            Self::B
        } else if score >= 70.0 {
            Self::C
        } else if score >= 60.0 {
            Self::D
        } else {
            Self::F
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::A => "A",
            Self::B => "B",
            Self::C => "C",
            Self::D => "D",
            Self::F => "F",
        }
    }
}

/// A crate profile's validated deduction multiplier (see
/// [`crate::rules::boundaries::CrateProfile`] and module docs, point 3).
///
/// Valid range: finite and within `(0.0, 10.0]`. Zero or negative values
/// would silently erase findings from the score, `NaN`/infinite values would
/// poison every downstream sum, and anything above [`Self::MAX`] is beyond
/// any sensible strictness scaling — all of these are config errors
/// (rejected by [`TryFrom`] and therefore at deserialization), not scores.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "f64", into = "f64")]
pub struct DeductionMultiplier(f64);

impl DeductionMultiplier {
    /// Upper bound of the valid range `(0.0, MAX]`.
    pub const MAX: f64 = 10.0;

    pub fn value(self) -> f64 {
        self.0
    }
}

impl Default for DeductionMultiplier {
    /// `1.0` — findings count unscaled (crates not named in any profile).
    fn default() -> Self {
        Self(1.0)
    }
}

impl TryFrom<f64> for DeductionMultiplier {
    type Error = String;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        if value.is_finite() && value > 0.0 && value <= Self::MAX {
            Ok(Self(value))
        } else {
            Err(format!(
                "deduction_multiplier must be finite and within (0.0, {}], got {value}",
                Self::MAX
            ))
        }
    }
}

impl From<DeductionMultiplier> for f64 {
    fn from(multiplier: DeductionMultiplier) -> Self {
        multiplier.0
    }
}

/// A computed health score: every number that went into it, so the result
/// stays explainable (see module docs, point 1).
#[derive(Debug, Clone, Serialize)]
pub struct HealthScore {
    pub score: f64,
    pub grade: Grade,
    pub total_loc: usize,
    pub fail_count: usize,
    pub warn_count: usize,
    /// The density-normalized deduction subtracted from 100 to get `score`.
    pub deduction: f64,
}

/// Why a health score could not be computed (see [`ScoreOutcome`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScoreReason {
    /// Zero authored LOC — the density normalization has no denominator, so
    /// any score (least of all a perfect 100/A) would be fabricated.
    NoAuthoredLoc,
}

impl std::fmt::Display for ScoreReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoAuthoredLoc => {
                write!(
                    f,
                    "no authored lines of code were analyzed (nothing to score)"
                )
            }
        }
    }
}

/// A health score, or the explicit reason there isn't one — an incomplete
/// basis produces [`ScoreOutcome::Unavailable`], never a perfect default
/// (see todo.md §15.1). The CLI turns `Unavailable` into `exit 2`, matching
/// `IngestError`/`GitError`/`BaselineError`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScoreOutcome {
    Available(HealthScore),
    Unavailable(ScoreReason),
}

/// `total_loc` must be non-zero — [`compute`] and [`trend`] guard that
/// before calling (a zero denominator is [`ScoreOutcome::Unavailable`], not
/// a division).
fn score_from(
    fail_count: usize,
    warn_count: usize,
    deduction: f64,
    total_loc: usize,
) -> HealthScore {
    let density_deduction = deduction / (total_loc as f64 / 1000.0);
    let score = (100.0 - density_deduction).clamp(0.0, 100.0);

    HealthScore {
        score,
        grade: Grade::from_score(score),
        total_loc,
        fail_count,
        warn_count,
        deduction: density_deduction,
    }
}

/// A source file that could not be read while counting the LOC denominator —
/// surfaced instead of silently under-counting, which would shrink the
/// denominator and distort the score (see todo.md §15.1). The CLI turns this
/// into `exit 2`, matching `IngestError`/`GitError`/`BaselineError`.
#[derive(Debug)]
pub struct LocError {
    pub path: PathBuf,
    pub source: std::io::Error,
}

impl std::fmt::Display for LocError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.path.display(), self.source)
    }
}

impl std::error::Error for LocError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

/// Counts authored lines of code across `workspace` (generated files are
/// excluded, same policy as `complexity`/`duplication`, see todo.md §3.A) —
/// the denominator for density-normalized deductions.
///
/// Unreadable files are silently skipped; score paths must use
/// [`total_authored_loc_checked`] instead, so a read failure can never
/// masquerade as a smaller codebase.
pub fn total_authored_loc(workspace: &Workspace) -> usize {
    count_loc(authored_source_files(workspace))
}

/// Like [`total_authored_loc`], but a read failure is a [`LocError`] instead
/// of a silently skipped file (see todo.md §15.1).
pub fn total_authored_loc_checked(workspace: &Workspace) -> Result<usize, LocError> {
    authored_source_files(workspace)
        .map(|file| {
            std::fs::read_to_string(&file.path)
                .map(|content| content.lines().count())
                .map_err(|err| LocError {
                    path: file.path.clone(),
                    source: err,
                })
        })
        .sum()
}

/// Like [`total_authored_loc`], but scoped to `files` (repository-root
/// relative paths — see [`crate::git::changed_files_since`]) — the LOC
/// denominator for a ratio gate judged against only what changed (see
/// `audit --since`, todo.md §6), not the whole workspace total.
pub fn authored_loc_in(workspace: &Workspace, files: &HashSet<PathBuf>) -> usize {
    count_loc(authored_source_files(workspace).filter(|file| {
        file.path
            .strip_prefix(&workspace.root)
            .is_ok_and(|relative| files.contains(relative))
    }))
}

/// Every authored (non-generated) source file across `workspace` — the
/// shared starting point for [`total_authored_loc`], [`total_authored_loc_checked`],
/// and [`authored_loc_in`], which otherwise only differ in how they turn
/// file contents into a count.
fn authored_source_files(workspace: &Workspace) -> impl Iterator<Item = &SourceFile> {
    workspace
        .crates
        .iter()
        .flat_map(|krate| krate.source_files.iter())
        .filter(|file| file.kind.is_locally_reportable())
}

/// Reads and sums line counts across `files`, silently skipping unreadable
/// ones — the read-and-count core [`total_authored_loc`] and
/// [`authored_loc_in`] share exactly; they differ only in which files they
/// pass in.
fn count_loc<'a>(files: impl Iterator<Item = &'a SourceFile>) -> usize {
    files
        .filter_map(|file| std::fs::read_to_string(&file.path).ok())
        .map(|content| content.lines().count())
        .sum()
}

/// Finds the workspace crate that owns `file` — the one whose `root` is the
/// longest matching prefix, to handle nested crates correctly. Returns
/// `None` for findings that aren't inside any single crate's directory
/// (e.g. a boundary violation, whose location is the workspace root
/// `Cargo.toml` in a multi-crate workspace) — those get the default `1.0`
/// multiplier.
fn crate_for_file<'a>(workspace: &'a Workspace, file: &Path) -> Option<&'a CrateInfo> {
    workspace
        .crates
        .iter()
        .filter(|krate| file.starts_with(&krate.root))
        .max_by_key(|krate| krate.root.as_os_str().len())
}

/// The deduction multiplier for a finding in `file`: the first profile in
/// `crate_profiles` naming the owning crate wins, and files outside any
/// profiled crate get the default `1.0`.
fn multiplier_for(
    workspace: &Workspace,
    file: &Path,
    crate_profiles: &[CrateProfile],
) -> DeductionMultiplier {
    crate_for_file(workspace, file)
        .and_then(|krate| {
            crate_profiles
                .iter()
                .find(|profile| profile.crates.iter().any(|name| name == &krate.name))
        })
        .map_or_else(DeductionMultiplier::default, |profile| {
            profile.deduction_multiplier
        })
}

/// Computes a [`HealthScore`] from `findings` (only *gating* `Fail`/`Warn`
/// findings count — `Info` findings are descriptive and heuristic findings
/// advisory, neither is scored, matching `baseline::Delta::verdict`'s same
/// carve-outs) and `total_loc`, scaling each
/// finding's deduction by its crate's `deduction_multiplier` from
/// `crate_profiles`, if configured (default `1.0`). A `total_loc` of zero is
/// [`ScoreOutcome::Unavailable`] — even with fail findings there is no basis
/// for a score, least of all a perfect one (see todo.md §15.1).
pub fn compute(
    findings: &[Finding],
    total_loc: usize,
    workspace: &Workspace,
    crate_profiles: &[CrateProfile],
) -> ScoreOutcome {
    if total_loc == 0 {
        return ScoreOutcome::Unavailable(ScoreReason::NoAuthoredLoc);
    }

    let (fail_count, warn_count, deduction) = tally_deductions(
        findings
            .iter()
            .filter(|finding| finding.is_gating())
            .map(|finding| {
                (
                    finding.severity,
                    multiplier_for(workspace, &finding.location.file, crate_profiles),
                )
            }),
    );

    ScoreOutcome::Available(score_from(fail_count, warn_count, deduction, total_loc))
}

/// Scores one gating finding's `severity` as a fail/warn deduction weight,
/// bumping the matching counter. `None` for `Info`, which is never scored.
fn score_severity(severity: Severity, fail_count: &mut usize, warn_count: &mut usize) -> Option<f64> {
    match severity {
        Severity::Fail => {
            *fail_count += 1;
            Some(FAIL_WEIGHT)
        }
        Severity::Warn => {
            *warn_count += 1;
            Some(WARN_WEIGHT)
        }
        Severity::Info => None,
    }
}

/// Tallies fail/warn counts and total weighted deduction across `entries` —
/// the accumulation loop [`compute`] and [`trend`] share exactly; they differ
/// only in what a "finding" is and how it's turned into a `(Severity,
/// DeductionMultiplier)` pair before reaching here.
fn tally_deductions(
    entries: impl Iterator<Item = (Severity, DeductionMultiplier)>,
) -> (usize, usize, f64) {
    let mut fail_count = 0;
    let mut warn_count = 0;
    let mut deduction = 0.0;
    for (severity, multiplier) in entries {
        let Some(weight) = score_severity(severity, &mut fail_count, &mut warn_count) else {
            continue;
        };
        deduction += weight * multiplier.value();
    }
    (fail_count, warn_count, deduction)
}

/// The score-formula conditions a baseline's findings were saved under:
/// formula version plus the effective `judge.toml` crate-profile
/// multipliers. A trend is only computed when these match the current run —
/// otherwise the delta would compare scores produced by different formulas
/// (see todo.md §15.1 and [`trend`]).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScoreContext {
    /// [`SCORE_FORMULA_VERSION`] active at save time.
    pub formula_version: u32,
    /// Effective crate-name → multiplier mapping (first matching profile
    /// wins, mirroring [`compute`]). Crates without a profile — and explicit
    /// `1.0` entries, which don't change the score — are omitted, so
    /// semantically identical configs compare equal.
    pub profile_multipliers: BTreeMap<String, DeductionMultiplier>,
}

impl ScoreContext {
    pub fn from_profiles(crate_profiles: &[CrateProfile]) -> Self {
        let mut profile_multipliers = BTreeMap::new();
        for profile in crate_profiles {
            for name in &profile.crates {
                profile_multipliers
                    .entry(name.clone())
                    .or_insert(profile.deduction_multiplier);
            }
        }
        profile_multipliers.retain(|_, multiplier| multiplier.value() != 1.0);
        Self {
            formula_version: SCORE_FORMULA_VERSION,
            profile_multipliers,
        }
    }
}

/// Why a baseline score can't be directly compared with the current one
/// (see [`Trend::NotComparable`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotComparableReason {
    /// The baseline was saved before judge recorded a [`ScoreContext`].
    MissingScoreContext,
    /// The baseline was scored with a different [`SCORE_FORMULA_VERSION`].
    FormulaVersionChanged,
    /// `judge.toml` crate profiles changed since the baseline was saved.
    ProfilesChanged,
    /// The baseline recorded no authored LOC, so its historical score is
    /// unavailable (see [`ScoreReason::NoAuthoredLoc`]).
    BaselineLocUnavailable,
}

impl NotComparableReason {
    /// Stable snake_case identifier for JSON output.
    pub const fn code(self) -> &'static str {
        match self {
            Self::MissingScoreContext => "missing_score_context",
            Self::FormulaVersionChanged => "formula_version_changed",
            Self::ProfilesChanged => "profiles_changed",
            Self::BaselineLocUnavailable => "baseline_loc_unavailable",
        }
    }
}

impl std::fmt::Display for NotComparableReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Self::MissingScoreContext => {
                "the baseline predates score-context tracking (re-save it with --save-baseline)"
            }
            Self::FormulaVersionChanged => {
                "the score formula changed since the baseline was saved (re-save it with --save-baseline)"
            }
            Self::ProfilesChanged => {
                "judge.toml crate profiles changed since the baseline was saved (re-save it with --save-baseline)"
            }
            Self::BaselineLocUnavailable => {
                "the baseline recorded no authored LOC, so its score is unavailable"
            }
        };
        f.write_str(text)
    }
}

/// The score trend against a baseline (see module docs, point 4 — the score
/// is never shown without this). Only [`Trend::Comparable`] carries a delta:
/// when the baseline was scored under different conditions the trend says so
/// explicitly instead of comparing scores from different formulas.
#[derive(Debug, Clone)]
pub enum Trend {
    Comparable {
        current: HealthScore,
        baseline_score: f64,
        baseline_grade: Grade,
    },
    NotComparable {
        current: HealthScore,
        reason: NotComparableReason,
    },
}

impl Trend {
    pub fn current(&self) -> &HealthScore {
        match self {
            Self::Comparable { current, .. } | Self::NotComparable { current, .. } => current,
        }
    }

    /// `None` when the baseline isn't directly comparable.
    pub fn delta(&self) -> Option<f64> {
        match self {
            Self::Comparable {
                current,
                baseline_score,
                ..
            } => Some(current.score - baseline_score),
            Self::NotComparable { .. } => None,
        }
    }
}

/// Computes the score trend of `current` against `baseline`, using the same
/// formula as [`compute`] — including crate profiles, which is only sound
/// because comparability requires the baseline's [`ScoreContext`] (formula
/// version and profile multipliers) to match the current run's exactly.
/// Unchanged findings under unchanged profiles therefore yield a delta of
/// zero; any mismatch is [`Trend::NotComparable`] (see todo.md §15.1).
pub fn trend(
    current: HealthScore,
    baseline: &Baseline,
    workspace: &Workspace,
    crate_profiles: &[CrateProfile],
) -> Trend {
    let Some(context) = &baseline.score_context else {
        return Trend::NotComparable {
            current,
            reason: NotComparableReason::MissingScoreContext,
        };
    };
    if context.formula_version != SCORE_FORMULA_VERSION {
        return Trend::NotComparable {
            current,
            reason: NotComparableReason::FormulaVersionChanged,
        };
    }
    if *context != ScoreContext::from_profiles(crate_profiles) {
        return Trend::NotComparable {
            current,
            reason: NotComparableReason::ProfilesChanged,
        };
    }
    if baseline.total_loc == 0 {
        return Trend::NotComparable {
            current,
            reason: NotComparableReason::BaselineLocUnavailable,
        };
    }

    // Same gating carve-out as `compute` — heuristic baseline findings are
    // advisory and never deducted (see module docs).
    let (fail_count, warn_count, deduction) = tally_deductions(
        baseline
            .findings
            .iter()
            .filter(|finding| finding.evidence_class.is_gating())
            .map(|finding| {
                // Stored paths are workspace-relative (`join` is a no-op for
                // older baselines that stored absolute paths).
                let file = workspace.root.join(&finding.file);
                (finding.severity, multiplier_for(workspace, &file, crate_profiles))
            }),
    );

    let baseline_score = score_from(fail_count, warn_count, deduction, baseline.total_loc);
    Trend::Comparable {
        current,
        baseline_score: baseline_score.score,
        baseline_grade: baseline_score.grade,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::{Location, OneBasedLine, Origin};
    use crate::ingest::{CrateInfo, SourceFile, SourceKind};
    use std::path::PathBuf;

    fn finding(severity: Severity, file: &str) -> Finding {
        Finding {
            id: "id".into(),
            rule: "rule".into(),
            severity,
            location: Location {
                file: PathBuf::from(file),
                line: OneBasedLine::FIRST,
                item_path: "item".to_string(),
            },
            evidence_class: crate::finding::EvidenceClass::DerivedFact,
            origin: Origin::Code,
            evidence: None,
            limitations: None,
            caused_by: Vec::new(),
            causes: Vec::new(),
        }
    }

    fn workspace_with_crate(root: &str, name: &str) -> Workspace {
        Workspace {
            root: PathBuf::from(root),
            crates: vec![CrateInfo {
                name: name.to_string(),
                version: "0.1.0".to_string(),
                manifest_path: PathBuf::from(root).join("Cargo.toml"),
                root: PathBuf::from(root),
                source_files: vec![SourceFile {
                    path: PathBuf::from(root).join("src/lib.rs"),
                    kind: SourceKind::Authored,
                }],
                entry_points: Vec::new(),
                dependencies: Vec::new(),
            }],
        }
    }

    fn multiplier(value: f64) -> DeductionMultiplier {
        DeductionMultiplier::try_from(value).unwrap()
    }

    fn available(outcome: ScoreOutcome) -> HealthScore {
        match outcome {
            ScoreOutcome::Available(score) => score,
            ScoreOutcome::Unavailable(reason) => panic!("score unavailable: {reason}"),
        }
    }

    #[test]
    fn no_findings_scores_perfectly() {
        let workspace = workspace_with_crate("/repo", "core");
        let score = available(compute(&[], 1000, &workspace, &[]));

        assert_eq!(score.score, 100.0);
        assert_eq!(score.grade, Grade::A);
        assert_eq!(score.fail_count, 0);
        assert_eq!(score.warn_count, 0);
    }

    #[test]
    fn info_findings_do_not_affect_the_score() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![finding(Severity::Info, "/repo/src/lib.rs")];
        let score = available(compute(&findings, 1000, &workspace, &[]));

        assert_eq!(score.score, 100.0);
    }

    #[test]
    fn heuristic_findings_do_not_deduct_and_are_not_counted() {
        let workspace = workspace_with_crate("/repo", "core");
        let mut heuristic_fail = finding(Severity::Fail, "/repo/src/lib.rs");
        heuristic_fail.evidence_class = crate::finding::EvidenceClass::Heuristic;
        let mut heuristic_warn = finding(Severity::Warn, "/repo/src/lib.rs");
        heuristic_warn.evidence_class = crate::finding::EvidenceClass::Heuristic;

        let score = available(compute(
            &[heuristic_fail, heuristic_warn],
            1000,
            &workspace,
            &[],
        ));

        assert_eq!(score.score, 100.0);
        assert_eq!(score.grade, Grade::A);
        assert_eq!(score.fail_count, 0);
        assert_eq!(score.warn_count, 0);
        assert_eq!(score.deduction, 0.0);
    }

    #[test]
    fn fail_and_warn_findings_are_weighted_and_density_normalized() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![
            finding(Severity::Fail, "/repo/src/lib.rs"),
            finding(Severity::Warn, "/repo/src/lib.rs"),
        ];
        // total_loc = 1000 -> density factor 1.0, deduction = 10 + 3 = 13
        let score = available(compute(&findings, 1000, &workspace, &[]));

        assert_eq!(score.fail_count, 1);
        assert_eq!(score.warn_count, 1);
        assert_eq!(score.deduction, 13.0);
        assert_eq!(score.score, 87.0);
        assert_eq!(score.grade, Grade::B);
    }

    #[test]
    fn same_findings_score_worse_on_a_smaller_codebase() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![finding(Severity::Fail, "/repo/src/lib.rs")];

        let large = available(compute(&findings, 10_000, &workspace, &[]));
        let small = available(compute(&findings, 100, &workspace, &[]));

        assert!(small.score < large.score);
    }

    #[test]
    fn zero_loc_is_unavailable_not_a_perfect_score() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![finding(Severity::Fail, "/repo/src/lib.rs")];

        let outcome = compute(&findings, 0, &workspace, &[]);

        assert!(matches!(
            outcome,
            ScoreOutcome::Unavailable(ScoreReason::NoAuthoredLoc)
        ));
    }

    #[test]
    fn total_authored_loc_checked_counts_authored_lines() {
        let dir = crate::test_util::TempDir::new("health-score-loc-checked");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/lib.rs"), "fn a() {}\nfn b() {}\n").unwrap();

        let mut workspace = workspace_with_crate("/ignored", "fixture");
        workspace.root = dir.to_path_buf();
        workspace.crates[0].root = dir.to_path_buf();
        workspace.crates[0].source_files = vec![SourceFile {
            path: dir.join("src/lib.rs"),
            kind: SourceKind::Authored,
        }];

        assert_eq!(total_authored_loc_checked(&workspace).unwrap(), 2);
    }

    #[test]
    fn unreadable_source_file_is_a_loc_error_not_a_smaller_codebase() {
        let workspace = workspace_with_crate("/nonexistent-judge-fixture", "core");

        let err = total_authored_loc_checked(&workspace).unwrap_err();

        assert_eq!(
            err.path,
            PathBuf::from("/nonexistent-judge-fixture/src/lib.rs")
        );
    }

    #[test]
    fn deduction_multiplier_rejects_out_of_range_values() {
        assert!(DeductionMultiplier::try_from(-1.0).is_err());
        assert!(DeductionMultiplier::try_from(0.0).is_err());
        assert!(DeductionMultiplier::try_from(f64::NAN).is_err());
        assert!(DeductionMultiplier::try_from(f64::INFINITY).is_err());
        assert!(DeductionMultiplier::try_from(f64::NEG_INFINITY).is_err());
        assert!(DeductionMultiplier::try_from(10.1).is_err());

        assert_eq!(DeductionMultiplier::try_from(0.5).unwrap().value(), 0.5);
        assert_eq!(DeductionMultiplier::try_from(10.0).unwrap().value(), 10.0);
        assert_eq!(DeductionMultiplier::default().value(), 1.0);
    }

    #[test]
    fn invalid_multiplier_in_judge_toml_is_a_config_error_not_a_score() {
        for value in ["-1.0", "0.0", "nan", "inf", "100.0"] {
            let source = format!(
                "[[crate_profile]]\nname = \"lenient\"\ncrates = [\"parser\"]\ndeduction_multiplier = {value}\n"
            );
            let result = toml::from_str::<crate::rules::boundaries::BoundaryConfig>(&source);
            assert!(result.is_err(), "multiplier {value} should be rejected");
        }
    }

    #[test]
    fn authored_loc_in_counts_only_the_given_files() {
        let dir = crate::test_util::TempDir::new("health-score-authored-loc-in");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/a.rs"), "fn a() {}\nfn a2() {}\n").unwrap();
        std::fs::write(dir.join("src/b.rs"), "fn b() {}\n").unwrap();

        let workspace = Workspace {
            root: dir.to_path_buf(),
            crates: vec![CrateInfo {
                name: "fixture".to_string(),
                version: "0.1.0".to_string(),
                manifest_path: dir.join("Cargo.toml"),
                root: dir.to_path_buf(),
                source_files: vec![
                    SourceFile {
                        path: dir.join("src/a.rs"),
                        kind: SourceKind::Authored,
                    },
                    SourceFile {
                        path: dir.join("src/b.rs"),
                        kind: SourceKind::Authored,
                    },
                ],
                entry_points: Vec::new(),
                dependencies: Vec::new(),
            }],
        };

        let touched = HashSet::from([PathBuf::from("src/a.rs")]);
        let loc = authored_loc_in(&workspace, &touched);

        assert_eq!(loc, 2);
    }

    /// Undecidable fixture (todo.md §17.5): `multiplier_for`'s own doc
    /// comment says "the first profile in `crate_profiles` naming the
    /// owning crate wins" -- a deliberate, documented precedence rule, not
    /// a bug. But nothing in `judge.toml`'s shape, nor in the resulting
    /// [`HealthScore`], distinguishes two very different authoring stories
    /// that produce the identical winning multiplier: (1) a leftover,
    /// never-cleaned-up duplicate profile that happens to be harmlessly
    /// shadowed by the one that was always meant to win, versus (2) someone
    /// appending a second, stricter profile meaning to override the first,
    /// unaware that first-wins semantics silently keep the original,
    /// lenient one active instead. Both configs below produce byte-identical
    /// deductions -- indistinguishable from a config where the second,
    /// silently-ignored profile was never written at all -- so there is no
    /// way to tell a broken override attempt apart from harmless dead
    /// config just by looking at the score.
    #[test]
    fn a_crate_named_in_two_profiles_silently_keeps_only_the_first_multiplier() {
        let workspace = workspace_with_crate("/repo", "vendor");
        let findings = vec![finding(Severity::Fail, "/repo/src/lib.rs")];

        let shadowed_override = vec![
            CrateProfile {
                name: "legacy-lenient".to_string(),
                crates: vec!["vendor".to_string()],
                deduction_multiplier: multiplier(0.5),
            },
            CrateProfile {
                name: "attempted-strict-override".to_string(),
                crates: vec!["vendor".to_string()],
                deduction_multiplier: multiplier(2.0),
            },
        ];
        let first_profile_only = vec![CrateProfile {
            name: "legacy-lenient".to_string(),
            crates: vec!["vendor".to_string()],
            deduction_multiplier: multiplier(0.5),
        }];

        let scaled = available(compute(&findings, 1000, &workspace, &shadowed_override));
        let lenient_only = available(compute(&findings, 1000, &workspace, &first_profile_only));

        assert_eq!(
            scaled.deduction, lenient_only.deduction,
            "the second profile's 2.0 multiplier is silently shadowed by the first's 0.5 -- \
             the score is byte-identical to a config where the second entry was never written \
             at all"
        );
    }

    #[test]
    fn crate_profile_multiplier_scales_that_crates_deductions() {
        let workspace = workspace_with_crate("/repo", "parser");
        let findings = vec![finding(Severity::Fail, "/repo/src/lib.rs")];
        let profiles = vec![CrateProfile {
            name: "lenient".to_string(),
            crates: vec!["parser".to_string()],
            deduction_multiplier: multiplier(0.5),
        }];

        let scaled = available(compute(&findings, 1000, &workspace, &profiles));
        let unscaled = available(compute(&findings, 1000, &workspace, &[]));

        assert_eq!(scaled.deduction, unscaled.deduction * 0.5);
    }

    #[test]
    fn trend_is_zero_for_unchanged_findings_and_profiles() {
        let workspace = workspace_with_crate("/repo", "parser");
        let profiles = vec![CrateProfile {
            name: "lenient".to_string(),
            crates: vec!["parser".to_string()],
            deduction_multiplier: multiplier(0.5),
        }];
        let findings = vec![
            finding(Severity::Fail, "/repo/src/lib.rs"),
            finding(Severity::Warn, "/repo/src/lib.rs"),
        ];
        let baseline = Baseline::new(
            &findings,
            "abc123".to_string(),
            std::collections::HashMap::new(),
            1000,
            ScoreContext::from_profiles(&profiles),
        );

        let current = available(compute(&findings, 1000, &workspace, &profiles));
        let trend = trend(current, &baseline, &workspace, &profiles);

        assert_eq!(trend.delta(), Some(0.0));
        assert!(matches!(trend, Trend::Comparable { .. }));
    }

    #[test]
    fn profile_change_makes_the_trend_not_comparable() {
        let workspace = workspace_with_crate("/repo", "parser");
        let findings = vec![finding(Severity::Fail, "/repo/src/lib.rs")];
        let baseline = Baseline::new(
            &findings,
            "abc123".to_string(),
            std::collections::HashMap::new(),
            1000,
            ScoreContext::from_profiles(&[]),
        );
        let profiles = vec![CrateProfile {
            name: "lenient".to_string(),
            crates: vec!["parser".to_string()],
            deduction_multiplier: multiplier(0.5),
        }];

        let current = available(compute(&findings, 1000, &workspace, &profiles));
        let trend = trend(current, &baseline, &workspace, &profiles);

        assert_eq!(trend.delta(), None);
        assert!(matches!(
            trend,
            Trend::NotComparable {
                reason: NotComparableReason::ProfilesChanged,
                ..
            }
        ));
    }

    #[test]
    fn trend_skips_heuristic_baseline_findings_like_compute_does() {
        // Baseline stored under the current formula, containing one gating
        // and one heuristic finding; the current run carries the same pair.
        // Both sides must skip the heuristic finding, so the delta is zero —
        // not a phantom improvement from the advisory carve-out.
        let workspace = workspace_with_crate("/repo", "core");
        let mut heuristic = finding(Severity::Warn, "/repo/src/lib.rs");
        heuristic.evidence_class = crate::finding::EvidenceClass::Heuristic;
        let findings = vec![finding(Severity::Warn, "/repo/src/lib.rs"), heuristic];
        let baseline = Baseline::new(
            &findings,
            "abc123".to_string(),
            std::collections::HashMap::new(),
            1000,
            ScoreContext::from_profiles(&[]),
        );

        let current = available(compute(&findings, 1000, &workspace, &[]));
        assert_eq!(current.warn_count, 1);
        let trend = trend(current, &baseline, &workspace, &[]);

        assert_eq!(trend.delta(), Some(0.0));
    }

    #[test]
    fn formula_version_change_makes_the_trend_not_comparable() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![finding(Severity::Warn, "/repo/src/lib.rs")];
        let mut baseline = Baseline::new(
            &findings,
            "abc123".to_string(),
            std::collections::HashMap::new(),
            1000,
            ScoreContext::from_profiles(&[]),
        );
        // Version 1: the formula before heuristic findings became
        // advisory-only.
        baseline.score_context.as_mut().unwrap().formula_version = 1;

        let current = available(compute(&findings, 1000, &workspace, &[]));
        let trend = trend(current, &baseline, &workspace, &[]);

        assert!(matches!(
            trend,
            Trend::NotComparable {
                reason: NotComparableReason::FormulaVersionChanged,
                ..
            }
        ));
    }

    #[test]
    fn baseline_without_score_context_is_not_comparable() {
        let workspace = workspace_with_crate("/repo", "core");
        let findings = vec![finding(Severity::Warn, "/repo/src/lib.rs")];
        let mut baseline = Baseline::new(
            &findings,
            "abc123".to_string(),
            std::collections::HashMap::new(),
            1000,
            ScoreContext::from_profiles(&[]),
        );
        baseline.score_context = None;

        let current = available(compute(&findings, 1000, &workspace, &[]));
        let trend = trend(current, &baseline, &workspace, &[]);

        assert!(matches!(
            trend,
            Trend::NotComparable {
                reason: NotComparableReason::MissingScoreContext,
                ..
            }
        ));
    }
}