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
//! Baseline snapshots and delta verdicts (see todo.md §5, §14.2 P0#5).
//!
//! A baseline freezes a previously analysed project state. Comparing a fresh
//! run against it reports findings that were introduced, resolved, or changed
//! in severity. The comparison is deliberately artifact-based: it neither
//! requires nor inspects a Git repository.

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

use serde::{Deserialize, Serialize};

use crate::finding::{
    EvidenceClass, Finding, FindingId, Origin, RuleId, Severity, evidence_class_for_rule,
};
use crate::health_score::ScoreContext;

/// v3 removes commit identity and the Git-derived code/rule introduction
/// split. v2 introduced `evidence_class` in place of numeric `confidence`.
pub const SCHEMA_VERSION: u32 = 3;

/// The minimal record kept per finding in a baseline file — enough to match
/// it against a later project state and point a reviewer at its prior scope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BaselineFinding {
    pub id: FindingId,
    pub rule: RuleId,
    pub severity: Severity,
    pub evidence_class: EvidenceClass,
    pub origin: Origin,
    pub file: PathBuf,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Baseline {
    pub schema_version: u32,
    /// judge version active when this baseline was saved.
    pub judge_version: String,
    /// Revision of every rule active when this baseline was saved.
    pub rule_revisions: HashMap<String, u32>,
    /// Authored lines of code analyzed when this baseline was saved (see
    /// [`crate::health_score`]) — lets a later run compute the historical
    /// score density this baseline represents, not just its raw finding
    /// count.
    pub total_loc: usize,
    /// Score-formula conditions at save time (see
    /// [`crate::health_score::ScoreContext`]). `None` for baselines saved by
    /// older judge versions — the score trend then reports "not comparable"
    /// instead of a delta computed under different conditions (see todo.md
    /// §15.1).
    #[serde(default)]
    pub score_context: Option<ScoreContext>,
    /// Per-crate public-API-surface item count at save time (see
    /// [`crate::rules::api_surface::ApiSurfaceSize`]), used by `cargo judge
    /// api-surface`'s trend line. `None` for baselines saved by older judge
    /// versions, and for baselines saved by any command other than
    /// `api-surface` — [`crate::rules::api_surface::size_trend`] then reports "not
    /// comparable" per crate instead of a false delta (see todo.md §I
    /// "API-Surface-Größe pro Crate, Trend gegen Baseline", and
    /// `score_context` above for the same additive-field pattern).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_surface_size: Option<HashMap<String, usize>>,
    pub findings: Vec<BaselineFinding>,
}

impl Baseline {
    pub fn new(
        findings: &[Finding],
        _legacy_commit: String,
        rule_revisions: HashMap<String, u32>,
        total_loc: usize,
        score_context: ScoreContext,
    ) -> Self {
        Self {
            schema_version: SCHEMA_VERSION,
            judge_version: env!("CARGO_PKG_VERSION").to_string(),
            rule_revisions,
            total_loc,
            score_context: Some(score_context),
            api_surface_size: None,
            findings: findings
                .iter()
                .map(|finding| BaselineFinding {
                    id: finding.id.clone(),
                    rule: finding.rule.clone(),
                    severity: finding.severity,
                    evidence_class: finding.evidence_class,
                    origin: finding.origin,
                    file: finding.location.file.clone(),
                })
                .collect(),
        }
    }

    /// Attaches a per-crate api-surface-size count to this baseline before
    /// saving (see [`crate::rules::api_surface::ApiSurfaceSize`]) — builder-style,
    /// so only `cargo judge api-surface --save-baseline` opts in and every
    /// other baseline keeps `api_surface_size: None`.
    pub fn with_api_surface_size(mut self, size: HashMap<String, usize>) -> Self {
        self.api_surface_size = Some(size);
        self
    }

    /// Migrates baselines written by older judge versions in the same
    /// checkout, which stored absolute paths in both `file` and `id`.
    pub fn relativize_paths(&mut self, workspace_root: &Path) {
        for finding in &mut self.findings {
            let Ok(relative) = finding.file.strip_prefix(workspace_root) else {
                continue;
            };
            let relative = relative.to_path_buf();
            // Same UTF-8 caveat as [`crate::finding::relativize_paths`]: a
            // non-UTF-8 path can never appear verbatim in the UTF-8 id, so
            // instead of substituting a lossy rendering the id is left
            // untouched and only the structured `file` is rebased.
            if let (Some(absolute_text), Some(relative_text)) =
                (finding.file.to_str(), relative.to_str())
            {
                finding.id =
                    FindingId::from(finding.id.as_str().replace(absolute_text, relative_text));
            }
            finding.file = relative;
        }
    }
}

#[derive(Debug)]
pub enum BaselineError {
    Io(PathBuf, std::io::Error),
    Serialize(serde_json::Error),
    Deserialize(PathBuf, serde_json::Error),
    /// The baseline declares a `schema_version` this judge has no migration
    /// for — typically one written by a newer judge. `found` is `None` when
    /// the field is missing entirely.
    UnsupportedSchemaVersion {
        path: PathBuf,
        found: Option<u64>,
    },
}

/// One arm of the shared Io/Serialize/Deserialize/UnsupportedSchemaVersion
/// error shape (see [`fmt_store_error`]).
pub(crate) enum StoreErrorRef<'a> {
    Io(&'a Path, &'a std::io::Error),
    Serialize(&'a serde_json::Error),
    Deserialize(&'a Path, &'a serde_json::Error),
    UnsupportedSchemaVersion {
        path: &'a Path,
        found: Option<u64>,
    },
}

/// Shared `Display` rendering for baseline-family store errors —
/// [`BaselineError`] and [`crate::pattern_baseline::PatternBaselineError`]
/// have the same four-variant shape and differ only in the noun used in
/// messages, the active schema version, and the resave command hint.
pub(crate) fn fmt_store_error(
    f: &mut std::fmt::Formatter<'_>,
    noun: &str,
    schema_version: u32,
    resave_command: &str,
    error: StoreErrorRef<'_>,
) -> std::fmt::Result {
    match error {
        StoreErrorRef::Io(path, err) => write!(f, "{}: {err}", path.display()),
        StoreErrorRef::Serialize(err) => write!(f, "failed to serialize {noun}: {err}"),
        StoreErrorRef::Deserialize(path, err) => {
            write!(f, "{}: failed to parse {noun}: {err}", path.display())
        }
        StoreErrorRef::UnsupportedSchemaVersion { path, found } => {
            match found {
                Some(found) => write!(
                    f,
                    "{}: unsupported {noun} schema_version {found} (this judge supports version {schema_version})",
                    path.display()
                )?,
                None => write!(
                    f,
                    "{}: {noun} has no schema_version (this judge supports version {schema_version})",
                    path.display()
                )?,
            }
            write!(f, " — re-save it with a matching judge via `{resave_command}`")
        }
    }
}

impl std::fmt::Display for BaselineError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let error = match self {
            Self::Io(path, err) => StoreErrorRef::Io(path, err),
            Self::Serialize(err) => StoreErrorRef::Serialize(err),
            Self::Deserialize(path, err) => StoreErrorRef::Deserialize(path, err),
            Self::UnsupportedSchemaVersion { path, found } => {
                StoreErrorRef::UnsupportedSchemaVersion {
                    path,
                    found: *found,
                }
            }
        };
        fmt_store_error(
            f,
            "baseline",
            SCHEMA_VERSION,
            "cargo judge --save-baseline",
            error,
        )
    }
}

impl std::error::Error for BaselineError {}

/// Extracts the `schema_version` field to inspect it before deciding how to
/// deserialize the rest of the document — shared by [`migrate`] and
/// [`crate::pattern_baseline::load`], which both gate deserialization on this
/// same probe.
pub(crate) fn schema_version_of(value: &serde_json::Value) -> Option<u64> {
    value
        .get("schema_version")
        .and_then(serde_json::Value::as_u64)
}

/// Reads `path` as UTF-8 text and parses it as JSON, routing I/O and parse
/// failures through the caller's own error type — shared by [`load`] and
/// [`crate::pattern_baseline::load`], which otherwise differ only in their
/// error enum (see `pattern_baseline` module docs for why the two stores
/// don't share a domain type).
pub(crate) fn read_json_value<E>(
    path: &Path,
    io_err: impl FnOnce(PathBuf, std::io::Error) -> E,
    parse_err: impl FnOnce(PathBuf, serde_json::Error) -> E,
) -> Result<serde_json::Value, E> {
    let content = std::fs::read_to_string(path).map_err(|err| io_err(path.to_path_buf(), err))?;
    serde_json::from_str(&content).map_err(|err| parse_err(path.to_path_buf(), err))
}

/// Deserializes an already-parsed JSON value into `T`, routing failures
/// through the caller's own error type — shared by [`migrate`]'s two
/// current-shape arms and [`crate::pattern_baseline::load`].
pub(crate) fn deserialize_value<T, E>(
    path: &Path,
    value: serde_json::Value,
    err: impl FnOnce(PathBuf, serde_json::Error) -> E,
) -> Result<T, E>
where
    T: serde::de::DeserializeOwned,
{
    serde_json::from_value(value).map_err(|inner| err(path.to_path_buf(), inner))
}

/// Writes `value` to `path` as pretty-printed JSON, creating parent
/// directories (e.g. `.judge/`) as needed and routing I/O/serialize failures
/// through the caller's own error type — shared by [`save`] and
/// [`crate::pattern_baseline::save`].
pub(crate) fn write_json_pretty<T, E>(
    path: &Path,
    value: &T,
    io_err: impl Fn(PathBuf, std::io::Error) -> E,
    serialize_err: impl FnOnce(serde_json::Error) -> E,
) -> Result<(), E>
where
    T: Serialize,
{
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|err| io_err(parent.to_path_buf(), err))?;
    }
    let json = serde_json::to_string_pretty(value).map_err(serialize_err)?;
    std::fs::write(path, json).map_err(|err| io_err(path.to_path_buf(), err))
}

/// Writes `baseline` to `path` as pretty-printed JSON, creating parent
/// directories (e.g. `.judge/`) as needed.
pub fn save(path: &Path, baseline: &Baseline) -> Result<(), BaselineError> {
    write_json_pretty(path, baseline, BaselineError::Io, BaselineError::Serialize)
}

pub fn load(path: &Path) -> Result<Baseline, BaselineError> {
    let value = read_json_value(path, BaselineError::Io, BaselineError::Deserialize)?;
    migrate(path, value)
}

/// Deserializes a parsed baseline, migrating explicitly per `schema_version`.
/// Every supported version gets its own arm; anything else — in particular a
/// version written by a newer judge — is rejected instead of being silently
/// processed under wrong assumptions.
///
/// v1 → v2: v1 findings carried a numeric `confidence` and no
/// `evidence_class`. `confidence` is discarded (it was never a calibrated
/// probability — todo.md §17.5) and `evidence_class` is derived
/// deterministically from the stored rule id via
/// [`evidence_class_for_rule`]; unknown rule ids conservatively become
/// `heuristic`.
fn migrate(path: &Path, mut value: serde_json::Value) -> Result<Baseline, BaselineError> {
    let found = schema_version_of(&value);
    match found {
        Some(1) | Some(2) => {
            if let Some(findings) = value
                .get_mut("findings")
                .and_then(serde_json::Value::as_array_mut)
            {
                for finding in findings {
                    let Some(finding) = finding.as_object_mut() else {
                        continue;
                    };
                    if finding.get("evidence_class").is_none() {
                        finding.remove("confidence");
                        let class = finding
                            .get("rule")
                            .and_then(serde_json::Value::as_str)
                            .map_or(EvidenceClass::Heuristic, |rule| {
                                evidence_class_for_rule(&RuleId::from(rule))
                            });
                        finding.insert(
                            "evidence_class".to_string(),
                            serde_json::to_value(class).map_err(BaselineError::Serialize)?,
                        );
                    }
                }
            }
            value
                .as_object_mut()
                .expect("baseline must be an object")
                .remove("commit");
            value["schema_version"] = serde_json::json!(SCHEMA_VERSION);
            deserialize_value(path, value, BaselineError::Deserialize)
        }
        Some(version) if version == u64::from(SCHEMA_VERSION) => {
            deserialize_value(path, value, BaselineError::Deserialize)
        }
        _ => Err(BaselineError::UnsupportedSchemaVersion {
            path: path.to_path_buf(),
            found,
        }),
    }
}

/// The result of comparing a fresh set of findings against a [`Baseline`].
#[derive(Debug, Clone, Serialize)]
pub struct Delta {
    /// Findings absent from the recorded project state.
    pub introduced: Vec<Finding>,
    /// Baseline findings that no longer appear in the current run.
    pub resolved: Vec<BaselineFinding>,
    /// Findings with the same stable identity but a different severity.
    pub severity_changed: Vec<SeverityChange>,
    /// Findings present in both the baseline and the current run.
    pub unchanged_count: usize,
    /// Backwards-compatible in-memory aliases for callers that have not yet
    /// moved from commit terminology. They are intentionally absent from the
    /// artifact schema and contain no Git-derived classification.
    #[serde(skip)]
    pub code_introduced: Vec<Finding>,
    #[serde(skip)]
    pub rule_introduced: Vec<Finding>,
}

/// One stable finding whose severity changed between two analysed states.
#[derive(Debug, Clone, Serialize)]
pub struct SeverityChange {
    pub before: BaselineFinding,
    pub after: Finding,
}

impl SeverityChange {
    /// The rule id plus the severity transition — the fields every delta
    /// renderer (TTY, Markdown) prints identically before appending its own
    /// location column.
    pub fn transition(&self) -> (&RuleId, Severity, Severity) {
        (&self.after.rule, self.before.severity, self.after.severity)
    }
}

/// Splits findings into (gating, advisory) — the shared split behind every
/// "advisory (heuristic) — no verdict effect" section (TTY, Markdown, and the
/// `health` slop block); see [`Finding::is_gating`].
pub fn partition_gating<'a, I>(findings: I) -> (Vec<&'a Finding>, Vec<&'a Finding>)
where
    I: IntoIterator<Item = &'a Finding>,
{
    findings.into_iter().partition(|finding| finding.is_gating())
}

/// Compares `current` findings against a recorded project state. The legacy
/// arguments are retained temporarily for source compatibility but are
/// deliberately ignored: comparison is wholly artifact-based.
pub fn diff(
    current: &[Finding],
    baseline: &Baseline,
    _touched_files: &HashSet<PathBuf>,
    _current_rule_revisions: &HashMap<String, u32>,
) -> Delta {
    let known = baseline
        .findings
        .iter()
        .map(|finding| (finding.id.as_str(), finding))
        .collect::<HashMap<_, _>>();

    let mut introduced = Vec::new();
    let mut severity_changed = Vec::new();
    let mut unchanged_count = 0;

    for finding in current {
        match known.get(finding.id.as_str()) {
            Some(previous) if previous.severity == finding.severity => unchanged_count += 1,
            Some(previous) => severity_changed.push(SeverityChange {
                before: (*previous).clone(),
                after: finding.clone(),
            }),
            None => introduced.push(finding.clone()),
        }
    }

    let current_ids: HashSet<&str> = current.iter().map(|f| f.id.as_str()).collect();
    let resolved = baseline
        .findings
        .iter()
        .filter(|finding| !current_ids.contains(finding.id.as_str()))
        .cloned()
        .collect();

    Delta {
        code_introduced: introduced.clone(),
        rule_introduced: Vec::new(),
        introduced,
        resolved,
        severity_changed,
        unchanged_count,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    Pass,
    Fail,
}

impl Verdict {
    /// The lower-case label used identically by every human-facing render
    /// (TTY, Markdown) — kept on the type so wording can't drift between
    /// formats.
    pub fn label(self) -> &'static str {
        match self {
            Verdict::Pass => "pass",
            Verdict::Fail => "fail",
        }
    }
}

/// A three-way verdict distinguishing `Warn` from `Fail` among
/// `code_introduced` findings, instead of collapsing both into `Fail` like
/// [`Delta::verdict`] does. It is retained for API consumers that need to
/// distinguish warning-only deltas from failing deltas.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TriVerdict {
    Pass,
    Warn,
    Fail,
}

impl Delta {
    /// Only actionable (`Warn`/`Fail`) *gating* introduced findings can
    /// fail the verdict. `Info` findings remain visible in the delta but are
    /// explicitly descriptive, not pass/fail judgements — and advisory
    /// (heuristic) findings never gate regardless of severity (see
    /// [`crate::finding::EvidenceClass::is_gating`], todo.md §17.2).
    pub fn verdict(&self) -> Verdict {
        if self
            .introduced
            .iter()
            .filter(|finding| finding.is_gating())
            .all(|finding| finding.severity == crate::finding::Severity::Info)
        {
            Verdict::Pass
        } else {
            Verdict::Fail
        }
    }

    /// Like [`Delta::verdict`], but keeps `Warn` and `Fail` distinct instead
    /// of collapsing both into `Fail` (see [`TriVerdict`]). Applies the same
    /// advisory carve-out: heuristic findings never force `Warn`/`Fail`.
    pub fn tri_verdict(&self) -> TriVerdict {
        let mut has_warn = false;
        for finding in self.introduced.iter().filter(|f| f.is_gating()) {
            match finding.severity {
                crate::finding::Severity::Fail => return TriVerdict::Fail,
                crate::finding::Severity::Warn => has_warn = true,
                crate::finding::Severity::Info => {}
            }
        }
        if has_warn {
            TriVerdict::Warn
        } else {
            TriVerdict::Pass
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::{Location, OneBasedLine, Severity};

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

    fn baseline_with(findings: &[Finding]) -> Baseline {
        Baseline::new(
            findings,
            "abc123".to_string(),
            HashMap::from([("duplicate-code".to_string(), 1)]),
            1000,
            ScoreContext::from_profiles(&[]),
        )
    }

    fn current_revisions() -> HashMap<String, u32> {
        HashMap::from([("duplicate-code".to_string(), 1)])
    }

    #[test]
    fn save_and_load_round_trips() {
        let dir = crate::test_util::TempDir::new("baseline-round-trip");
        let path = dir.join(".judge/baseline.json");
        let baseline = baseline_with(&[finding("a", "src/a.rs")]);

        save(&path, &baseline).unwrap();
        let loaded = load(&path).unwrap();

        assert_eq!(loaded.findings.len(), 1);
        assert_eq!(loaded.findings[0].id, "a");
        assert_eq!(loaded.score_context, baseline.score_context);
    }

    fn write_baseline_json(name: &str, json: &str) -> (crate::test_util::TempDir, PathBuf) {
        let dir = crate::test_util::TempDir::new(name);
        let path = dir.join("baseline.json");
        std::fs::write(&path, json).unwrap();
        (dir, path)
    }

    #[test]
    fn baseline_without_score_context_still_loads() {
        // A baseline saved before `score_context` existed (see todo.md
        // §15.1) — `load` must tolerate the missing field and yield `None`,
        // not fail.
        let (_dir, path) = write_baseline_json(
            "baseline-no-score-context",
            r#"{
                "schema_version": 2,
                "judge_version": "0.1.0",
                "commit": "abc123",
                "rule_revisions": {},
                "total_loc": 1000,
                "findings": []
            }"#,
        );

        let baseline = load(&path).unwrap();

        assert!(baseline.score_context.is_none());
    }

    #[test]
    fn baseline_without_api_surface_size_still_loads() {
        // A baseline saved before `api_surface_size` existed — or saved by a
        // command other than `api-surface` — must still load, with the field
        // `None` rather than a parse failure (see todo.md §I "API-Surface-
        // Größe pro Crate, Trend gegen Baseline").
        let (_dir, path) = write_baseline_json(
            "baseline-no-api-surface-size",
            r#"{
                "schema_version": 2,
                "judge_version": "0.1.0",
                "commit": "abc123",
                "rule_revisions": {},
                "total_loc": 1000,
                "findings": []
            }"#,
        );

        let baseline = load(&path).unwrap();

        assert!(baseline.api_surface_size.is_none());
    }

    #[test]
    fn v1_baseline_with_confidence_migrates_to_evidence_classes() {
        // A v1 baseline stored numeric `confidence` per finding and no
        // `evidence_class`. Migration must discard `confidence` and derive
        // the class from the rule id — unknown rules conservatively become
        // `heuristic` (todo.md §17.5).
        let (_dir, path) = write_baseline_json(
            "baseline-v1-migration",
            r#"{
                "schema_version": 1,
                "judge_version": "0.1.0",
                "commit": "abc123",
                "rule_revisions": {},
                "total_loc": 1000,
                "findings": [
                    {
                        "id": "duplicate-code:src/a.rs:f:0-20",
                        "rule": "duplicate-code",
                        "severity": "warn",
                        "origin": "code",
                        "confidence": 1.0,
                        "file": "src/a.rs"
                    },
                    {
                        "id": "unused-pub-workspace:src/b.rs:g",
                        "rule": "unused-pub-workspace",
                        "severity": "warn",
                        "origin": "code",
                        "confidence": 1.0,
                        "file": "src/b.rs"
                    },
                    {
                        "id": "phantom-crate:app:dep",
                        "rule": "phantom-crate",
                        "severity": "fail",
                        "origin": "code",
                        "confidence": 0.9,
                        "file": "Cargo.toml"
                    },
                    {
                        "id": "hotspot:src/c.rs",
                        "rule": "hotspot",
                        "severity": "info",
                        "origin": "code",
                        "confidence": 1.0,
                        "file": "src/c.rs"
                    },
                    {
                        "id": "some-retired-rule:src/d.rs",
                        "rule": "some-retired-rule",
                        "severity": "warn",
                        "origin": "code",
                        "confidence": 0.7,
                        "file": "src/d.rs"
                    }
                ]
            }"#,
        );

        let baseline = load(&path).unwrap();

        assert_eq!(baseline.schema_version, SCHEMA_VERSION);
        let classes: Vec<EvidenceClass> = baseline
            .findings
            .iter()
            .map(|finding| finding.evidence_class)
            .collect();
        assert_eq!(
            classes,
            vec![
                EvidenceClass::DerivedFact,
                EvidenceClass::BoundedSemantic,
                EvidenceClass::ExternalMeasurement,
                EvidenceClass::Heuristic,
                EvidenceClass::Heuristic,
            ]
        );
    }

    #[test]
    fn baseline_with_future_schema_version_is_rejected() {
        let (_dir, path) = write_baseline_json(
            "baseline-future-schema",
            r#"{
                "schema_version": 4,
                "judge_version": "9.9.9",
                "commit": "abc123",
                "rule_revisions": {},
                "total_loc": 1000,
                "findings": []
            }"#,
        );

        let err = load(&path).unwrap_err();

        assert!(matches!(
            err,
            BaselineError::UnsupportedSchemaVersion { found: Some(4), .. }
        ));
        let message = err.to_string();
        assert!(message.contains("schema_version 4"), "{message}");
        assert!(message.contains("supports version 3"), "{message}");
    }

    #[test]
    fn baseline_without_schema_version_is_rejected() {
        let (_dir, path) = write_baseline_json(
            "baseline-missing-schema",
            r#"{
                "judge_version": "0.1.0",
                "commit": "abc123",
                "rule_revisions": {},
                "total_loc": 1000,
                "findings": []
            }"#,
        );

        let err = load(&path).unwrap_err();

        assert!(matches!(
            err,
            BaselineError::UnsupportedSchemaVersion { found: None, .. }
        ));
        assert!(err.to_string().contains("no schema_version"), "{err}");
    }

    #[test]
    fn known_finding_is_unchanged_not_introduced() {
        let baseline = baseline_with(&[finding("a", "src/a.rs")]);
        let current = [finding("a", "src/a.rs")];

        let delta = diff(&current, &baseline, &HashSet::new(), &current_revisions());

        assert_eq!(delta.unchanged_count, 1);
        assert!(delta.code_introduced.is_empty());
        assert!(delta.rule_introduced.is_empty());
        assert_eq!(delta.verdict(), Verdict::Pass);
    }

    #[test]
    fn new_finding_in_a_touched_file_is_code_introduced() {
        let baseline = baseline_with(&[]);
        let current = [finding("new", "src/a.rs")];
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(&current, &baseline, &touched, &current_revisions());

        assert_eq!(delta.code_introduced.len(), 1);
        assert!(delta.rule_introduced.is_empty());
        assert_eq!(delta.verdict(), Verdict::Fail);
    }

    #[test]
    fn new_finding_is_introduced_even_when_a_rule_revision_changed() {
        let baseline = baseline_with(&[]);
        let current = [finding("new", "src/a.rs")];

        let mut revised = current_revisions();
        revised.insert("duplicate-code".to_string(), 2);
        let delta = diff(&current, &baseline, &HashSet::new(), &revised);

        assert_eq!(delta.introduced.len(), 1);
        assert!(delta.rule_introduced.is_empty());
        assert_eq!(delta.verdict(), Verdict::Fail);
    }

    #[test]
    fn finding_missing_from_the_current_run_is_resolved() {
        let baseline = baseline_with(&[finding("gone", "src/a.rs")]);

        let delta = diff(&[], &baseline, &HashSet::new(), &current_revisions());

        assert_eq!(delta.resolved.len(), 1);
        assert_eq!(delta.resolved[0].id, "gone");
    }

    #[test]
    fn new_finding_without_a_rule_change_fails_even_in_an_untouched_file() {
        let baseline = baseline_with(&[]);
        let current = [finding("new", "src/a.rs")];

        let delta = diff(&current, &baseline, &HashSet::new(), &current_revisions());

        assert_eq!(delta.code_introduced.len(), 1);
        assert!(delta.rule_introduced.is_empty());
        assert_eq!(delta.verdict(), Verdict::Fail);
    }

    #[test]
    fn changed_rule_keeps_an_identical_finding_unchanged() {
        let baseline = baseline_with(&[finding("known", "src/a.rs")]);
        let current = [finding("known", "src/a.rs")];
        let revised = HashMap::from([("duplicate-code".to_string(), 2)]);

        let delta = diff(&current, &baseline, &HashSet::new(), &revised);

        assert_eq!(delta.unchanged_count, 1);
        assert!(delta.rule_introduced.is_empty());
    }

    #[test]
    fn informational_code_finding_does_not_fail_the_verdict() {
        let baseline = baseline_with(&[]);
        let mut info = finding("info", "src/a.rs");
        info.severity = Severity::Info;
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(&[info], &baseline, &touched, &current_revisions());

        assert_eq!(delta.code_introduced.len(), 1);
        assert_eq!(delta.verdict(), Verdict::Pass);
    }

    #[test]
    fn tri_verdict_is_warn_for_warn_only_code_introduced_findings() {
        let baseline = baseline_with(&[]);
        let current = [finding("new", "src/a.rs")];
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(&current, &baseline, &touched, &current_revisions());

        assert_eq!(delta.tri_verdict(), TriVerdict::Warn);
    }

    #[test]
    fn tri_verdict_is_fail_when_any_code_introduced_finding_fails() {
        let baseline = baseline_with(&[]);
        let mut fail = finding("fail", "src/a.rs");
        fail.severity = Severity::Fail;
        let warn = finding("warn", "src/a.rs");
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(&[fail, warn], &baseline, &touched, &current_revisions());

        assert_eq!(delta.tri_verdict(), TriVerdict::Fail);
    }

    #[test]
    fn heuristic_code_introduced_findings_are_advisory_and_do_not_fail() {
        // A new heuristic finding in a touched file still classifies as
        // code-introduced (it stays visible in the delta), but it can't
        // gate: heuristics are advisory by default (todo.md §17.2, §17.5).
        let baseline = baseline_with(&[]);
        let mut heuristic_fail = finding("hotspot:src/a.rs", "src/a.rs");
        heuristic_fail.rule = "hotspot".into();
        heuristic_fail.severity = Severity::Fail;
        heuristic_fail.evidence_class = EvidenceClass::Heuristic;
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(&[heuristic_fail], &baseline, &touched, &current_revisions());

        assert_eq!(delta.code_introduced.len(), 1);
        assert_eq!(delta.verdict(), Verdict::Pass);
        assert_eq!(delta.tri_verdict(), TriVerdict::Pass);
    }

    #[test]
    fn gating_fail_still_fails_alongside_advisory_findings() {
        let baseline = baseline_with(&[]);
        let mut derived_fail = finding("fail", "src/a.rs");
        derived_fail.severity = Severity::Fail;
        let mut heuristic = finding("hotspot:src/a.rs", "src/a.rs");
        heuristic.rule = "hotspot".into();
        heuristic.evidence_class = EvidenceClass::Heuristic;
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);

        let delta = diff(
            &[derived_fail, heuristic],
            &baseline,
            &touched,
            &current_revisions(),
        );

        assert_eq!(delta.verdict(), Verdict::Fail);
        assert_eq!(delta.tri_verdict(), TriVerdict::Fail);
    }

    #[test]
    fn tri_verdict_is_pass_for_empty_or_info_only_code_introduced_findings() {
        let baseline = baseline_with(&[]);
        assert_eq!(
            diff(&[], &baseline, &HashSet::new(), &current_revisions()).tri_verdict(),
            TriVerdict::Pass
        );

        let mut info = finding("info", "src/a.rs");
        info.severity = Severity::Info;
        let touched = HashSet::from([PathBuf::from("src/a.rs")]);
        let delta = diff(&[info], &baseline, &touched, &current_revisions());

        assert_eq!(delta.tri_verdict(), TriVerdict::Pass);
    }
}